diff --git a/README.md b/README.md index 5721f3d..deec33c 100644 --- a/README.md +++ b/README.md @@ -420,6 +420,12 @@ status: lastJob: name: karkive-backup-app-postgres-29781240 outcome: Succeeded # or Failed, with reason and message + lastObject: # Stream Backups: the dump the last successful Job stored + key: app/pgdump/pg_dump-app-2026-11-20-02-00-03.dump.gpg + sizeBytes: 1677721 + durationSeconds: 4 + jobName: karkive-backup-app-postgres-29781240 + completionTime: "2026-11-20T02:04:12Z" conditions: - type: Ready status: "True" @@ -436,6 +442,8 @@ kubectl describe backup app-postgres -n backup Print columns: engine, schedule, phase, Succeeded, last success (Backup only) and last Job outcome. +`status.lastObject` is set by Stream Backups only. The pod writes the object key, size and duration to its termination message; the operator copies it from the successful pod of the last finished Job, so it needs `get`/`list` on pods. A failed Job, or a Job whose pods are already gone, leaves the previous object in place. The key is `/`, or `retained/` on the volume when S3 is off. + ## Monitoring The chart exposes `/metrics` on a ClusterIP Service (`:8080`) and `/healthz` + `/readyz` on `:8081`. @@ -451,12 +459,15 @@ Custom series exist for both kinds (`karkive_backup_*` and `karkive_restore_*`), | `…_last_job_failed` | `1` when the last finished Job failed | | `…_last_job_duration_seconds` | Wall time of the last finished Job | | `…_last_job_info` | Always `1`; labels `outcome`, `reason`, `job_name` | +| `karkive_backup_last_size_bytes` | Size of the object in `status.lastObject` (Stream Backups; absent until one is recorded) | +| `karkive_backup_last_object_timestamp_seconds` | When the Job that stored that object finished | Alerts (with `metrics.prometheusRule.enabled=true`): - CR not Ready for 15m - Last Job failed - Backup's last success older than `backupAgingSeconds` (default 8h), and stale past `backupStaleSeconds` (default 36h); suspended Backups are skipped +- Backup's last object below `backupSizeDropRatio` (default `0.5`) of the largest one in `backupSizeDropWindow` (default `7d`): often an empty or partial dump. `0` turns it off - CronJob has scheduled but no Job has finished - Missed CronJob schedule (needs kube-state-metrics) diff --git a/TODO.md b/TODO.md index 5a45221..187d695 100644 --- a/TODO.md +++ b/TODO.md @@ -8,7 +8,7 @@ - [ ] Postgres restore without scratch: `pg_restore --jobs` needs a seekable file, so the decrypted dump lands on the volume once. Stream straight into `pg_restore` when `jobs: 1`, and size the volume from the last object size otherwise (needs `status.lastObject` and `backupRef`) - [ ] MariaDB parallel dump/restore with `mydumper` / `myloader` (per-table files, zstd) behind `jobs > 1` -- [ ] Record the last object in `status.lastObject` (key, size, checksum, duration, compression ratio) and expose `karkive_backup_last_size_bytes`; alert on a sudden size drop. A Restore can default to it +- [ ] `status.lastObject` follow-ups: add the checksum (with upload verification below) and the compression ratio, and let a Restore default to it (needs `backupRef`) - [ ] Verify each upload: `rclone check --download` of the object against a sha256 computed in the pipe (`tee >(sha256sum)`), stored in the `.meta` sidecar - [ ] Bandwidth and IO limits for big dumps (`rclone --bwlimit`, `ionice`, `pg_dump --jobs` capped by DB CPU) so a backup does not starve the primary; prefer a read replica host (`spec.database.readHost`) - [ ] Continuous archiving for Postgres (WAL via the CNPG Barman/plugin path) for point-in-time recovery; keep logical dumps for portability @@ -126,6 +126,7 @@ - [x] Per-engine runner images, built in CI only when `runner//` changes - [x] Encrypt with `age` (X25519 public key) instead of symmetric gpg: Backups hold only the public key, Restores hold the private key; also faster than gpg on large streams. Covers public-key encryption, so no GPG keypair mode is planned - [x] `Stream` is the default `spec.pipeline.mode`; `Stage` stays available as an opt-in +- [x] `status.lastObject` on Stream Backups (key, size, duration, Job, completion time): the pod writes it to its termination message and the operator reads it from the successful pod of the last finished Job; a failed Job or a deleted pod keeps the previous object. Exposed as `karkive_backup_last_size_bytes` and `karkive_backup_last_object_timestamp_seconds`, with alert `KArkiveBackupSizeDrop` (below half the largest object of the last 7 days by default) ### API and controller diff --git a/api/v1alpha1/backup_types.go b/api/v1alpha1/backup_types.go index d265054..b49c5f8 100644 --- a/api/v1alpha1/backup_types.go +++ b/api/v1alpha1/backup_types.go @@ -160,6 +160,9 @@ type BackupStatus struct { // LastJob is the most recently finished Job, including failure reason. LastJob *LastJobStatus `json:"lastJob,omitempty"` + // LastObject is the dump written by the most recent successful Job (Stream mode). A failed Job leaves it unchanged. + LastObject *LastObjectStatus `json:"lastObject,omitempty"` + // Conditions of the Backup. Ready is admission/sync of owned resources. // BackupSucceeded is the last finished Job (Unknown until one exists). // +listType=map diff --git a/api/v1alpha1/common_types.go b/api/v1alpha1/common_types.go index 446e360..e37c6c1 100644 --- a/api/v1alpha1/common_types.go +++ b/api/v1alpha1/common_types.go @@ -339,3 +339,21 @@ type LastJobStatus struct { // CompletionTime when the Job finished (or the condition transition time). CompletionTime *metav1.Time `json:"completionTime,omitempty"` } + +// LastObjectStatus is the dump the most recent successful Backup Job wrote, as reported by its pod (Stream mode). +type LastObjectStatus struct { + // Key of the object: / in the bucket, or retained/ on the volume when S3 is off. + Key string `json:"key,omitempty"` + + // SizeBytes of the stored (compressed and encrypted) object. + SizeBytes int64 `json:"sizeBytes,omitempty"` + + // DurationSeconds of dump, compress, encrypt and upload together. + DurationSeconds int64 `json:"durationSeconds,omitempty"` + + // JobName of the Job that wrote the object. + JobName string `json:"jobName,omitempty"` + + // CompletionTime of that Job. + CompletionTime *metav1.Time `json:"completionTime,omitempty"` +} diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 4055ede..cdbe41b 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -222,6 +222,11 @@ func (in *BackupStatus) DeepCopyInto(out *BackupStatus) { *out = new(LastJobStatus) (*in).DeepCopyInto(*out) } + if in.LastObject != nil { + in, out := &in.LastObject, &out.LastObject + *out = new(LastObjectStatus) + (*in).DeepCopyInto(*out) + } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]metav1.Condition, len(*in)) @@ -414,6 +419,25 @@ func (in *LastJobStatus) DeepCopy() *LastJobStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *LastObjectStatus) DeepCopyInto(out *LastObjectStatus) { + *out = *in + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LastObjectStatus. +func (in *LastObjectStatus) DeepCopy() *LastObjectStatus { + if in == nil { + return nil + } + out := new(LastObjectStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PVCSourceSpec) DeepCopyInto(out *PVCSourceSpec) { *out = *in diff --git a/charts/karkive/templates/crd-karkive.io_backups.yaml b/charts/karkive/templates/crd-karkive.io_backups.yaml index 2f7995e..cf96533 100644 --- a/charts/karkive/templates/crd-karkive.io_backups.yaml +++ b/charts/karkive/templates/crd-karkive.io_backups.yaml @@ -1018,6 +1018,32 @@ spec: format: date-time type: string type: object + lastObject: + description: LastObject is the dump written by the most recent successful + Job (Stream mode). A failed Job leaves it unchanged. + properties: + completionTime: + description: CompletionTime of that Job. + format: date-time + type: string + durationSeconds: + description: DurationSeconds of dump, compress, encrypt and upload + together. + format: int64 + type: integer + jobName: + description: JobName of the Job that wrote the object. + type: string + key: + description: 'Key of the object: / in the + bucket, or retained/ on the volume when S3 is off.' + type: string + sizeBytes: + description: SizeBytes of the stored (compressed and encrypted) + object. + format: int64 + type: integer + type: object lastScheduleTime: description: LastScheduleTime copied from the CronJob. format: date-time diff --git a/charts/karkive/templates/prometheusrule.yaml b/charts/karkive/templates/prometheusrule.yaml index 6719162..3f1e584 100644 --- a/charts/karkive/templates/prometheusrule.yaml +++ b/charts/karkive/templates/prometheusrule.yaml @@ -97,4 +97,17 @@ spec: annotations: summary: CronJob {{`{{ $labels.namespace }}`}}/{{`{{ $labels.cronjob }}`}} missed its next schedule description: Requires kube-state-metrics. The next_schedule_time is more than {{ .Values.metrics.prometheusRule.missedScheduleGraceSeconds }}s in the past. + {{- with .Values.metrics.prometheusRule.backupSizeDropRatio }} + - alert: KArkiveBackupSizeDrop + # Compares the newest object with the largest one of the window. Only Stream Backups report a size. A dump that shrinks this much is often empty or partial (wrong database, lost permissions, truncated tables). + expr: |- + karkive_backup_last_size_bytes + < {{ . }} * max_over_time(karkive_backup_last_size_bytes[{{ $.Values.metrics.prometheusRule.backupSizeDropWindow }}]) + for: 15m + labels: + severity: warning + annotations: + summary: Backup {{`{{ $labels.namespace }}`}}/{{`{{ $labels.name }}`}} is much smaller than before + description: The last stored object is {{`{{ $value | humanize1024 }}`}}B, below {{ . }} times the largest one in the last {{ $.Values.metrics.prometheusRule.backupSizeDropWindow }} (engine={{`{{ $labels.engine }}`}}). Check that the dump is complete. + {{- end }} {{- end }} diff --git a/charts/karkive/templates/rbac.yaml b/charts/karkive/templates/rbac.yaml index ec6473c..04ddb8e 100644 --- a/charts/karkive/templates/rbac.yaml +++ b/charts/karkive/templates/rbac.yaml @@ -29,6 +29,9 @@ rules: - apiGroups: [""] resources: ["secrets"] verbs: ["get", "list", "watch"] + - apiGroups: [""] + resources: ["pods"] + verbs: ["get", "list"] - apiGroups: [""] resources: ["events"] verbs: ["create", "patch"] diff --git a/charts/karkive/values.yaml b/charts/karkive/values.yaml index fd64846..f1b2872 100644 --- a/charts/karkive/values.yaml +++ b/charts/karkive/values.yaml @@ -91,6 +91,9 @@ metrics: # Dashboard red: no success within this many seconds (default 36h). backupStaleSeconds: 129600 missedScheduleGraceSeconds: 1800 + # KArkiveBackupSizeDrop fires when the last stored object (karkive_backup_last_size_bytes, Stream Backups) is below this fraction of the largest one in backupSizeDropWindow. Empty or 0 turns the alert off. + backupSizeDropRatio: 0.5 + backupSizeDropWindow: 7d grafanaDashboard: enabled: false labels: diff --git a/cmd/main.go b/cmd/main.go index d8078fb..67dcfc1 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -112,10 +112,11 @@ func main() { } if err := (&controller.BackupReconciler{ - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - Recorder: mgr.GetEventRecorderFor("backup-controller"), - Config: cfg, + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + Recorder: mgr.GetEventRecorderFor("backup-controller"), + Config: cfg, + APIReader: mgr.GetAPIReader(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Backup") os.Exit(1) diff --git a/config/crd/bases/karkive.io_backups.yaml b/config/crd/bases/karkive.io_backups.yaml index 4014c09..20e20cd 100644 --- a/config/crd/bases/karkive.io_backups.yaml +++ b/config/crd/bases/karkive.io_backups.yaml @@ -1017,6 +1017,32 @@ spec: format: date-time type: string type: object + lastObject: + description: LastObject is the dump written by the most recent successful + Job (Stream mode). A failed Job leaves it unchanged. + properties: + completionTime: + description: CompletionTime of that Job. + format: date-time + type: string + durationSeconds: + description: DurationSeconds of dump, compress, encrypt and upload + together. + format: int64 + type: integer + jobName: + description: JobName of the Job that wrote the object. + type: string + key: + description: 'Key of the object: / in the + bucket, or retained/ on the volume when S3 is off.' + type: string + sizeBytes: + description: SizeBytes of the stored (compressed and encrypted) + object. + format: int64 + type: integer + type: object lastScheduleTime: description: LastScheduleTime copied from the CronJob. format: date-time diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 14288e7..b078bff 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -24,6 +24,13 @@ rules: verbs: - create - patch +- apiGroups: + - "" + resources: + - pods + verbs: + - get + - list - apiGroups: - "" resources: diff --git a/internal/controller/backup_controller.go b/internal/controller/backup_controller.go index 5ed6f4f..a2273df 100644 --- a/internal/controller/backup_controller.go +++ b/internal/controller/backup_controller.go @@ -48,6 +48,15 @@ type BackupReconciler struct { Scheme *runtime.Scheme Recorder record.EventRecorder Config config.Config + // APIReader reads Job pods for status.lastObject without caching every pod. Nil falls back to Client (tests). + APIReader client.Reader +} + +func (r *BackupReconciler) podReader() client.Reader { + if r.APIReader != nil { + return r.APIReader + } + return r.Client } // +kubebuilder:rbac:groups=karkive.io,resources=backups,verbs=get;list;watch;create;update;patch;delete @@ -60,6 +69,7 @@ type BackupReconciler struct { // +kubebuilder:rbac:groups=core,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch // +kubebuilder:rbac:groups=core,resources=events,verbs=create;patch +// +kubebuilder:rbac:groups=core,resources=pods,verbs=get;list func (r *BackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { res, err := r.reconcile(ctx, req) @@ -237,6 +247,12 @@ func (r *BackupReconciler) setStatus( phaseChanged := backup.Status.Phase != phase newLastJob := lastJobStatus(ctx, r.Client, backup.Namespace, resources.LabelBackupName, backup.Name, resources.KindBackup) lastJobChanged := !lastJobEqual(backup.Status.LastJob, newLastJob) + newLastObject := backup.Status.LastObject + if resources.IsStreamBackup(backup) { + newLastObject = lastObjectStatus(ctx, r.podReader(), backup.Namespace, backup.Status.LastObject, newLastJob) + } + lastObjectChanged := !lastObjectEqual(backup.Status.LastObject, newLastObject) + backup.Status.LastObject = newLastObject cronChanged := false if cron != nil { @@ -266,7 +282,7 @@ func (r *BackupReconciler) setStatus( if r.Recorder != nil && shouldRecordEvent(eventType, specChanged, phaseChanged, readyChanged) { r.Recorder.Event(backup, eventType, reason, message) } - if !statusNeedsPatch(specChanged, phaseChanged, condChanged, lastJobChanged, cronChanged || holderChanged) { + if !statusNeedsPatch(specChanged, phaseChanged, condChanged, lastJobChanged || lastObjectChanged, cronChanged || holderChanged) { return nil } return r.Status().Update(ctx, backup) diff --git a/internal/controller/last_object.go b/internal/controller/last_object.go new file mode 100644 index 0000000..1c04f33 --- /dev/null +++ b/internal/controller/last_object.go @@ -0,0 +1,77 @@ +package controller + +import ( + "bufio" + "context" + "strconv" + "strings" + + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/log" + + karkivev1alpha1 "github.com/mahdidarabi/KArkive/api/v1alpha1" +) + +// streamContainerName is the single container of a Stream Job; its termination message reports the stored object. +const streamContainerName = "stream" + +// lastObjectStatus returns status.lastObject for a Stream Backup. It reads the termination message of the pod that succeeded in the last finished Job, and only when that Job succeeded and is not the one prev already describes. In every other case (failed Job, pod already deleted, a runner that does not report) it keeps prev. +// The pod is read through reader, an uncached client, so the operator does not keep an informer on every pod in the cluster for one lookup per run. +func lastObjectStatus(ctx context.Context, reader client.Reader, namespace string, prev *karkivev1alpha1.LastObjectStatus, job *karkivev1alpha1.LastJobStatus) *karkivev1alpha1.LastObjectStatus { + if job == nil || job.Outcome != karkivev1alpha1.LastJobOutcomeSucceeded || job.Name == "" { + return prev + } + if prev != nil && prev.JobName == job.Name { + return prev + } + pods := &corev1.PodList{} + if err := reader.List(ctx, pods, client.InNamespace(namespace), client.MatchingLabels{batchv1.JobNameLabel: job.Name}); err != nil { + log.FromContext(ctx).Info("cannot list pods of the last Job; keeping status.lastObject", "job", job.Name, "error", err.Error()) + return prev + } + for i := range pods.Items { + for _, cs := range pods.Items[i].Status.ContainerStatuses { + term := cs.State.Terminated + if cs.Name != streamContainerName || term == nil || term.ExitCode != 0 { + continue + } + key, size, duration, ok := parseObjectReport(term.Message) + if !ok { + continue + } + return &karkivev1alpha1.LastObjectStatus{ + Key: key, + SizeBytes: size, + DurationSeconds: duration, + JobName: job.Name, + CompletionTime: job.CompletionTime, + } + } + } + return prev +} + +// parseObjectReport reads the key=value lines report_object (scripts/stream/common.sh) writes: object, size and duration. Unknown keys are ignored; object and a positive size are required. +func parseObjectReport(msg string) (key string, size, duration int64, ok bool) { + sc := bufio.NewScanner(strings.NewReader(msg)) + for sc.Scan() { + k, v, found := strings.Cut(strings.TrimSpace(sc.Text()), "=") + if !found { + continue + } + switch k { + case "object": + key = v + case "size": + size, _ = strconv.ParseInt(v, 10, 64) + case "duration": + duration, _ = strconv.ParseInt(v, 10, 64) + } + } + if duration < 0 { + duration = 0 + } + return key, size, duration, key != "" && size > 0 +} diff --git a/internal/controller/last_object_test.go b/internal/controller/last_object_test.go new file mode 100644 index 0000000..b24f679 --- /dev/null +++ b/internal/controller/last_object_test.go @@ -0,0 +1,186 @@ +package controller + +import ( + "context" + "testing" + "time" + + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/record" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/reconcile" + + karkivev1alpha1 "github.com/mahdidarabi/KArkive/api/v1alpha1" + "github.com/mahdidarabi/KArkive/internal/resources" +) + +func TestParseObjectReport(t *testing.T) { + for _, tc := range []struct { + msg string + key string + size int64 + duration int64 + ok bool + }{ + {"object=app/pgdump/pg_dump-app-1.dump.gpg\nsize=1677721\nduration=4\n", "app/pgdump/pg_dump-app-1.dump.gpg", 1677721, 4, true}, + {"size=10\nobject=retained/x.age\n", "retained/x.age", 10, 0, true}, + {"object=a\nsize=0\nduration=3\n", "a", 0, 3, false}, + {"object=a\nsize=abc\n", "a", 0, 0, false}, + {"size=10\n", "", 10, 0, false}, + {"object=a\nsize=10\nduration=-5\nextra=1\n", "a", 10, 0, true}, + {"", "", 0, 0, false}, + } { + key, size, duration, ok := parseObjectReport(tc.msg) + if key != tc.key || size != tc.size || duration != tc.duration || ok != tc.ok { + t.Errorf("%q: got (%q, %d, %d, %v), want (%q, %d, %d, %v)", tc.msg, key, size, duration, ok, tc.key, tc.size, tc.duration, tc.ok) + } + } +} + +func streamBackupFixture() (*karkivev1alpha1.Backup, *corev1.Secret) { + backup := &karkivev1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "app-postgres", Namespace: "backup"}, + Spec: karkivev1alpha1.BackupSpec{ + Engine: karkivev1alpha1.EnginePostgres, + Schedule: "0 2 * * *", + Database: karkivev1alpha1.DatabaseSpec{Host: "postgres.example.svc.cluster.local", Name: "app"}, + S3: karkivev1alpha1.S3Spec{Endpoint: "https://s3.example.com", Bucket: "backups", Path: "app/pgdump"}, + SecretRef: corev1.LocalObjectReference{Name: "backup-creds"}, + }, + } + secret := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "backup-creds", Namespace: "backup"}, + Data: map[string][]byte{ + "username": []byte("app"), "password": []byte("secret"), + "s3_access_key": []byte("ak"), "s3_secret_key": []byte("sk"), "gpg_passphrase": []byte("pgp"), + }, + } + return backup, secret +} + +func backupJob(name string, failed bool, finished time.Time) *batchv1.Job { + at := metav1.NewTime(finished) + start := metav1.NewTime(finished.Add(-time.Minute)) + job := &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: "backup", + Labels: map[string]string{ + resources.LabelAppManagedBy: resources.ManagedBy, + resources.LabelKind: resources.KindBackup, + resources.LabelBackupName: "app-postgres", + }, + }, + Status: batchv1.JobStatus{StartTime: &start}, + } + if failed { + job.Status.Failed = 1 + job.Status.Conditions = []batchv1.JobCondition{{Type: batchv1.JobFailed, Status: corev1.ConditionTrue, Reason: "BackoffLimitExceeded", LastTransitionTime: at}} + } else { + job.Status.Succeeded = 1 + job.Status.CompletionTime = &at + } + return job +} + +func jobPod(job, name string, exitCode int32, message string) *corev1.Pod { + return &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: "backup", Labels: map[string]string{batchv1.JobNameLabel: job}}, + Status: corev1.PodStatus{ContainerStatuses: []corev1.ContainerStatus{{ + Name: streamContainerName, + State: corev1.ContainerState{Terminated: &corev1.ContainerStateTerminated{ExitCode: exitCode, Message: message}}, + }}}, + } +} + +func reconcileBackup(t *testing.T, c client.Client) *karkivev1alpha1.Backup { + t.Helper() + r := &BackupReconciler{Client: c, Scheme: c.Scheme(), Recorder: record.NewFakeRecorder(16)} + key := types.NamespacedName{Name: "app-postgres", Namespace: "backup"} + if _, err := r.Reconcile(context.Background(), reconcile.Request{NamespacedName: key}); err != nil { + t.Fatal(err) + } + got := &karkivev1alpha1.Backup{} + if err := c.Get(context.Background(), key, got); err != nil { + t.Fatal(err) + } + return got +} + +func TestBackupReconcile_RecordsLastObjectFromStreamPod(t *testing.T) { + scheme := testScheme(t) + backup, secret := streamBackupFixture() + finished := time.Unix(1_800_000_000, 0) + job := backupJob("karkive-backup-app-postgres-1", false, finished) + // A retry pod that failed after reporting a partial object, then the pod that succeeded: only the successful one counts. + failedPod := jobPod(job.Name, "karkive-backup-app-postgres-1-aaaaa", 1, "object=app/pgdump/partial.dump.gpg\nsize=5\nduration=1\n") + okPod := jobPod(job.Name, "karkive-backup-app-postgres-1-bbbbb", 0, "object=app/pgdump/pg_dump-app-2027-01-15-08-00-00.dump.gpg\nsize=1677721\nduration=4\n") + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(backup, secret, job, failedPod, okPod). + WithStatusSubresource(&karkivev1alpha1.Backup{}).Build() + + got := reconcileBackup(t, c).Status.LastObject + if got == nil { + t.Fatal("expected status.lastObject") + } + if got.Key != "app/pgdump/pg_dump-app-2027-01-15-08-00-00.dump.gpg" || got.SizeBytes != 1677721 || got.DurationSeconds != 4 || got.JobName != job.Name { + t.Errorf("lastObject=%+v", got) + } + if got.CompletionTime == nil || !got.CompletionTime.Time.Equal(finished) { + t.Errorf("completionTime=%v, want %v", got.CompletionTime, finished) + } +} + +func TestBackupReconcile_FailedJobKeepsLastObject(t *testing.T) { + scheme := testScheme(t) + backup, secret := streamBackupFixture() + prev := &karkivev1alpha1.LastObjectStatus{Key: "app/pgdump/old.dump.gpg", SizeBytes: 100, JobName: "karkive-backup-app-postgres-0"} + backup.Status.LastObject = prev + job := backupJob("karkive-backup-app-postgres-1", true, time.Unix(1_800_000_000, 0)) + // Even a pod that reported an object must not count when the Job failed. + pod := jobPod(job.Name, "karkive-backup-app-postgres-1-aaaaa", 0, "object=app/pgdump/new.dump.gpg\nsize=5\n") + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(backup, secret, job, pod). + WithStatusSubresource(&karkivev1alpha1.Backup{}).Build() + + got := reconcileBackup(t, c).Status.LastObject + if got == nil || got.Key != prev.Key || got.SizeBytes != prev.SizeBytes { + t.Errorf("lastObject=%+v, want the previous object", got) + } +} + +func TestBackupReconcile_LastObjectSurvivesPodCleanup(t *testing.T) { + scheme := testScheme(t) + backup, secret := streamBackupFixture() + job := backupJob("karkive-backup-app-postgres-1", false, time.Unix(1_800_000_000, 0)) + // Recorded from an older Job; the new Job's pods are already gone (TTL or history limit), so nothing replaces it. + prev := &karkivev1alpha1.LastObjectStatus{Key: "app/pgdump/x.dump.gpg", SizeBytes: 42, JobName: "karkive-backup-app-postgres-0"} + backup.Status.LastObject = prev + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(backup, secret, job). + WithStatusSubresource(&karkivev1alpha1.Backup{}).Build() + + got := reconcileBackup(t, c).Status.LastObject + if got == nil || got.Key != prev.Key || got.SizeBytes != 42 { + t.Errorf("lastObject=%+v, want the recorded object", got) + } +} + +func TestBackupReconcile_StageModeHasNoLastObject(t *testing.T) { + scheme := testScheme(t) + backup, secret := streamBackupFixture() + backup.Spec.Pipeline = &karkivev1alpha1.PipelineSpec{Mode: karkivev1alpha1.PipelineModeStage} + job := backupJob("karkive-backup-app-postgres-1", false, time.Unix(1_800_000_000, 0)) + pod := jobPod(job.Name, "karkive-backup-app-postgres-1-aaaaa", 0, "object=a\nsize=5\n") + c := fake.NewClientBuilder().WithScheme(scheme). + WithObjects(backup, secret, job, pod). + WithStatusSubresource(&karkivev1alpha1.Backup{}).Build() + + if got := reconcileBackup(t, c).Status.LastObject; got != nil { + t.Errorf("Stage mode lastObject=%+v, want nil", got) + } +} diff --git a/internal/controller/status.go b/internal/controller/status.go index 129ead8..24239c0 100644 --- a/internal/controller/status.go +++ b/internal/controller/status.go @@ -15,6 +15,10 @@ func lastJobEqual(a, b *karkivev1alpha1.LastJobStatus) bool { return equality.Semantic.DeepEqual(a, b) } +func lastObjectEqual(a, b *karkivev1alpha1.LastObjectStatus) bool { + return equality.Semantic.DeepEqual(a, b) +} + func metaTimeEqual(a, b *metav1.Time) bool { return equality.Semantic.DeepEqual(a, b) } diff --git a/internal/metrics/collector.go b/internal/metrics/collector.go index 039e952..fe2c392 100644 --- a/internal/metrics/collector.go +++ b/internal/metrics/collector.go @@ -58,6 +58,18 @@ var ( []string{"namespace", "name", "engine", "outcome", "reason", "job_name"}, nil, ) + backupLastSizeDesc = prometheus.NewDesc( + "karkive_backup_last_size_bytes", + "Size in bytes of the object the most recent successful Job stored (status.lastObject, Stream mode). Absent until one is recorded.", + []string{"namespace", "name", "engine"}, + nil, + ) + backupLastObjectTimeDesc = prometheus.NewDesc( + "karkive_backup_last_object_timestamp_seconds", + "Unix time the Job that stored status.lastObject finished. Absent until one is recorded.", + []string{"namespace", "name", "engine"}, + nil, + ) restoreReadyDesc = prometheus.NewDesc( "karkive_restore_ready", @@ -123,6 +135,8 @@ func (c *Collector) Describe(ch chan<- *prometheus.Desc) { ch <- backupLastJobFailedDesc ch <- backupLastJobDurationDesc ch <- backupLastJobInfoDesc + ch <- backupLastSizeDesc + ch <- backupLastObjectTimeDesc ch <- restoreReadyDesc ch <- restoreSuspendedDesc ch <- restoreLastScheduleDesc @@ -172,6 +186,13 @@ func (c *Collector) collectBackup(ch chan<- prometheus.Metric, backup *karkivev1 st = jobstatus.Summarize(jobstatus.LastFinished(jobs, backup.Namespace, resources.LabelBackupName, backup.Name, resources.KindBackup)) } emitLastJob(ch, st, backupLastJobFailedDesc, backupLastJobDurationDesc, backupLastJobInfoDesc, labels) + + if obj := backup.Status.LastObject; obj != nil && obj.SizeBytes > 0 { + ch <- gauge(backupLastSizeDesc, float64(obj.SizeBytes), labels) + if t := unixTime(obj.CompletionTime); t > 0 { + ch <- gauge(backupLastObjectTimeDesc, t, labels) + } + } } func (c *Collector) collectRestore(ch chan<- prometheus.Metric, restore *karkivev1alpha1.Restore, jobs []batchv1.Job) { diff --git a/internal/metrics/collector_test.go b/internal/metrics/collector_test.go index e4ec8c2..5fdfef9 100644 --- a/internal/metrics/collector_test.go +++ b/internal/metrics/collector_test.go @@ -323,3 +323,56 @@ func TestCollector_NoSeriesWithoutCRs(t *testing.T) { } } } + +func TestCollector_LastObjectSize(t *testing.T) { + scheme := runtime.NewScheme() + if err := karkivev1alpha1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + if err := batchv1.AddToScheme(scheme); err != nil { + t.Fatal(err) + } + done := metav1.NewTime(time.Unix(1_800_000_000, 0)) + withObject := &karkivev1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "app-postgres", Namespace: "backup"}, + Spec: karkivev1alpha1.BackupSpec{Engine: karkivev1alpha1.EnginePostgres}, + Status: karkivev1alpha1.BackupStatus{LastObject: &karkivev1alpha1.LastObjectStatus{ + Key: "app/pgdump/pg_dump-app-1.dump.gpg", SizeBytes: 1677721, JobName: "job-1", CompletionTime: &done, + }}, + } + without := &karkivev1alpha1.Backup{ + ObjectMeta: metav1.ObjectMeta{Name: "fresh", Namespace: "backup"}, + Spec: karkivev1alpha1.BackupSpec{Engine: karkivev1alpha1.EngineRedis}, + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(withObject, without).Build() + reg := prometheus.NewPedanticRegistry() + reg.MustRegister(&Collector{Client: c}) + fams, err := reg.Gather() + if err != nil { + t.Fatal(err) + } + got := map[string]map[string]float64{} + for _, fam := range fams { + for _, m := range fam.Metric { + for _, name := range []string{"app-postgres", "fresh"} { + if match(m, "backup", name) { + if got[name] == nil { + got[name] = map[string]float64{} + } + got[name][fam.GetName()] = m.GetGauge().GetValue() + } + } + } + } + if v := got["app-postgres"]["karkive_backup_last_size_bytes"]; v != 1677721 { + t.Errorf("last_size_bytes=%v", v) + } + if v := got["app-postgres"]["karkive_backup_last_object_timestamp_seconds"]; v != float64(done.Unix()) { + t.Errorf("last_object_timestamp=%v", v) + } + for _, metric := range []string{"karkive_backup_last_size_bytes", "karkive_backup_last_object_timestamp_seconds"} { + if _, ok := got["fresh"][metric]; ok { + t.Errorf("%s must be absent until an object is recorded", metric) + } + } +} diff --git a/internal/pipeline/helpers_test.go b/internal/pipeline/helpers_test.go index 6f8ead0..47a0b90 100644 --- a/internal/pipeline/helpers_test.go +++ b/internal/pipeline/helpers_test.go @@ -210,3 +210,26 @@ echo after`, map[string]string{"RUN_DIR": run}, stubs) t.Errorf("err=%v, output:\n%s", err, out) } } + +func TestStreamReportObjectWritesTerminationMessage(t *testing.T) { + msg := filepath.Join(t.TempDir(), "termination-log") + out, err := runHelpers(t, "bash", streamCommon(t), `report_object "app/pgdump/pg_dump-app-1.dump.gpg" 1677721 4`, map[string]string{"TERMINATION_MESSAGE_PATH": msg}, nil) + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + b, err := os.ReadFile(msg) + if err != nil { + t.Fatal(err) + } + if want := "object=app/pgdump/pg_dump-app-1.dump.gpg\nsize=1677721\nduration=4\n"; string(b) != want { + t.Errorf("got %q, want %q", b, want) + } +} + +func TestStreamReportObjectIsBestEffort(t *testing.T) { + out, err := runHelpers(t, "bash", streamCommon(t), `report_object key 1 1 +echo after`, map[string]string{"TERMINATION_MESSAGE_PATH": filepath.Join(t.TempDir(), "missing", "termination-log")}, nil) + if err != nil || !strings.Contains(out, "WARN: could not write") || !strings.Contains(out, "after") { + t.Errorf("err=%v, output:\n%s", err, out) + } +} diff --git a/internal/pipeline/scripts/stream/backup.sh b/internal/pipeline/scripts/stream/backup.sh index 8577ece..ed5c704 100644 --- a/internal/pipeline/scripts/stream/backup.sh +++ b/internal/pipeline/scripts/stream/backup.sh @@ -135,6 +135,7 @@ if [ "${s3_enabled}" = true ]; then die "upload of ${NAME} not found after rcat" fi log "uploaded ${NAME} ($(human "${size}")) in $(elapsed "$t")" + report_object "${S3_PATH%/}/${NAME}" "${size}" "$(( $(date +%s) - t ))" if [ -n "${META:-}" ]; then printf '%s\n' "${META}" | rclone rcat "${S3_PREFIX}/${BASE}.meta" || log "WARN: could not upload ${BASE}.meta" fi @@ -149,5 +150,6 @@ else mv "${OUT}.part" "${OUT}" [ -z "${META:-}" ] || printf '%s\n' "${META}" > "${RETAINED}/${BASE}.meta" log "wrote ${OUT} ($(human "$(stat -c %s "${OUT}")")) in $(elapsed "$t")" + report_object "retained/${NAME}" "$(stat -c %s "${OUT}")" "$(( $(date +%s) - t ))" fi log "backup done in $(elapsed "${START}")" diff --git a/internal/pipeline/scripts/stream/common.sh b/internal/pipeline/scripts/stream/common.sh index 9c57f51..5861531 100644 --- a/internal/pipeline/scripts/stream/common.sh +++ b/internal/pipeline/scripts/stream/common.sh @@ -221,3 +221,11 @@ s3_latest() { rclone lsf --files-only --format tp --separator '|' --include "${include}" "${S3_PREFIX}/" \ | sort | tail -n 1 | cut -d'|' -f2- } + +# Tell the operator which object a Backup stored ($1 key, $2 size in bytes, $3 seconds): key=value lines in the container's termination message, which it copies into status.lastObject. Best effort: a backup that is stored does not fail here. +report_object() { + local f="${TERMINATION_MESSAGE_PATH:-/dev/termination-log}" + if ! printf 'object=%s\nsize=%s\nduration=%s\n' "$1" "$2" "$3" 2>/dev/null > "${f}"; then + log "WARN: could not write ${f}; status.lastObject keeps the previous object" + fi +}