|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +package backupcontroller |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "crypto/tls" |
| 7 | + "crypto/x509" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "github.com/minio/minio-go/v7" |
| 14 | + "github.com/minio/minio-go/v7/pkg/credentials" |
| 15 | + corev1 "k8s.io/api/core/v1" |
| 16 | + "k8s.io/apimachinery/pkg/types" |
| 17 | + |
| 18 | + strategyv1alpha1 "github.com/cozystack/cozystack/api/backups/strategy/v1alpha1" |
| 19 | + "github.com/cozystack/cozystack/internal/backupcontroller/mariadbtypes" |
| 20 | +) |
| 21 | + |
| 22 | +const ( |
| 23 | + mariadbSizeProbeTimeout = 30 * time.Second |
| 24 | + |
| 25 | + // Slack around the [created, completed] window of the operator Backup |
| 26 | + // when matching the timestamp mariadb-operator embeds in the dump file |
| 27 | + // name: that timestamp comes from the backup Job pod's clock, not the |
| 28 | + // apiserver's, and is truncated to seconds. |
| 29 | + mariadbSizeProbeClockSkew = time.Minute |
| 30 | +) |
| 31 | + |
| 32 | +type s3ObjectInfo struct { |
| 33 | + Key string |
| 34 | + Size int64 |
| 35 | +} |
| 36 | + |
| 37 | +type s3ObjectLister interface { |
| 38 | + ListObjects(ctx context.Context, bucket, prefix string) ([]s3ObjectInfo, error) |
| 39 | +} |
| 40 | + |
| 41 | +// mariadbArtifactSizeBytes measures the dump mariadb-operator uploaded for |
| 42 | +// mdbBackup. The strategy prefix is shared by every backup of the |
| 43 | +// application, so the dump is identified by the timestamp in its file name |
| 44 | +// falling inside the operator Backup's lifetime. Returns 0 - leaving |
| 45 | +// Artifact.SizeBytes absent - when the object store cannot be read or the |
| 46 | +// window does not match exactly one dump: an unknown size must not be |
| 47 | +// reported as a measured one. |
| 48 | +func (r *BackupJobReconciler) mariadbArtifactSizeBytes( |
| 49 | + ctx context.Context, |
| 50 | + namespace string, |
| 51 | + s3 *strategyv1alpha1.MariaDBS3Template, |
| 52 | + mdbBackup *mariadbtypes.Backup, |
| 53 | + completedAt time.Time, |
| 54 | +) int64 { |
| 55 | + logger := getLogger(ctx) |
| 56 | + ctx, cancel := context.WithTimeout(ctx, mariadbSizeProbeTimeout) |
| 57 | + defer cancel() |
| 58 | + |
| 59 | + newLister := r.newS3ObjectLister |
| 60 | + if newLister == nil { |
| 61 | + newLister = r.newMariaDBMinioLister |
| 62 | + } |
| 63 | + lister, err := newLister(ctx, namespace, s3) |
| 64 | + if err != nil { |
| 65 | + logger.Debug("cannot build S3 client to measure MariaDB backup size", "backup", mdbBackup.Name, "error", err) |
| 66 | + return 0 |
| 67 | + } |
| 68 | + prefix := mariadbOperatorS3Prefix(s3.Prefix) |
| 69 | + objects, err := lister.ListObjects(ctx, s3.Bucket, prefix) |
| 70 | + if err != nil { |
| 71 | + logger.Debug("cannot list MariaDB backup objects to measure size", "backup", mdbBackup.Name, "error", err) |
| 72 | + return 0 |
| 73 | + } |
| 74 | + |
| 75 | + lower := mdbBackup.CreationTimestamp.Add(-mariadbSizeProbeClockSkew) |
| 76 | + upper := completedAt.Add(mariadbSizeProbeClockSkew) |
| 77 | + var matched []s3ObjectInfo |
| 78 | + for _, obj := range objects { |
| 79 | + ts, ok := parseMariaDBLogicalBackupFile(strings.TrimPrefix(obj.Key, prefix)) |
| 80 | + if !ok || ts.Before(lower) || ts.After(upper) { |
| 81 | + continue |
| 82 | + } |
| 83 | + matched = append(matched, obj) |
| 84 | + } |
| 85 | + if len(matched) != 1 { |
| 86 | + logger.Debug("MariaDB backup dump not attributable to a single object; leaving size unset", |
| 87 | + "backup", mdbBackup.Name, "candidates", len(matched)) |
| 88 | + return 0 |
| 89 | + } |
| 90 | + return matched[0].Size |
| 91 | +} |
| 92 | + |
| 93 | +// mariadbOperatorS3Prefix mirrors how mariadb-operator normalises |
| 94 | +// spec.storage.s3.prefix before prepending it to object keys. |
| 95 | +func mariadbOperatorS3Prefix(prefix string) string { |
| 96 | + if prefix == "" || prefix == "/" { |
| 97 | + return "" |
| 98 | + } |
| 99 | + if !strings.HasSuffix(prefix, "/") { |
| 100 | + return prefix + "/" |
| 101 | + } |
| 102 | + return prefix |
| 103 | +} |
| 104 | + |
| 105 | +// parseMariaDBLogicalBackupFile accepts the logical-backup file names |
| 106 | +// mariadb-operator writes, backup.<RFC3339>.sql and |
| 107 | +// backup.<RFC3339>.<compression>.sql, and returns the embedded timestamp. |
| 108 | +func parseMariaDBLogicalBackupFile(name string) (time.Time, bool) { |
| 109 | + parts := strings.Split(name, ".") |
| 110 | + if len(parts) != 3 && len(parts) != 4 { |
| 111 | + return time.Time{}, false |
| 112 | + } |
| 113 | + if parts[0] != "backup" || parts[len(parts)-1] != "sql" { |
| 114 | + return time.Time{}, false |
| 115 | + } |
| 116 | + ts, err := time.Parse(time.RFC3339, parts[1]) |
| 117 | + if err != nil { |
| 118 | + return time.Time{}, false |
| 119 | + } |
| 120 | + return ts, true |
| 121 | +} |
| 122 | + |
| 123 | +type minioObjectLister struct { |
| 124 | + client *minio.Client |
| 125 | +} |
| 126 | + |
| 127 | +func (l *minioObjectLister) ListObjects(ctx context.Context, bucket, prefix string) ([]s3ObjectInfo, error) { |
| 128 | + var out []s3ObjectInfo |
| 129 | + for obj := range l.client.ListObjects(ctx, bucket, minio.ListObjectsOptions{Prefix: prefix}) { |
| 130 | + if obj.Err != nil { |
| 131 | + return nil, obj.Err |
| 132 | + } |
| 133 | + out = append(out, s3ObjectInfo{Key: obj.Key, Size: obj.Size}) |
| 134 | + } |
| 135 | + return out, nil |
| 136 | +} |
| 137 | + |
| 138 | +// newMariaDBMinioLister builds an S3 client from the same Secrets and TLS |
| 139 | +// settings the operator Backup was rendered with, so the controller reads |
| 140 | +// the bucket with the tenant's credentials rather than its own. |
| 141 | +func (r *BackupJobReconciler) newMariaDBMinioLister(ctx context.Context, namespace string, s3 *strategyv1alpha1.MariaDBS3Template) (s3ObjectLister, error) { |
| 142 | + accessKey, err := r.mariadbSecretValue(ctx, namespace, s3.AccessKeyIDSecretKeyRef) |
| 143 | + if err != nil { |
| 144 | + return nil, err |
| 145 | + } |
| 146 | + secretKey, err := r.mariadbSecretValue(ctx, namespace, s3.SecretAccessKeySecretKeyRef) |
| 147 | + if err != nil { |
| 148 | + return nil, err |
| 149 | + } |
| 150 | + var sessionToken string |
| 151 | + if s3.SessionTokenSecretKeyRef != nil { |
| 152 | + if sessionToken, err = r.mariadbSecretValue(ctx, namespace, *s3.SessionTokenSecretKeyRef); err != nil { |
| 153 | + return nil, err |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + opts := &minio.Options{ |
| 158 | + Creds: credentials.NewStaticV4(accessKey, secretKey, sessionToken), |
| 159 | + Region: s3.Region, |
| 160 | + Secure: s3.TLS != nil && s3.TLS.Enabled, |
| 161 | + } |
| 162 | + if opts.Secure && s3.TLS.CASecretKeyRef != nil { |
| 163 | + caPEM, err := r.mariadbSecretValue(ctx, namespace, *s3.TLS.CASecretKeyRef) |
| 164 | + if err != nil { |
| 165 | + return nil, err |
| 166 | + } |
| 167 | + pool, err := x509.SystemCertPool() |
| 168 | + if err != nil { |
| 169 | + pool = x509.NewCertPool() |
| 170 | + } |
| 171 | + if !pool.AppendCertsFromPEM([]byte(caPEM)) { |
| 172 | + return nil, fmt.Errorf("no PEM certificates in Secret %s/%s key %q", namespace, s3.TLS.CASecretKeyRef.Name, s3.TLS.CASecretKeyRef.Key) |
| 173 | + } |
| 174 | + opts.Transport = &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool, MinVersion: tls.VersionTLS12}} |
| 175 | + } |
| 176 | + client, err := minio.New(s3.Endpoint, opts) |
| 177 | + if err != nil { |
| 178 | + return nil, err |
| 179 | + } |
| 180 | + return &minioObjectLister{client: client}, nil |
| 181 | +} |
| 182 | + |
| 183 | +func (r *BackupJobReconciler) mariadbSecretValue(ctx context.Context, namespace string, ref strategyv1alpha1.MariaDBSecretKeySelector) (string, error) { |
| 184 | + secret := &corev1.Secret{} |
| 185 | + if err := r.Get(ctx, types.NamespacedName{Namespace: namespace, Name: ref.Name}, secret); err != nil { |
| 186 | + return "", err |
| 187 | + } |
| 188 | + v, ok := secret.Data[ref.Key] |
| 189 | + if !ok { |
| 190 | + return "", fmt.Errorf("Secret %s/%s has no key %q", namespace, ref.Name, ref.Key) |
| 191 | + } |
| 192 | + return string(v), nil |
| 193 | +} |
0 commit comments