|
1 | 1 | package backup
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "bytes" |
4 | 5 | "context"
|
5 | 6 | "fmt"
|
6 | 7 | "net/url"
|
@@ -117,27 +118,45 @@ func getMongoUri(ctx context.Context, k8sclient client.Client, cr *api.PerconaSe
|
117 | 118 | return "", errors.Wrap(err, "get ssl secret")
|
118 | 119 | }
|
119 | 120 |
|
| 121 | + isCertFileOutdated := func(certData []byte, certFilePath string) (bool, error) { |
| 122 | + _, err := os.Stat(certFilePath) |
| 123 | + if os.IsNotExist(err) { |
| 124 | + return true, nil |
| 125 | + } |
| 126 | + |
| 127 | + fileData, err := os.ReadFile(certFilePath) |
| 128 | + if err != nil { |
| 129 | + return true, err |
| 130 | + } |
| 131 | + |
| 132 | + return !bytes.Equal(fileData, certData), nil |
| 133 | + } |
| 134 | + |
| 135 | + writeCertFileIfOutdated := func(certData []byte, filePath string) error { |
| 136 | + if isCertOutdated, err := isCertFileOutdated(certData, filePath); err != nil { |
| 137 | + return err |
| 138 | + } else if isCertOutdated { |
| 139 | + return os.WriteFile(filePath, certData, 0o600) |
| 140 | + } |
| 141 | + return nil |
| 142 | + } |
| 143 | + |
120 | 144 | tlsKey := sslSecret.Data["tls.key"]
|
121 | 145 | tlsCert := sslSecret.Data["tls.crt"]
|
122 | 146 | tlsPemFile := fmt.Sprintf("/tmp/%s-%s-tls.pem", cr.Namespace, cr.Name)
|
123 |
| - f, err := os.OpenFile(tlsPemFile, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0o600) |
| 147 | + tlsPem := append(tlsKey, tlsCert...) |
| 148 | + |
| 149 | + err = writeCertFileIfOutdated(tlsPem, tlsPemFile) |
124 | 150 | if err != nil {
|
125 |
| - return "", errors.Wrapf(err, "open %s", tlsPemFile) |
126 |
| - } |
127 |
| - defer f.Close() |
128 |
| - if _, err := f.Write(append(tlsKey, tlsCert...)); err != nil { |
129 |
| - return "", errors.Wrapf(err, "write TLS key and certificate to %s", tlsPemFile) |
| 151 | + return "", errors.Wrapf(err, "error checking and writing TLS key and certificate to file %s", tlsPemFile) |
130 | 152 | }
|
131 | 153 |
|
132 | 154 | caCert := sslSecret.Data["ca.crt"]
|
133 | 155 | caCertFile := fmt.Sprintf("/tmp/%s-%s-ca.crt", cr.Namespace, cr.Name)
|
134 |
| - f, err = os.OpenFile(caCertFile, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0o600) |
| 156 | + |
| 157 | + err = writeCertFileIfOutdated(caCert, caCertFile) |
135 | 158 | if err != nil {
|
136 |
| - return "", errors.Wrapf(err, "open %s", caCertFile) |
137 |
| - } |
138 |
| - defer f.Close() |
139 |
| - if _, err := f.Write(caCert); err != nil { |
140 |
| - return "", errors.Wrapf(err, "write CA certificate to %s", caCertFile) |
| 159 | + return "", errors.Wrapf(err, "error checking and writing CA certificate to file %s", tlsPemFile) |
141 | 160 | }
|
142 | 161 |
|
143 | 162 | murl += fmt.Sprintf(
|
|
0 commit comments