Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 `<spec.s3.path>/<name>`, or `retained/<name>` on the volume when S3 is off.

## Monitoring

The chart exposes `/metrics` on a ClusterIP Service (`:8080`) and `/healthz` + `/readyz` on `:8081`.
Expand All @@ -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)

Expand Down
3 changes: 2 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -126,6 +126,7 @@
- [x] Per-engine runner images, built in CI only when `runner/<engine>/` 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

Expand Down
3 changes: 3 additions & 0 deletions api/v1alpha1/backup_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions api/v1alpha1/common_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: <spec.s3.path>/<name> in the bucket, or retained/<name> 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"`
}
24 changes: 24 additions & 0 deletions api/v1alpha1/zz_generated.deepcopy.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions charts/karkive/templates/crd-karkive.io_backups.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: <spec.s3.path>/<name> in the
bucket, or retained/<name> 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
Expand Down
13 changes: 13 additions & 0 deletions charts/karkive/templates/prometheusrule.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
3 changes: 3 additions & 0 deletions charts/karkive/templates/rbac.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list"]
- apiGroups: [""]
resources: ["events"]
verbs: ["create", "patch"]
Expand Down
3 changes: 3 additions & 0 deletions charts/karkive/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 5 additions & 4 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
26 changes: 26 additions & 0 deletions config/crd/bases/karkive.io_backups.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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: <spec.s3.path>/<name> in the
bucket, or retained/<name> 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
Expand Down
7 changes: 7 additions & 0 deletions config/rbac/role.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ rules:
verbs:
- create
- patch
- apiGroups:
- ""
resources:
- pods
verbs:
- get
- list
- apiGroups:
- ""
resources:
Expand Down
18 changes: 17 additions & 1 deletion internal/controller/backup_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down
77 changes: 77 additions & 0 deletions internal/controller/last_object.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading