From 3df908d117b3d7d98e632143be11b2a649d0e1d6 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 10:40:27 -0700 Subject: [PATCH 1/8] Add restic-based backup and restore for PVCs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Introduces three new CRDs and three reconcilers that add VolSync-style backup/restore for TopoLVM PVCs using restic against any S3-compatible object store: - BackupConfig (cluster-scoped singleton) — global S3 endpoint/bucket, credentials + restic password Secret refs, default schedule, retention, selector, and `keepSnapshotAfterBackup` toggle. - PVCBackup (namespaced, per PVC) — backup state machine with phases Idle → Snapshotting → Cloning → Moving → Cleanup → Synced|Failed, an in-process cron, and a manual `.spec.trigger` for on-demand runs. - Restore (namespaced) — provisions a fresh target PVC and mounts a restic mover Job against it. The target PVC is intentionally not owner-referenced so deleting the Restore never drops restored data. Each backup run creates a VolumeSnapshot, a temp PVC cloned from it, and a Job mounting the temp PVC read-only; restic pushes to `s3://[/]/`, giving one repository per source PVC. All children carry owner references, so GC handles cleanup on CR deletion; the reconciler also deletes them in the Cleanup phase at end of each run. The BackupConfig controller watches PVCs, applies selector + per-PVC `topolvm.io/backup*` annotation overrides, creates managed PVCBackup objects, and mirrors both user-authored Secrets into every namespace that has a managed PVC (user-authored PVCBackups are never touched). Wiring: `--enable-backup`, `--restic-image`, `--backup-mover-service- account`, `--controller-namespace` flags on topolvm-controller; new controller.backup.* Helm values block; CRD templates; ClusterRole additions for jobs/secrets/pods/log/volumesnapshots/backup CRDs. Testing: 14 pure-Go unit tests cover manifest shaping, owner refs, env composition, annotation merging, selector logic, and spec equality. A new e2e spec (`test/e2e/backup_test.go`, opt-in via BACKUP_ENABLED=1) walks the full PVC → backup → restore → verify loop. A new backup job in .github/workflows/e2e-k8s.yaml runs that spec with `--focus=backup` against Kubernetes 1.34.3 on same-repo events only (fork PRs cannot access the repo secrets). Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- .github/workflows/e2e-k8s-workflow.yaml | 21 + .github/workflows/e2e-k8s.yaml | 19 + AGENTS.md | 1 + Makefile | 6 + api/legacy/v1/backupconfig_types.go | 160 +++++++ api/legacy/v1/pvcbackup_types.go | 189 ++++++++ api/legacy/v1/restore_types.go | 104 ++++ api/legacy/v1/zz_generated.deepcopy.go | 375 +++++++++++++++ api/v1/backupconfig_types.go | 160 +++++++ api/v1/pvcbackup_types.go | 189 ++++++++ api/v1/restore_types.go | 104 ++++ api/v1/zz_generated.deepcopy.go | 375 +++++++++++++++ .../templates/controller/clusterroles.yaml | 51 ++ .../templates/controller/deployment.yaml | 11 +- .../topolvm.cybozu.com_backupconfigs.yaml | 303 ++++++++++++ .../crds/topolvm.cybozu.com_pvcbackups.yaml | 261 ++++++++++ .../crds/topolvm.cybozu.com_restores.yaml | 185 +++++++ .../crds/topolvm.io_backupconfigs.yaml | 303 ++++++++++++ .../templates/crds/topolvm.io_pvcbackups.yaml | 261 ++++++++++ .../templates/crds/topolvm.io_restores.yaml | 185 +++++++ charts/topolvm/values.yaml | 16 + cmd/topolvm-controller/app/root.go | 8 + cmd/topolvm-controller/app/run.go | 16 + .../topolvm.cybozu.com_backupconfigs.yaml | 300 ++++++++++++ .../bases/topolvm.cybozu.com_pvcbackups.yaml | 258 ++++++++++ .../bases/topolvm.cybozu.com_restores.yaml | 182 +++++++ .../crd/bases/topolvm.io_backupconfigs.yaml | 300 ++++++++++++ config/crd/bases/topolvm.io_pvcbackups.yaml | 258 ++++++++++ config/crd/bases/topolvm.io_restores.yaml | 182 +++++++ config/rbac/role.yaml | 45 +- constants.go | 40 ++ docs/backup-restore.md | 176 +++++++ go.mod | 1 + go.sum | 2 + internal/backup/manifests.go | 453 ++++++++++++++++++ internal/backup/manifests_test.go | 296 ++++++++++++ .../controller/backupconfig_controller.go | 422 ++++++++++++++++ .../backupconfig_controller_test.go | 210 ++++++++ internal/controller/pvcbackup_controller.go | 445 +++++++++++++++++ internal/controller/restore_controller.go | 226 +++++++++ pkg/controller/backup_controllers.go | 34 ++ test/e2e/Makefile | 13 + test/e2e/backup_test.go | 267 +++++++++++ test/e2e/manifests/values/backup.yaml | 3 + test/e2e/suite_test.go | 1 + .../backup/backupconfig-template.yaml | 17 + test/e2e/testdata/backup/pvc-template.yaml | 10 + .../testdata/backup/reader-pod-template.yaml | 27 ++ .../backup/restic-password-secret.yaml | 8 + .../e2e/testdata/backup/restore-template.yaml | 11 + test/e2e/testdata/backup/s3-creds-secret.yaml | 9 + .../testdata/backup/writer-pod-template.yaml | 23 + 52 files changed, 7517 insertions(+), 5 deletions(-) create mode 100644 api/legacy/v1/backupconfig_types.go create mode 100644 api/legacy/v1/pvcbackup_types.go create mode 100644 api/legacy/v1/restore_types.go create mode 100644 api/v1/backupconfig_types.go create mode 100644 api/v1/pvcbackup_types.go create mode 100644 api/v1/restore_types.go create mode 100644 charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml create mode 100644 charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml create mode 100644 charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml create mode 100644 charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml create mode 100644 charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml create mode 100644 charts/topolvm/templates/crds/topolvm.io_restores.yaml create mode 100644 config/crd/bases/topolvm.cybozu.com_backupconfigs.yaml create mode 100644 config/crd/bases/topolvm.cybozu.com_pvcbackups.yaml create mode 100644 config/crd/bases/topolvm.cybozu.com_restores.yaml create mode 100644 config/crd/bases/topolvm.io_backupconfigs.yaml create mode 100644 config/crd/bases/topolvm.io_pvcbackups.yaml create mode 100644 config/crd/bases/topolvm.io_restores.yaml create mode 100644 docs/backup-restore.md create mode 100644 internal/backup/manifests.go create mode 100644 internal/backup/manifests_test.go create mode 100644 internal/controller/backupconfig_controller.go create mode 100644 internal/controller/backupconfig_controller_test.go create mode 100644 internal/controller/pvcbackup_controller.go create mode 100644 internal/controller/restore_controller.go create mode 100644 pkg/controller/backup_controllers.go create mode 100644 test/e2e/backup_test.go create mode 100644 test/e2e/manifests/values/backup.yaml create mode 100644 test/e2e/testdata/backup/backupconfig-template.yaml create mode 100644 test/e2e/testdata/backup/pvc-template.yaml create mode 100644 test/e2e/testdata/backup/reader-pod-template.yaml create mode 100644 test/e2e/testdata/backup/restic-password-secret.yaml create mode 100644 test/e2e/testdata/backup/restore-template.yaml create mode 100644 test/e2e/testdata/backup/s3-creds-secret.yaml create mode 100644 test/e2e/testdata/backup/writer-pod-template.yaml diff --git a/.github/workflows/e2e-k8s-workflow.yaml b/.github/workflows/e2e-k8s-workflow.yaml index 0a89d89cd..53f4988e7 100644 --- a/.github/workflows/e2e-k8s-workflow.yaml +++ b/.github/workflows/e2e-k8s-workflow.yaml @@ -8,12 +8,26 @@ on: rwx_enabled: type: string default: "" + backup_enabled: + type: string + default: "" kubernetes_versions: type: string default: '["1.34.3", "1.33.7", "1.32.11"]' ginkgo_flags: type: string default: "" + secrets: + BACKUP_S3_ENDPOINT: + required: false + BACKUP_S3_BUCKET: + required: false + BACKUP_S3_ACCESS_KEY: + required: false + BACKUP_S3_SECRET_KEY: + required: false + BACKUP_RESTIC_PASSWORD: + required: false jobs: e2e-k8s: @@ -28,6 +42,13 @@ jobs: TEST_SCHEDULER_EXTENDER_TYPE: ${{ inputs.test_scheduler_extender_type }} TEST_LEGACY: ${{ inputs.test_legacy }} RWX_ENABLED: ${{ inputs.rwx_enabled }} + BACKUP_ENABLED: ${{ inputs.backup_enabled }} + BACKUP_S3_ENDPOINT: ${{ secrets.BACKUP_S3_ENDPOINT }} + BACKUP_S3_BUCKET: ${{ secrets.BACKUP_S3_BUCKET }} + BACKUP_S3_ACCESS_KEY: ${{ secrets.BACKUP_S3_ACCESS_KEY }} + BACKUP_S3_SECRET_KEY: ${{ secrets.BACKUP_S3_SECRET_KEY }} + BACKUP_RESTIC_PASSWORD: ${{ secrets.BACKUP_RESTIC_PASSWORD }} + BACKUP_S3_PREFIX: ci/${{ github.run_id }}-${{ github.run_attempt }} GINKGO_FLAGS: ${{ inputs.ginkgo_flags }} steps: - id: check diff --git a/.github/workflows/e2e-k8s.yaml b/.github/workflows/e2e-k8s.yaml index 8ac97069f..0e95c8f03 100644 --- a/.github/workflows/e2e-k8s.yaml +++ b/.github/workflows/e2e-k8s.yaml @@ -76,3 +76,22 @@ jobs: rwx_enabled: "1" kubernetes_versions: '["1.34.3"]' ginkgo_flags: "--focus=rwx" + + backup: + needs: build + uses: ./.github/workflows/e2e-k8s-workflow.yaml + # Skip on forks: PRs from forks cannot access repo secrets, so the backup + # job would always skip. Running only on same-repo events avoids the noise. + if: github.event.pull_request.head.repo.full_name == github.repository || github.event_name == 'push' + with: + test_scheduler_extender_type: "daemonset" + test_legacy: "false" + backup_enabled: "1" + kubernetes_versions: '["1.34.3"]' + ginkgo_flags: "--focus=backup" + secrets: + BACKUP_S3_ENDPOINT: ${{ secrets.BACKUP_S3_ENDPOINT }} + BACKUP_S3_BUCKET: ${{ secrets.BACKUP_S3_BUCKET }} + BACKUP_S3_ACCESS_KEY: ${{ secrets.BACKUP_S3_ACCESS_KEY }} + BACKUP_S3_SECRET_KEY: ${{ secrets.BACKUP_S3_SECRET_KEY }} + BACKUP_RESTIC_PASSWORD: ${{ secrets.BACKUP_RESTIC_PASSWORD }} diff --git a/AGENTS.md b/AGENTS.md index f50210636..1aa0de16b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -26,6 +26,7 @@ When you use AI assistance on this project, the AI reads this file to understand - [docs/lvmd-protocol.md](./docs/lvmd-protocol.md) - gRPC protocol (auto-generated) - **Advanced Topics**: - [docs/snapshot-and-restore.md](./docs/snapshot-and-restore.md) - Snapshot/clone support + - [docs/backup-restore.md](./docs/backup-restore.md) - restic-based backup/restore to S3 (opt-in) - [docs/advanced-setup.md](./docs/advanced-setup.md) - Advanced configurations - [docs/limitations.md](./docs/limitations.md) - Known limitations - [docs/faq.md](./docs/faq.md) - Frequently asked questions diff --git a/Makefile b/Makefile index 26437554d..d561d0c78 100644 --- a/Makefile +++ b/Makefile @@ -95,6 +95,12 @@ manifests: generate-legacy-api ## Generate WebhookConfiguration, ClusterRole and output:crd:artifacts:config=config/crd/bases cat config/crd/bases/topolvm.io_logicalvolumes.yaml | xargs -d" " printf "$$CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.io_logicalvolumes.yaml cat config/crd/bases/topolvm.cybozu.com_logicalvolumes.yaml | xargs -d" " printf "$$LEGACY_CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.cybozu.com_logicalvolumes.yaml + cat config/crd/bases/topolvm.io_backupconfigs.yaml | xargs -d" " printf "$$CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml + cat config/crd/bases/topolvm.io_pvcbackups.yaml | xargs -d" " printf "$$CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml + cat config/crd/bases/topolvm.io_restores.yaml | xargs -d" " printf "$$CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.io_restores.yaml + cat config/crd/bases/topolvm.cybozu.com_backupconfigs.yaml | xargs -d" " printf "$$LEGACY_CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml + cat config/crd/bases/topolvm.cybozu.com_pvcbackups.yaml | xargs -d" " printf "$$LEGACY_CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml + cat config/crd/bases/topolvm.cybozu.com_restores.yaml | xargs -d" " printf "$$LEGACY_CRD_TEMPLATE" > charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml .PHONY: generate-api ## Generate code containing DeepCopy, DeepCopyInto, and DeepCopyObject method implementations. generate-api: diff --git a/api/legacy/v1/backupconfig_types.go b/api/legacy/v1/backupconfig_types.go new file mode 100644 index 000000000..a8bd9a652 --- /dev/null +++ b/api/legacy/v1/backupconfig_types.go @@ -0,0 +1,160 @@ +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// S3Spec describes the remote S3-compatible object store used as the restic repository backend. +type S3Spec struct { + // Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + // or a MinIO endpoint. Required. + Endpoint string `json:"endpoint"` + + // Bucket is the target bucket name. One restic repository per PVC is + // created under the key prefix "//". + Bucket string `json:"bucket"` + + // Region is the S3 region. Optional for providers that do not require it. + //+kubebuilder:validation:Optional + Region string `json:"region,omitempty"` + + // CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + // AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + // the topolvm-controller. + CredentialsSecretRef corev1.SecretReference `json:"credentialsSecretRef"` + + // InsecureTLS disables TLS verification against the S3 endpoint. Use only + // for self-signed endpoints during testing. + //+kubebuilder:validation:Optional + InsecureTLS bool `json:"insecureTLS,omitempty"` + + // Prefix is an optional key prefix prepended under the bucket root before + // the per-PVC "/" path. Useful for isolating CI runs that + // share a bucket, e.g. prefix="ci/". + //+kubebuilder:validation:Optional + Prefix string `json:"prefix,omitempty"` +} + +// RetentionSpec mirrors the restic forget --keep-* flags. +type RetentionSpec struct { + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepLast int32 `json:"keepLast,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepHourly int32 `json:"keepHourly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepDaily int32 `json:"keepDaily,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepWeekly int32 `json:"keepWeekly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepMonthly int32 `json:"keepMonthly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepYearly int32 `json:"keepYearly,omitempty"` +} + +// BackupConfigSpec defines the cluster-wide backup configuration. A single +// BackupConfig named "default" is expected; additional BackupConfigs are +// ignored by the controller. +type BackupConfigSpec struct { + // S3 is the remote object store configuration. + S3 S3Spec `json:"s3"` + + // ResticPasswordSecretRef references a Secret with a single "password" key + // used as the restic repository password. Losing this secret makes existing + // backups unreadable. + ResticPasswordSecretRef corev1.SecretReference `json:"resticPasswordSecretRef"` + + // Schedule is the default cron schedule applied to every backed-up PVC. + // When empty, no backup CronJobs are created unless a PVC sets its own + // schedule via the "topolvm.io/backup-schedule" annotation. + //+kubebuilder:validation:Optional + Schedule string `json:"schedule,omitempty"` + + // Retention is the default retention policy. Per-PVC annotations of the + // form "topolvm.io/backup-retention-" override individual buckets. + //+kubebuilder:validation:Optional + Retention RetentionSpec `json:"retention,omitempty"` + + // Selector restricts which PVCs are backed up. An empty selector matches + // every PVC bound to a TopoLVM StorageClass. PVCs annotated + // "topolvm.io/backup=false" are always skipped. + //+kubebuilder:validation:Optional + Selector *metav1.LabelSelector `json:"selector,omitempty"` + + // KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + // the backup is preserved after restic completes. When false (default) the + // snapshot is deleted once the backup finishes, regardless of outcome. + // Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + //+kubebuilder:default=false + KeepSnapshotAfterBackup bool `json:"keepSnapshotAfterBackup,omitempty"` + + // VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + // PVCs prior to backup. If empty the controller falls back to the default + // VolumeSnapshotClass for the topolvm driver. + //+kubebuilder:validation:Optional + VolumeSnapshotClassName string `json:"volumeSnapshotClassName,omitempty"` + + // Suspend pauses creation of new backup Jobs without deleting existing + // CronJobs or previously taken backups. + //+kubebuilder:validation:Optional + Suspend bool `json:"suspend,omitempty"` +} + +// BackupConfigStatus reports the observed state of the backup fleet. +type BackupConfigStatus struct { + // ObservedGeneration matches BackupConfig.metadata.generation when the + // status was last updated. + //+kubebuilder:validation:Optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // ManagedPVCs is the number of PVCs the controller currently has a + // backup CronJob for. + //+kubebuilder:validation:Optional + ManagedPVCs int32 `json:"managedPVCs,omitempty"` + + // Conditions is the list of conditions for this BackupConfig. Typical + // condition types: "Ready", "CredentialsValid". + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Cluster + +// BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore +// via restic. +type BackupConfig struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BackupConfigSpec `json:"spec,omitempty"` + Status BackupConfigStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// BackupConfigList contains a list of BackupConfig. +type BackupConfigList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []BackupConfig `json:"items"` +} + +func init() { + SchemeBuilder.Register(&BackupConfig{}, &BackupConfigList{}) +} diff --git a/api/legacy/v1/pvcbackup_types.go b/api/legacy/v1/pvcbackup_types.go new file mode 100644 index 000000000..28af5aa99 --- /dev/null +++ b/api/legacy/v1/pvcbackup_types.go @@ -0,0 +1,189 @@ +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// PVCBackupPhase is the high-level phase of a PVCBackup reconciliation. +type PVCBackupPhase string + +const ( + // PVCBackupPhaseIdle means the controller is waiting for the next + // scheduled fire time. + PVCBackupPhaseIdle PVCBackupPhase = "Idle" + + // PVCBackupPhaseSnapshotting means a VolumeSnapshot has been created + // and the controller is waiting for it to become ready. + PVCBackupPhaseSnapshotting PVCBackupPhase = "Snapshotting" + + // PVCBackupPhaseCloning means a temp PVC is being provisioned from the + // ready VolumeSnapshot and the controller is waiting for it to bind. + PVCBackupPhaseCloning PVCBackupPhase = "Cloning" + + // PVCBackupPhaseMoving means the restic mover Job is running against + // the temp PVC. + PVCBackupPhaseMoving PVCBackupPhase = "Moving" + + // PVCBackupPhaseCleanup means the mover has finished and the + // controller is tearing down the temp PVC (and optionally the + // VolumeSnapshot). + PVCBackupPhaseCleanup PVCBackupPhase = "Cleanup" + + // PVCBackupPhaseSynced means the last run finished successfully and + // the controller is back to Idle until the next fire time. This phase + // is set briefly between runs for status-subresource consumers; the + // controller transitions back to Idle on the next reconcile. + PVCBackupPhaseSynced PVCBackupPhase = "Synced" + + // PVCBackupPhaseFailed means the last run failed. The controller will + // still honor the schedule and attempt again at the next fire time. + PVCBackupPhaseFailed PVCBackupPhase = "Failed" +) + +// PVCBackupSpec defines the backup policy for a single PVC. The object is +// typically owned by a BackupConfig reconciler that creates/updates one +// PVCBackup per matching PVC, but users may also author PVCBackup objects +// directly for one-off or bespoke schedules. +type PVCBackupSpec struct { + // PVCName is the name of the source PersistentVolumeClaim in the same + // namespace as this PVCBackup. + PVCName string `json:"pvcName"` + + // Schedule is a cron expression evaluated in-process by the controller. + // Empty disables scheduling; the controller will not take backups. + //+kubebuilder:validation:Optional + Schedule string `json:"schedule,omitempty"` + + // Retention is the restic forget policy applied after each successful + // backup. + //+kubebuilder:validation:Optional + Retention RetentionSpec `json:"retention,omitempty"` + + // KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + // mover completes. The temp PVC is always deleted. + //+kubebuilder:validation:Optional + KeepSnapshotAfterBackup bool `json:"keepSnapshotAfterBackup,omitempty"` + + // VolumeSnapshotClassName is the VolumeSnapshotClass used for the + // backup snapshot. If empty the default class for the PVC's driver is + // used. + //+kubebuilder:validation:Optional + VolumeSnapshotClassName string `json:"volumeSnapshotClassName,omitempty"` + + // Suspend pauses new backup runs without affecting the current run or + // existing restic data. + //+kubebuilder:validation:Optional + Suspend bool `json:"suspend,omitempty"` + + // Trigger forces a one-shot run. Setting this to a new value that + // differs from status.lastHandledTrigger causes the controller to run a + // backup immediately, regardless of the schedule. A common pattern is + // to set it to a timestamp. Empty means no manual trigger. + //+kubebuilder:validation:Optional + Trigger string `json:"trigger,omitempty"` +} + +// MoverStatus captures the outcome of the last mover Job. +type MoverStatus struct { + //+kubebuilder:validation:Optional + JobName string `json:"jobName,omitempty"` + + //+kubebuilder:validation:Optional + Succeeded bool `json:"succeeded,omitempty"` + + //+kubebuilder:validation:Optional + Logs string `json:"logs,omitempty"` +} + +// PVCBackupStatus reports the observed state of a PVCBackup. +type PVCBackupStatus struct { + //+kubebuilder:validation:Optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + //+kubebuilder:validation:Optional + Phase PVCBackupPhase `json:"phase,omitempty"` + + //+kubebuilder:validation:Optional + Message string `json:"message,omitempty"` + + // LastSyncTime is when the most recent backup completed successfully. + //+kubebuilder:validation:Optional + LastSyncTime *metav1.Time `json:"lastSyncTime,omitempty"` + + // LastSyncDuration is how long the most recent successful backup took. + //+kubebuilder:validation:Optional + LastSyncDuration *metav1.Duration `json:"lastSyncDuration,omitempty"` + + // NextSyncTime is the next scheduled fire time based on .spec.schedule. + //+kubebuilder:validation:Optional + NextSyncTime *metav1.Time `json:"nextSyncTime,omitempty"` + + // LastHandledTrigger mirrors .spec.trigger the last time a manual run + // was accepted, so repeated reconciles of the same trigger value don't + // retrigger backups. + //+kubebuilder:validation:Optional + LastHandledTrigger string `json:"lastHandledTrigger,omitempty"` + + // CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + // VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + //+kubebuilder:validation:Optional + CurrentRunStartTime *metav1.Time `json:"currentRunStartTime,omitempty"` + + // CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + // the child resources owned by this PVCBackup during an active run. + //+kubebuilder:validation:Optional + CurrentSnapshotName string `json:"currentSnapshotName,omitempty"` + + //+kubebuilder:validation:Optional + CurrentTempPVCName string `json:"currentTempPVCName,omitempty"` + + //+kubebuilder:validation:Optional + CurrentMoverJobName string `json:"currentMoverJobName,omitempty"` + + // LatestMoverStatus mirrors the final state of the most recently completed mover Job. + //+kubebuilder:validation:Optional + LatestMoverStatus *MoverStatus `json:"latestMoverStatus,omitempty"` + + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Namespaced,shortName=pvcbk +//+kubebuilder:printcolumn:name="PVC",type=string,JSONPath=`.spec.pvcName` +//+kubebuilder:printcolumn:name="Schedule",type=string,JSONPath=`.spec.schedule` +//+kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` +//+kubebuilder:printcolumn:name="LastSync",type=date,JSONPath=`.status.lastSyncTime` +//+kubebuilder:printcolumn:name="NextSync",type=date,JSONPath=`.status.nextSyncTime` +//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` + +// PVCBackup represents an ongoing backup policy for a single PVC. The +// controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at +// each fire time, provisions a temp PVC from the snapshot, runs a restic +// mover Job against it, and cleans up the temp PVC (and optionally the +// VolumeSnapshot). All child resources are owned by the PVCBackup so +// deleting it cascades cleanly. +type PVCBackup struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PVCBackupSpec `json:"spec,omitempty"` + Status PVCBackupStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// PVCBackupList contains a list of PVCBackup. +type PVCBackupList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PVCBackup `json:"items"` +} + +func init() { + SchemeBuilder.Register(&PVCBackup{}, &PVCBackupList{}) +} diff --git a/api/legacy/v1/restore_types.go b/api/legacy/v1/restore_types.go new file mode 100644 index 000000000..f12e2e708 --- /dev/null +++ b/api/legacy/v1/restore_types.go @@ -0,0 +1,104 @@ +package v1 + +import ( + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// RestorePhase captures the coarse state of a Restore. +type RestorePhase string + +const ( + RestorePhasePending RestorePhase = "Pending" + RestorePhaseRunning RestorePhase = "Running" + RestorePhaseSucceeded RestorePhase = "Succeeded" + RestorePhaseFailed RestorePhase = "Failed" +) + +// RestoreSpec defines a single restore operation from a restic repository +// back into a fresh PersistentVolumeClaim. +type RestoreSpec struct { + // SourceNamespace is the namespace of the PVC whose backups should be + // restored. The restic repository key is "/". + SourceNamespace string `json:"sourceNamespace"` + + // SourcePVCName is the name of the original PVC that was backed up. + SourcePVCName string `json:"sourcePVCName"` + + // SnapshotID is the restic snapshot id to restore. If empty, "latest" is + // used. + //+kubebuilder:validation:Optional + SnapshotID string `json:"snapshotID,omitempty"` + + // TargetPVCName is the name of the PVC to create in this Restore's + // namespace. The controller provisions this PVC with the given size and + // storage class, then mounts it into the restic restore Job. + TargetPVCName string `json:"targetPVCName"` + + // Size is the capacity for the target PVC. It should be at least as large + // as the source. + Size resource.Quantity `json:"size"` + + // StorageClassName is the StorageClass for the target PVC. Must reference + // a TopoLVM StorageClass. + StorageClassName string `json:"storageClassName"` +} + +// RestoreStatus reports the observed state of a Restore. +type RestoreStatus struct { + //+kubebuilder:validation:Optional + Phase RestorePhase `json:"phase,omitempty"` + + // Message is a human-readable explanation of the current phase. + //+kubebuilder:validation:Optional + Message string `json:"message,omitempty"` + + // JobName is the name of the Job running the restic restore. + //+kubebuilder:validation:Optional + JobName string `json:"jobName,omitempty"` + + // StartTime is when the restore Job was created. + //+kubebuilder:validation:Optional + StartTime *metav1.Time `json:"startTime,omitempty"` + + // CompletionTime is when the restore Job reached a terminal state. + //+kubebuilder:validation:Optional + CompletionTime *metav1.Time `json:"completionTime,omitempty"` + + // Conditions is the list of conditions for this Restore. + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Namespaced +//+kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` +//+kubebuilder:printcolumn:name="Source",type=string,JSONPath=`.spec.sourcePVCName` +//+kubebuilder:printcolumn:name="Target",type=string,JSONPath=`.spec.targetPVCName` +//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` + +// Restore is the Schema for restic-backed PVC restore operations. +type Restore struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec RestoreSpec `json:"spec,omitempty"` + Status RestoreStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// RestoreList contains a list of Restore. +type RestoreList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Restore `json:"items"` +} + +func init() { + SchemeBuilder.Register(&Restore{}, &RestoreList{}) +} diff --git a/api/legacy/v1/zz_generated.deepcopy.go b/api/legacy/v1/zz_generated.deepcopy.go index 2acb0cea9..7f21cd1c8 100644 --- a/api/legacy/v1/zz_generated.deepcopy.go +++ b/api/legacy/v1/zz_generated.deepcopy.go @@ -5,9 +5,114 @@ package v1 import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfig) DeepCopyInto(out *BackupConfig) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfig. +func (in *BackupConfig) DeepCopy() *BackupConfig { + if in == nil { + return nil + } + out := new(BackupConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BackupConfig) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigList) DeepCopyInto(out *BackupConfigList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]BackupConfig, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigList. +func (in *BackupConfigList) DeepCopy() *BackupConfigList { + if in == nil { + return nil + } + out := new(BackupConfigList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BackupConfigList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigSpec) DeepCopyInto(out *BackupConfigSpec) { + *out = *in + out.S3 = in.S3 + out.ResticPasswordSecretRef = in.ResticPasswordSecretRef + out.Retention = in.Retention + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(metav1.LabelSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigSpec. +func (in *BackupConfigSpec) DeepCopy() *BackupConfigSpec { + if in == nil { + return nil + } + out := new(BackupConfigSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigStatus) DeepCopyInto(out *BackupConfigStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigStatus. +func (in *BackupConfigStatus) DeepCopy() *BackupConfigStatus { + if in == nil { + return nil + } + out := new(BackupConfigStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogicalVolume) DeepCopyInto(out *LogicalVolume) { *out = *in @@ -102,3 +207,273 @@ func (in *LogicalVolumeStatus) DeepCopy() *LogicalVolumeStatus { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MoverStatus) DeepCopyInto(out *MoverStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MoverStatus. +func (in *MoverStatus) DeepCopy() *MoverStatus { + if in == nil { + return nil + } + out := new(MoverStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackup) DeepCopyInto(out *PVCBackup) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackup. +func (in *PVCBackup) DeepCopy() *PVCBackup { + if in == nil { + return nil + } + out := new(PVCBackup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PVCBackup) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupList) DeepCopyInto(out *PVCBackupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PVCBackup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupList. +func (in *PVCBackupList) DeepCopy() *PVCBackupList { + if in == nil { + return nil + } + out := new(PVCBackupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PVCBackupList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupSpec) DeepCopyInto(out *PVCBackupSpec) { + *out = *in + out.Retention = in.Retention +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupSpec. +func (in *PVCBackupSpec) DeepCopy() *PVCBackupSpec { + if in == nil { + return nil + } + out := new(PVCBackupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupStatus) DeepCopyInto(out *PVCBackupStatus) { + *out = *in + if in.LastSyncTime != nil { + in, out := &in.LastSyncTime, &out.LastSyncTime + *out = (*in).DeepCopy() + } + if in.LastSyncDuration != nil { + in, out := &in.LastSyncDuration, &out.LastSyncDuration + *out = new(metav1.Duration) + **out = **in + } + if in.NextSyncTime != nil { + in, out := &in.NextSyncTime, &out.NextSyncTime + *out = (*in).DeepCopy() + } + if in.CurrentRunStartTime != nil { + in, out := &in.CurrentRunStartTime, &out.CurrentRunStartTime + *out = (*in).DeepCopy() + } + if in.LatestMoverStatus != nil { + in, out := &in.LatestMoverStatus, &out.LatestMoverStatus + *out = new(MoverStatus) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupStatus. +func (in *PVCBackupStatus) DeepCopy() *PVCBackupStatus { + if in == nil { + return nil + } + out := new(PVCBackupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Restore) DeepCopyInto(out *Restore) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Restore. +func (in *Restore) DeepCopy() *Restore { + if in == nil { + return nil + } + out := new(Restore) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Restore) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreList) DeepCopyInto(out *RestoreList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Restore, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreList. +func (in *RestoreList) DeepCopy() *RestoreList { + if in == nil { + return nil + } + out := new(RestoreList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RestoreList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreSpec) DeepCopyInto(out *RestoreSpec) { + *out = *in + out.Size = in.Size.DeepCopy() +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreSpec. +func (in *RestoreSpec) DeepCopy() *RestoreSpec { + if in == nil { + return nil + } + out := new(RestoreSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreStatus) DeepCopyInto(out *RestoreStatus) { + *out = *in + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = (*in).DeepCopy() + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = (*in).DeepCopy() + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreStatus. +func (in *RestoreStatus) DeepCopy() *RestoreStatus { + if in == nil { + return nil + } + out := new(RestoreStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RetentionSpec) DeepCopyInto(out *RetentionSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RetentionSpec. +func (in *RetentionSpec) DeepCopy() *RetentionSpec { + if in == nil { + return nil + } + out := new(RetentionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *S3Spec) DeepCopyInto(out *S3Spec) { + *out = *in + out.CredentialsSecretRef = in.CredentialsSecretRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new S3Spec. +func (in *S3Spec) DeepCopy() *S3Spec { + if in == nil { + return nil + } + out := new(S3Spec) + in.DeepCopyInto(out) + return out +} diff --git a/api/v1/backupconfig_types.go b/api/v1/backupconfig_types.go new file mode 100644 index 000000000..a8bd9a652 --- /dev/null +++ b/api/v1/backupconfig_types.go @@ -0,0 +1,160 @@ +package v1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// S3Spec describes the remote S3-compatible object store used as the restic repository backend. +type S3Spec struct { + // Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + // or a MinIO endpoint. Required. + Endpoint string `json:"endpoint"` + + // Bucket is the target bucket name. One restic repository per PVC is + // created under the key prefix "//". + Bucket string `json:"bucket"` + + // Region is the S3 region. Optional for providers that do not require it. + //+kubebuilder:validation:Optional + Region string `json:"region,omitempty"` + + // CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + // AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + // the topolvm-controller. + CredentialsSecretRef corev1.SecretReference `json:"credentialsSecretRef"` + + // InsecureTLS disables TLS verification against the S3 endpoint. Use only + // for self-signed endpoints during testing. + //+kubebuilder:validation:Optional + InsecureTLS bool `json:"insecureTLS,omitempty"` + + // Prefix is an optional key prefix prepended under the bucket root before + // the per-PVC "/" path. Useful for isolating CI runs that + // share a bucket, e.g. prefix="ci/". + //+kubebuilder:validation:Optional + Prefix string `json:"prefix,omitempty"` +} + +// RetentionSpec mirrors the restic forget --keep-* flags. +type RetentionSpec struct { + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepLast int32 `json:"keepLast,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepHourly int32 `json:"keepHourly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepDaily int32 `json:"keepDaily,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepWeekly int32 `json:"keepWeekly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepMonthly int32 `json:"keepMonthly,omitempty"` + + //+kubebuilder:validation:Minimum=0 + //+kubebuilder:validation:Optional + KeepYearly int32 `json:"keepYearly,omitempty"` +} + +// BackupConfigSpec defines the cluster-wide backup configuration. A single +// BackupConfig named "default" is expected; additional BackupConfigs are +// ignored by the controller. +type BackupConfigSpec struct { + // S3 is the remote object store configuration. + S3 S3Spec `json:"s3"` + + // ResticPasswordSecretRef references a Secret with a single "password" key + // used as the restic repository password. Losing this secret makes existing + // backups unreadable. + ResticPasswordSecretRef corev1.SecretReference `json:"resticPasswordSecretRef"` + + // Schedule is the default cron schedule applied to every backed-up PVC. + // When empty, no backup CronJobs are created unless a PVC sets its own + // schedule via the "topolvm.io/backup-schedule" annotation. + //+kubebuilder:validation:Optional + Schedule string `json:"schedule,omitempty"` + + // Retention is the default retention policy. Per-PVC annotations of the + // form "topolvm.io/backup-retention-" override individual buckets. + //+kubebuilder:validation:Optional + Retention RetentionSpec `json:"retention,omitempty"` + + // Selector restricts which PVCs are backed up. An empty selector matches + // every PVC bound to a TopoLVM StorageClass. PVCs annotated + // "topolvm.io/backup=false" are always skipped. + //+kubebuilder:validation:Optional + Selector *metav1.LabelSelector `json:"selector,omitempty"` + + // KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + // the backup is preserved after restic completes. When false (default) the + // snapshot is deleted once the backup finishes, regardless of outcome. + // Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + //+kubebuilder:default=false + KeepSnapshotAfterBackup bool `json:"keepSnapshotAfterBackup,omitempty"` + + // VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + // PVCs prior to backup. If empty the controller falls back to the default + // VolumeSnapshotClass for the topolvm driver. + //+kubebuilder:validation:Optional + VolumeSnapshotClassName string `json:"volumeSnapshotClassName,omitempty"` + + // Suspend pauses creation of new backup Jobs without deleting existing + // CronJobs or previously taken backups. + //+kubebuilder:validation:Optional + Suspend bool `json:"suspend,omitempty"` +} + +// BackupConfigStatus reports the observed state of the backup fleet. +type BackupConfigStatus struct { + // ObservedGeneration matches BackupConfig.metadata.generation when the + // status was last updated. + //+kubebuilder:validation:Optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + // ManagedPVCs is the number of PVCs the controller currently has a + // backup CronJob for. + //+kubebuilder:validation:Optional + ManagedPVCs int32 `json:"managedPVCs,omitempty"` + + // Conditions is the list of conditions for this BackupConfig. Typical + // condition types: "Ready", "CredentialsValid". + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Cluster + +// BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore +// via restic. +type BackupConfig struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec BackupConfigSpec `json:"spec,omitempty"` + Status BackupConfigStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// BackupConfigList contains a list of BackupConfig. +type BackupConfigList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []BackupConfig `json:"items"` +} + +func init() { + SchemeBuilder.Register(&BackupConfig{}, &BackupConfigList{}) +} diff --git a/api/v1/pvcbackup_types.go b/api/v1/pvcbackup_types.go new file mode 100644 index 000000000..28af5aa99 --- /dev/null +++ b/api/v1/pvcbackup_types.go @@ -0,0 +1,189 @@ +package v1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// PVCBackupPhase is the high-level phase of a PVCBackup reconciliation. +type PVCBackupPhase string + +const ( + // PVCBackupPhaseIdle means the controller is waiting for the next + // scheduled fire time. + PVCBackupPhaseIdle PVCBackupPhase = "Idle" + + // PVCBackupPhaseSnapshotting means a VolumeSnapshot has been created + // and the controller is waiting for it to become ready. + PVCBackupPhaseSnapshotting PVCBackupPhase = "Snapshotting" + + // PVCBackupPhaseCloning means a temp PVC is being provisioned from the + // ready VolumeSnapshot and the controller is waiting for it to bind. + PVCBackupPhaseCloning PVCBackupPhase = "Cloning" + + // PVCBackupPhaseMoving means the restic mover Job is running against + // the temp PVC. + PVCBackupPhaseMoving PVCBackupPhase = "Moving" + + // PVCBackupPhaseCleanup means the mover has finished and the + // controller is tearing down the temp PVC (and optionally the + // VolumeSnapshot). + PVCBackupPhaseCleanup PVCBackupPhase = "Cleanup" + + // PVCBackupPhaseSynced means the last run finished successfully and + // the controller is back to Idle until the next fire time. This phase + // is set briefly between runs for status-subresource consumers; the + // controller transitions back to Idle on the next reconcile. + PVCBackupPhaseSynced PVCBackupPhase = "Synced" + + // PVCBackupPhaseFailed means the last run failed. The controller will + // still honor the schedule and attempt again at the next fire time. + PVCBackupPhaseFailed PVCBackupPhase = "Failed" +) + +// PVCBackupSpec defines the backup policy for a single PVC. The object is +// typically owned by a BackupConfig reconciler that creates/updates one +// PVCBackup per matching PVC, but users may also author PVCBackup objects +// directly for one-off or bespoke schedules. +type PVCBackupSpec struct { + // PVCName is the name of the source PersistentVolumeClaim in the same + // namespace as this PVCBackup. + PVCName string `json:"pvcName"` + + // Schedule is a cron expression evaluated in-process by the controller. + // Empty disables scheduling; the controller will not take backups. + //+kubebuilder:validation:Optional + Schedule string `json:"schedule,omitempty"` + + // Retention is the restic forget policy applied after each successful + // backup. + //+kubebuilder:validation:Optional + Retention RetentionSpec `json:"retention,omitempty"` + + // KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + // mover completes. The temp PVC is always deleted. + //+kubebuilder:validation:Optional + KeepSnapshotAfterBackup bool `json:"keepSnapshotAfterBackup,omitempty"` + + // VolumeSnapshotClassName is the VolumeSnapshotClass used for the + // backup snapshot. If empty the default class for the PVC's driver is + // used. + //+kubebuilder:validation:Optional + VolumeSnapshotClassName string `json:"volumeSnapshotClassName,omitempty"` + + // Suspend pauses new backup runs without affecting the current run or + // existing restic data. + //+kubebuilder:validation:Optional + Suspend bool `json:"suspend,omitempty"` + + // Trigger forces a one-shot run. Setting this to a new value that + // differs from status.lastHandledTrigger causes the controller to run a + // backup immediately, regardless of the schedule. A common pattern is + // to set it to a timestamp. Empty means no manual trigger. + //+kubebuilder:validation:Optional + Trigger string `json:"trigger,omitempty"` +} + +// MoverStatus captures the outcome of the last mover Job. +type MoverStatus struct { + //+kubebuilder:validation:Optional + JobName string `json:"jobName,omitempty"` + + //+kubebuilder:validation:Optional + Succeeded bool `json:"succeeded,omitempty"` + + //+kubebuilder:validation:Optional + Logs string `json:"logs,omitempty"` +} + +// PVCBackupStatus reports the observed state of a PVCBackup. +type PVCBackupStatus struct { + //+kubebuilder:validation:Optional + ObservedGeneration int64 `json:"observedGeneration,omitempty"` + + //+kubebuilder:validation:Optional + Phase PVCBackupPhase `json:"phase,omitempty"` + + //+kubebuilder:validation:Optional + Message string `json:"message,omitempty"` + + // LastSyncTime is when the most recent backup completed successfully. + //+kubebuilder:validation:Optional + LastSyncTime *metav1.Time `json:"lastSyncTime,omitempty"` + + // LastSyncDuration is how long the most recent successful backup took. + //+kubebuilder:validation:Optional + LastSyncDuration *metav1.Duration `json:"lastSyncDuration,omitempty"` + + // NextSyncTime is the next scheduled fire time based on .spec.schedule. + //+kubebuilder:validation:Optional + NextSyncTime *metav1.Time `json:"nextSyncTime,omitempty"` + + // LastHandledTrigger mirrors .spec.trigger the last time a manual run + // was accepted, so repeated reconciles of the same trigger value don't + // retrigger backups. + //+kubebuilder:validation:Optional + LastHandledTrigger string `json:"lastHandledTrigger,omitempty"` + + // CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + // VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + //+kubebuilder:validation:Optional + CurrentRunStartTime *metav1.Time `json:"currentRunStartTime,omitempty"` + + // CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + // the child resources owned by this PVCBackup during an active run. + //+kubebuilder:validation:Optional + CurrentSnapshotName string `json:"currentSnapshotName,omitempty"` + + //+kubebuilder:validation:Optional + CurrentTempPVCName string `json:"currentTempPVCName,omitempty"` + + //+kubebuilder:validation:Optional + CurrentMoverJobName string `json:"currentMoverJobName,omitempty"` + + // LatestMoverStatus mirrors the final state of the most recently completed mover Job. + //+kubebuilder:validation:Optional + LatestMoverStatus *MoverStatus `json:"latestMoverStatus,omitempty"` + + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Namespaced,shortName=pvcbk +//+kubebuilder:printcolumn:name="PVC",type=string,JSONPath=`.spec.pvcName` +//+kubebuilder:printcolumn:name="Schedule",type=string,JSONPath=`.spec.schedule` +//+kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` +//+kubebuilder:printcolumn:name="LastSync",type=date,JSONPath=`.status.lastSyncTime` +//+kubebuilder:printcolumn:name="NextSync",type=date,JSONPath=`.status.nextSyncTime` +//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` + +// PVCBackup represents an ongoing backup policy for a single PVC. The +// controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at +// each fire time, provisions a temp PVC from the snapshot, runs a restic +// mover Job against it, and cleans up the temp PVC (and optionally the +// VolumeSnapshot). All child resources are owned by the PVCBackup so +// deleting it cascades cleanly. +type PVCBackup struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec PVCBackupSpec `json:"spec,omitempty"` + Status PVCBackupStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// PVCBackupList contains a list of PVCBackup. +type PVCBackupList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []PVCBackup `json:"items"` +} + +func init() { + SchemeBuilder.Register(&PVCBackup{}, &PVCBackupList{}) +} diff --git a/api/v1/restore_types.go b/api/v1/restore_types.go new file mode 100644 index 000000000..f12e2e708 --- /dev/null +++ b/api/v1/restore_types.go @@ -0,0 +1,104 @@ +package v1 + +import ( + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! +// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. + +// RestorePhase captures the coarse state of a Restore. +type RestorePhase string + +const ( + RestorePhasePending RestorePhase = "Pending" + RestorePhaseRunning RestorePhase = "Running" + RestorePhaseSucceeded RestorePhase = "Succeeded" + RestorePhaseFailed RestorePhase = "Failed" +) + +// RestoreSpec defines a single restore operation from a restic repository +// back into a fresh PersistentVolumeClaim. +type RestoreSpec struct { + // SourceNamespace is the namespace of the PVC whose backups should be + // restored. The restic repository key is "/". + SourceNamespace string `json:"sourceNamespace"` + + // SourcePVCName is the name of the original PVC that was backed up. + SourcePVCName string `json:"sourcePVCName"` + + // SnapshotID is the restic snapshot id to restore. If empty, "latest" is + // used. + //+kubebuilder:validation:Optional + SnapshotID string `json:"snapshotID,omitempty"` + + // TargetPVCName is the name of the PVC to create in this Restore's + // namespace. The controller provisions this PVC with the given size and + // storage class, then mounts it into the restic restore Job. + TargetPVCName string `json:"targetPVCName"` + + // Size is the capacity for the target PVC. It should be at least as large + // as the source. + Size resource.Quantity `json:"size"` + + // StorageClassName is the StorageClass for the target PVC. Must reference + // a TopoLVM StorageClass. + StorageClassName string `json:"storageClassName"` +} + +// RestoreStatus reports the observed state of a Restore. +type RestoreStatus struct { + //+kubebuilder:validation:Optional + Phase RestorePhase `json:"phase,omitempty"` + + // Message is a human-readable explanation of the current phase. + //+kubebuilder:validation:Optional + Message string `json:"message,omitempty"` + + // JobName is the name of the Job running the restic restore. + //+kubebuilder:validation:Optional + JobName string `json:"jobName,omitempty"` + + // StartTime is when the restore Job was created. + //+kubebuilder:validation:Optional + StartTime *metav1.Time `json:"startTime,omitempty"` + + // CompletionTime is when the restore Job reached a terminal state. + //+kubebuilder:validation:Optional + CompletionTime *metav1.Time `json:"completionTime,omitempty"` + + // Conditions is the list of conditions for this Restore. + //+kubebuilder:validation:Optional + Conditions []metav1.Condition `json:"conditions,omitempty"` +} + +//+kubebuilder:object:root=true +//+kubebuilder:subresource:status +//+kubebuilder:resource:scope=Namespaced +//+kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase` +//+kubebuilder:printcolumn:name="Source",type=string,JSONPath=`.spec.sourcePVCName` +//+kubebuilder:printcolumn:name="Target",type=string,JSONPath=`.spec.targetPVCName` +//+kubebuilder:printcolumn:name="Age",type=date,JSONPath=`.metadata.creationTimestamp` + +// Restore is the Schema for restic-backed PVC restore operations. +type Restore struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec RestoreSpec `json:"spec,omitempty"` + Status RestoreStatus `json:"status,omitempty"` +} + +//+kubebuilder:object:root=true + +// RestoreList contains a list of Restore. +type RestoreList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + Items []Restore `json:"items"` +} + +func init() { + SchemeBuilder.Register(&Restore{}, &RestoreList{}) +} diff --git a/api/v1/zz_generated.deepcopy.go b/api/v1/zz_generated.deepcopy.go index 2acb0cea9..7f21cd1c8 100644 --- a/api/v1/zz_generated.deepcopy.go +++ b/api/v1/zz_generated.deepcopy.go @@ -5,9 +5,114 @@ package v1 import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfig) DeepCopyInto(out *BackupConfig) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfig. +func (in *BackupConfig) DeepCopy() *BackupConfig { + if in == nil { + return nil + } + out := new(BackupConfig) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BackupConfig) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigList) DeepCopyInto(out *BackupConfigList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]BackupConfig, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigList. +func (in *BackupConfigList) DeepCopy() *BackupConfigList { + if in == nil { + return nil + } + out := new(BackupConfigList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *BackupConfigList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigSpec) DeepCopyInto(out *BackupConfigSpec) { + *out = *in + out.S3 = in.S3 + out.ResticPasswordSecretRef = in.ResticPasswordSecretRef + out.Retention = in.Retention + if in.Selector != nil { + in, out := &in.Selector, &out.Selector + *out = new(metav1.LabelSelector) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigSpec. +func (in *BackupConfigSpec) DeepCopy() *BackupConfigSpec { + if in == nil { + return nil + } + out := new(BackupConfigSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupConfigStatus) DeepCopyInto(out *BackupConfigStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupConfigStatus. +func (in *BackupConfigStatus) DeepCopy() *BackupConfigStatus { + if in == nil { + return nil + } + out := new(BackupConfigStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *LogicalVolume) DeepCopyInto(out *LogicalVolume) { *out = *in @@ -102,3 +207,273 @@ func (in *LogicalVolumeStatus) DeepCopy() *LogicalVolumeStatus { in.DeepCopyInto(out) return out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *MoverStatus) DeepCopyInto(out *MoverStatus) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MoverStatus. +func (in *MoverStatus) DeepCopy() *MoverStatus { + if in == nil { + return nil + } + out := new(MoverStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackup) DeepCopyInto(out *PVCBackup) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + out.Spec = in.Spec + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackup. +func (in *PVCBackup) DeepCopy() *PVCBackup { + if in == nil { + return nil + } + out := new(PVCBackup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PVCBackup) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupList) DeepCopyInto(out *PVCBackupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PVCBackup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupList. +func (in *PVCBackupList) DeepCopy() *PVCBackupList { + if in == nil { + return nil + } + out := new(PVCBackupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *PVCBackupList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupSpec) DeepCopyInto(out *PVCBackupSpec) { + *out = *in + out.Retention = in.Retention +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupSpec. +func (in *PVCBackupSpec) DeepCopy() *PVCBackupSpec { + if in == nil { + return nil + } + out := new(PVCBackupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PVCBackupStatus) DeepCopyInto(out *PVCBackupStatus) { + *out = *in + if in.LastSyncTime != nil { + in, out := &in.LastSyncTime, &out.LastSyncTime + *out = (*in).DeepCopy() + } + if in.LastSyncDuration != nil { + in, out := &in.LastSyncDuration, &out.LastSyncDuration + *out = new(metav1.Duration) + **out = **in + } + if in.NextSyncTime != nil { + in, out := &in.NextSyncTime, &out.NextSyncTime + *out = (*in).DeepCopy() + } + if in.CurrentRunStartTime != nil { + in, out := &in.CurrentRunStartTime, &out.CurrentRunStartTime + *out = (*in).DeepCopy() + } + if in.LatestMoverStatus != nil { + in, out := &in.LatestMoverStatus, &out.LatestMoverStatus + *out = new(MoverStatus) + **out = **in + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PVCBackupStatus. +func (in *PVCBackupStatus) DeepCopy() *PVCBackupStatus { + if in == nil { + return nil + } + out := new(PVCBackupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Restore) DeepCopyInto(out *Restore) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Restore. +func (in *Restore) DeepCopy() *Restore { + if in == nil { + return nil + } + out := new(Restore) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *Restore) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreList) DeepCopyInto(out *RestoreList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]Restore, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreList. +func (in *RestoreList) DeepCopy() *RestoreList { + if in == nil { + return nil + } + out := new(RestoreList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *RestoreList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreSpec) DeepCopyInto(out *RestoreSpec) { + *out = *in + out.Size = in.Size.DeepCopy() +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreSpec. +func (in *RestoreSpec) DeepCopy() *RestoreSpec { + if in == nil { + return nil + } + out := new(RestoreSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreStatus) DeepCopyInto(out *RestoreStatus) { + *out = *in + if in.StartTime != nil { + in, out := &in.StartTime, &out.StartTime + *out = (*in).DeepCopy() + } + if in.CompletionTime != nil { + in, out := &in.CompletionTime, &out.CompletionTime + *out = (*in).DeepCopy() + } + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]metav1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreStatus. +func (in *RestoreStatus) DeepCopy() *RestoreStatus { + if in == nil { + return nil + } + out := new(RestoreStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RetentionSpec) DeepCopyInto(out *RetentionSpec) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RetentionSpec. +func (in *RetentionSpec) DeepCopy() *RetentionSpec { + if in == nil { + return nil + } + out := new(RetentionSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *S3Spec) DeepCopyInto(out *S3Spec) { + *out = *in + out.CredentialsSecretRef = in.CredentialsSecretRef +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new S3Spec. +func (in *S3Spec) DeepCopy() *S3Spec { + if in == nil { + return nil + } + out := new(S3Spec) + in.DeepCopyInto(out) + return out +} diff --git a/charts/topolvm/templates/controller/clusterroles.yaml b/charts/topolvm/templates/controller/clusterroles.yaml index 80e34a3b8..da23025d1 100644 --- a/charts/topolvm/templates/controller/clusterroles.yaml +++ b/charts/topolvm/templates/controller/clusterroles.yaml @@ -22,6 +22,7 @@ rules: - configmaps - persistentvolumeclaims - persistentvolumes + - secrets - services verbs: - create @@ -40,6 +41,24 @@ rules: - list - update - watch +- apiGroups: + - "" + resources: + - pods/log + verbs: + - get +- apiGroups: + - batch + resources: + - jobs + verbs: + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - apps resources: @@ -93,6 +112,38 @@ rules: - get - patch - update +- apiGroups: + - "{{ include "topolvm.pluginName" . }}" + resources: + - backupconfigs + - pvcbackups + - restores + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - "{{ include "topolvm.pluginName" . }}" + resources: + - backupconfigs/status + - pvcbackups/status + - restores/status + verbs: + - get + - patch + - update +- apiGroups: + - "{{ include "topolvm.pluginName" . }}" + resources: + - backupconfigs/finalizers + - pvcbackups/finalizers + - restores/finalizers + verbs: + - update --- # Copied from https://github.com/kubernetes-csi/external-provisioner/blob/master/deploy/kubernetes/rbac.yaml kind: ClusterRole diff --git a/charts/topolvm/templates/controller/deployment.yaml b/charts/topolvm/templates/controller/deployment.yaml index df4e8128d..17d352718 100644 --- a/charts/topolvm/templates/controller/deployment.yaml +++ b/charts/topolvm/templates/controller/deployment.yaml @@ -78,8 +78,16 @@ spec: - --rwx-ganesha-image={{ .Values.controller.rwx.ganeshaImage }} {{- end }} {{- end }} - {{- if or .Values.useLegacy .Values.env.topolvm_controller }} + {{- if .Values.controller.backup.enabled }} + - --enable-backup + - --restic-image={{ .Values.controller.backup.resticImage }} + - --backup-mover-service-account={{ .Values.controller.backup.moverServiceAccount }} + {{- end }} env: + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace {{- if .Values.useLegacy }} - name: USE_LEGACY value: "true" @@ -87,7 +95,6 @@ spec: {{- with .Values.env.topolvm_controller }} {{- toYaml . | nindent 12 }} {{- end }} - {{- end }} {{- with .Values.controller.args }} args: {{ toYaml . | nindent 12 }} {{- end }} diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml new file mode 100644 index 000000000..b8a3ce528 --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml @@ -0,0 +1,303 @@ +{{ if .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: backupconfigs.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: BackupConfig + listKind: BackupConfigList + plural: backupconfigs + singular: backupconfig + scope: Cluster + versions: + - name: v1 + schema: + openAPIV3Schema: + description: |- + BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore + via restic. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BackupConfigSpec defines the cluster-wide backup configuration. A single + BackupConfig named "default" is expected; additional BackupConfigs are + ignored by the controller. + properties: + keepSnapshotAfterBackup: + default: false + description: |- + KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + the backup is preserved after restic completes. When false (default) the + snapshot is deleted once the backup finishes, regardless of outcome. + Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + type: boolean + resticPasswordSecretRef: + description: |- + ResticPasswordSecretRef references a Secret with a single "password" key + used as the restic repository password. Losing this secret makes existing + backups unreadable. + properties: + name: + description: name is unique within a namespace to reference a + secret resource. + type: string + namespace: + description: namespace defines the space within which the secret + name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + retention: + description: |- + Retention is the default retention policy. Per-PVC annotations of the + form "topolvm.io/backup-retention-" override individual buckets. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + s3: + description: S3 is the remote object store configuration. + properties: + bucket: + description: |- + Bucket is the target bucket name. One restic repository per PVC is + created under the key prefix "//". + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + the topolvm-controller. + properties: + name: + description: name is unique within a namespace to reference + a secret resource. + type: string + namespace: + description: namespace defines the space within which the + secret name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + endpoint: + description: |- + Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + or a MinIO endpoint. Required. + type: string + insecureTLS: + description: |- + InsecureTLS disables TLS verification against the S3 endpoint. Use only + for self-signed endpoints during testing. + type: boolean + prefix: + description: |- + Prefix is an optional key prefix prepended under the bucket root before + the per-PVC "/" path. Useful for isolating CI runs that + share a bucket, e.g. prefix="ci/". + type: string + region: + description: Region is the S3 region. Optional for providers that + do not require it. + type: string + required: + - bucket + - credentialsSecretRef + - endpoint + type: object + schedule: + description: |- + Schedule is the default cron schedule applied to every backed-up PVC. + When empty, no backup CronJobs are created unless a PVC sets its own + schedule via the "topolvm.io/backup-schedule" annotation. + type: string + selector: + description: |- + Selector restricts which PVCs are backed up. An empty selector matches + every PVC bound to a TopoLVM StorageClass. PVCs annotated + "topolvm.io/backup=false" are always skipped. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + suspend: + description: |- + Suspend pauses creation of new backup Jobs without deleting existing + CronJobs or previously taken backups. + type: boolean + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + PVCs prior to backup. If empty the controller falls back to the default + VolumeSnapshotClass for the topolvm driver. + type: string + required: + - resticPasswordSecretRef + - s3 + type: object + status: + description: BackupConfigStatus reports the observed state of the backup + fleet. + properties: + conditions: + description: |- + Conditions is the list of conditions for this BackupConfig. Typical + condition types: "Ready", "CredentialsValid". + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + managedPVCs: + description: |- + ManagedPVCs is the number of PVCs the controller currently has a + backup CronJob for. + format: int32 + type: integer + observedGeneration: + description: |- + ObservedGeneration matches BackupConfig.metadata.generation when the + status was last updated. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml new file mode 100644 index 000000000..5485d94dd --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml @@ -0,0 +1,261 @@ +{{ if .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: pvcbackups.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: PVCBackup + listKind: PVCBackupList + plural: pvcbackups + shortNames: + - pvcbk + singular: pvcbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.pvcName + name: PVC + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.lastSyncTime + name: LastSync + type: date + - jsonPath: .status.nextSyncTime + name: NextSync + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: |- + PVCBackup represents an ongoing backup policy for a single PVC. The + controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at + each fire time, provisions a temp PVC from the snapshot, runs a restic + mover Job against it, and cleans up the temp PVC (and optionally the + VolumeSnapshot). All child resources are owned by the PVCBackup so + deleting it cascades cleanly. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + PVCBackupSpec defines the backup policy for a single PVC. The object is + typically owned by a BackupConfig reconciler that creates/updates one + PVCBackup per matching PVC, but users may also author PVCBackup objects + directly for one-off or bespoke schedules. + properties: + keepSnapshotAfterBackup: + description: |- + KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + mover completes. The temp PVC is always deleted. + type: boolean + pvcName: + description: |- + PVCName is the name of the source PersistentVolumeClaim in the same + namespace as this PVCBackup. + type: string + retention: + description: |- + Retention is the restic forget policy applied after each successful + backup. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + schedule: + description: |- + Schedule is a cron expression evaluated in-process by the controller. + Empty disables scheduling; the controller will not take backups. + type: string + suspend: + description: |- + Suspend pauses new backup runs without affecting the current run or + existing restic data. + type: boolean + trigger: + description: |- + Trigger forces a one-shot run. Setting this to a new value that + differs from status.lastHandledTrigger causes the controller to run a + backup immediately, regardless of the schedule. A common pattern is + to set it to a timestamp. Empty means no manual trigger. + type: string + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used for the + backup snapshot. If empty the default class for the PVC's driver is + used. + type: string + required: + - pvcName + type: object + status: + description: PVCBackupStatus reports the observed state of a PVCBackup. + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + currentMoverJobName: + type: string + currentRunStartTime: + description: |- + CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + format: date-time + type: string + currentSnapshotName: + description: |- + CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + the child resources owned by this PVCBackup during an active run. + type: string + currentTempPVCName: + type: string + lastHandledTrigger: + description: |- + LastHandledTrigger mirrors .spec.trigger the last time a manual run + was accepted, so repeated reconciles of the same trigger value don't + retrigger backups. + type: string + lastSyncDuration: + description: LastSyncDuration is how long the most recent successful + backup took. + type: string + lastSyncTime: + description: LastSyncTime is when the most recent backup completed + successfully. + format: date-time + type: string + latestMoverStatus: + description: LatestMoverStatus mirrors the final state of the most + recently completed mover Job. + properties: + jobName: + type: string + logs: + type: string + succeeded: + type: boolean + type: object + message: + type: string + nextSyncTime: + description: NextSyncTime is the next scheduled fire time based on + .spec.schedule. + format: date-time + type: string + observedGeneration: + format: int64 + type: integer + phase: + description: PVCBackupPhase is the high-level phase of a PVCBackup + reconciliation. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml new file mode 100644 index 000000000..e548dd3c6 --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml @@ -0,0 +1,185 @@ +{{ if .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: restores.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: Restore + listKind: RestoreList + plural: restores + singular: restore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.sourcePVCName + name: Source + type: string + - jsonPath: .spec.targetPVCName + name: Target + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: Restore is the Schema for restic-backed PVC restore operations. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + RestoreSpec defines a single restore operation from a restic repository + back into a fresh PersistentVolumeClaim. + properties: + size: + anyOf: + - type: integer + - type: string + description: |- + Size is the capacity for the target PVC. It should be at least as large + as the source. + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + snapshotID: + description: |- + SnapshotID is the restic snapshot id to restore. If empty, "latest" is + used. + type: string + sourceNamespace: + description: |- + SourceNamespace is the namespace of the PVC whose backups should be + restored. The restic repository key is "/". + type: string + sourcePVCName: + description: SourcePVCName is the name of the original PVC that was + backed up. + type: string + storageClassName: + description: |- + StorageClassName is the StorageClass for the target PVC. Must reference + a TopoLVM StorageClass. + type: string + targetPVCName: + description: |- + TargetPVCName is the name of the PVC to create in this Restore's + namespace. The controller provisions this PVC with the given size and + storage class, then mounts it into the restic restore Job. + type: string + required: + - size + - sourceNamespace + - sourcePVCName + - storageClassName + - targetPVCName + type: object + status: + description: RestoreStatus reports the observed state of a Restore. + properties: + completionTime: + description: CompletionTime is when the restore Job reached a terminal + state. + format: date-time + type: string + conditions: + description: Conditions is the list of conditions for this Restore. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + jobName: + description: JobName is the name of the Job running the restic restore. + type: string + message: + description: Message is a human-readable explanation of the current + phase. + type: string + phase: + description: RestorePhase captures the coarse state of a Restore. + type: string + startTime: + description: StartTime is when the restore Job was created. + format: date-time + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml b/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml new file mode 100644 index 000000000..7be78466e --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml @@ -0,0 +1,303 @@ +{{ if not .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: backupconfigs.topolvm.io +spec: + group: topolvm.io + names: + kind: BackupConfig + listKind: BackupConfigList + plural: backupconfigs + singular: backupconfig + scope: Cluster + versions: + - name: v1 + schema: + openAPIV3Schema: + description: |- + BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore + via restic. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BackupConfigSpec defines the cluster-wide backup configuration. A single + BackupConfig named "default" is expected; additional BackupConfigs are + ignored by the controller. + properties: + keepSnapshotAfterBackup: + default: false + description: |- + KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + the backup is preserved after restic completes. When false (default) the + snapshot is deleted once the backup finishes, regardless of outcome. + Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + type: boolean + resticPasswordSecretRef: + description: |- + ResticPasswordSecretRef references a Secret with a single "password" key + used as the restic repository password. Losing this secret makes existing + backups unreadable. + properties: + name: + description: name is unique within a namespace to reference a + secret resource. + type: string + namespace: + description: namespace defines the space within which the secret + name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + retention: + description: |- + Retention is the default retention policy. Per-PVC annotations of the + form "topolvm.io/backup-retention-" override individual buckets. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + s3: + description: S3 is the remote object store configuration. + properties: + bucket: + description: |- + Bucket is the target bucket name. One restic repository per PVC is + created under the key prefix "//". + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + the topolvm-controller. + properties: + name: + description: name is unique within a namespace to reference + a secret resource. + type: string + namespace: + description: namespace defines the space within which the + secret name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + endpoint: + description: |- + Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + or a MinIO endpoint. Required. + type: string + insecureTLS: + description: |- + InsecureTLS disables TLS verification against the S3 endpoint. Use only + for self-signed endpoints during testing. + type: boolean + prefix: + description: |- + Prefix is an optional key prefix prepended under the bucket root before + the per-PVC "/" path. Useful for isolating CI runs that + share a bucket, e.g. prefix="ci/". + type: string + region: + description: Region is the S3 region. Optional for providers that + do not require it. + type: string + required: + - bucket + - credentialsSecretRef + - endpoint + type: object + schedule: + description: |- + Schedule is the default cron schedule applied to every backed-up PVC. + When empty, no backup CronJobs are created unless a PVC sets its own + schedule via the "topolvm.io/backup-schedule" annotation. + type: string + selector: + description: |- + Selector restricts which PVCs are backed up. An empty selector matches + every PVC bound to a TopoLVM StorageClass. PVCs annotated + "topolvm.io/backup=false" are always skipped. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + suspend: + description: |- + Suspend pauses creation of new backup Jobs without deleting existing + CronJobs or previously taken backups. + type: boolean + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + PVCs prior to backup. If empty the controller falls back to the default + VolumeSnapshotClass for the topolvm driver. + type: string + required: + - resticPasswordSecretRef + - s3 + type: object + status: + description: BackupConfigStatus reports the observed state of the backup + fleet. + properties: + conditions: + description: |- + Conditions is the list of conditions for this BackupConfig. Typical + condition types: "Ready", "CredentialsValid". + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + managedPVCs: + description: |- + ManagedPVCs is the number of PVCs the controller currently has a + backup CronJob for. + format: int32 + type: integer + observedGeneration: + description: |- + ObservedGeneration matches BackupConfig.metadata.generation when the + status was last updated. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml b/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml new file mode 100644 index 000000000..90843c5b2 --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml @@ -0,0 +1,261 @@ +{{ if not .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: pvcbackups.topolvm.io +spec: + group: topolvm.io + names: + kind: PVCBackup + listKind: PVCBackupList + plural: pvcbackups + shortNames: + - pvcbk + singular: pvcbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.pvcName + name: PVC + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.lastSyncTime + name: LastSync + type: date + - jsonPath: .status.nextSyncTime + name: NextSync + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: |- + PVCBackup represents an ongoing backup policy for a single PVC. The + controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at + each fire time, provisions a temp PVC from the snapshot, runs a restic + mover Job against it, and cleans up the temp PVC (and optionally the + VolumeSnapshot). All child resources are owned by the PVCBackup so + deleting it cascades cleanly. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + PVCBackupSpec defines the backup policy for a single PVC. The object is + typically owned by a BackupConfig reconciler that creates/updates one + PVCBackup per matching PVC, but users may also author PVCBackup objects + directly for one-off or bespoke schedules. + properties: + keepSnapshotAfterBackup: + description: |- + KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + mover completes. The temp PVC is always deleted. + type: boolean + pvcName: + description: |- + PVCName is the name of the source PersistentVolumeClaim in the same + namespace as this PVCBackup. + type: string + retention: + description: |- + Retention is the restic forget policy applied after each successful + backup. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + schedule: + description: |- + Schedule is a cron expression evaluated in-process by the controller. + Empty disables scheduling; the controller will not take backups. + type: string + suspend: + description: |- + Suspend pauses new backup runs without affecting the current run or + existing restic data. + type: boolean + trigger: + description: |- + Trigger forces a one-shot run. Setting this to a new value that + differs from status.lastHandledTrigger causes the controller to run a + backup immediately, regardless of the schedule. A common pattern is + to set it to a timestamp. Empty means no manual trigger. + type: string + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used for the + backup snapshot. If empty the default class for the PVC's driver is + used. + type: string + required: + - pvcName + type: object + status: + description: PVCBackupStatus reports the observed state of a PVCBackup. + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + currentMoverJobName: + type: string + currentRunStartTime: + description: |- + CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + format: date-time + type: string + currentSnapshotName: + description: |- + CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + the child resources owned by this PVCBackup during an active run. + type: string + currentTempPVCName: + type: string + lastHandledTrigger: + description: |- + LastHandledTrigger mirrors .spec.trigger the last time a manual run + was accepted, so repeated reconciles of the same trigger value don't + retrigger backups. + type: string + lastSyncDuration: + description: LastSyncDuration is how long the most recent successful + backup took. + type: string + lastSyncTime: + description: LastSyncTime is when the most recent backup completed + successfully. + format: date-time + type: string + latestMoverStatus: + description: LatestMoverStatus mirrors the final state of the most + recently completed mover Job. + properties: + jobName: + type: string + logs: + type: string + succeeded: + type: boolean + type: object + message: + type: string + nextSyncTime: + description: NextSyncTime is the next scheduled fire time based on + .spec.schedule. + format: date-time + type: string + observedGeneration: + format: int64 + type: integer + phase: + description: PVCBackupPhase is the high-level phase of a PVCBackup + reconciliation. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/templates/crds/topolvm.io_restores.yaml b/charts/topolvm/templates/crds/topolvm.io_restores.yaml new file mode 100644 index 000000000..65be9c711 --- /dev/null +++ b/charts/topolvm/templates/crds/topolvm.io_restores.yaml @@ -0,0 +1,185 @@ +{{ if not .Values.useLegacy }} +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: restores.topolvm.io +spec: + group: topolvm.io + names: + kind: Restore + listKind: RestoreList + plural: restores + singular: restore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.sourcePVCName + name: Source + type: string + - jsonPath: .spec.targetPVCName + name: Target + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: Restore is the Schema for restic-backed PVC restore operations. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + RestoreSpec defines a single restore operation from a restic repository + back into a fresh PersistentVolumeClaim. + properties: + size: + anyOf: + - type: integer + - type: string + description: |- + Size is the capacity for the target PVC. It should be at least as large + as the source. + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + snapshotID: + description: |- + SnapshotID is the restic snapshot id to restore. If empty, "latest" is + used. + type: string + sourceNamespace: + description: |- + SourceNamespace is the namespace of the PVC whose backups should be + restored. The restic repository key is "/". + type: string + sourcePVCName: + description: SourcePVCName is the name of the original PVC that was + backed up. + type: string + storageClassName: + description: |- + StorageClassName is the StorageClass for the target PVC. Must reference + a TopoLVM StorageClass. + type: string + targetPVCName: + description: |- + TargetPVCName is the name of the PVC to create in this Restore's + namespace. The controller provisions this PVC with the given size and + storage class, then mounts it into the restic restore Job. + type: string + required: + - size + - sourceNamespace + - sourcePVCName + - storageClassName + - targetPVCName + type: object + status: + description: RestoreStatus reports the observed state of a Restore. + properties: + completionTime: + description: CompletionTime is when the restore Job reached a terminal + state. + format: date-time + type: string + conditions: + description: Conditions is the list of conditions for this Restore. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + jobName: + description: JobName is the name of the Job running the restic restore. + type: string + message: + description: Message is a human-readable explanation of the current + phase. + type: string + phase: + description: RestorePhase captures the coarse state of a Restore. + type: string + startTime: + description: StartTime is when the restore Job was created. + format: date-time + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} +{{ end }} + diff --git a/charts/topolvm/values.yaml b/charts/topolvm/values.yaml index 8b768892c..e57a20a7b 100644 --- a/charts/topolvm/values.yaml +++ b/charts/topolvm/values.yaml @@ -455,6 +455,22 @@ controller: # Leave empty to use the controller's compiled-in default. ganeshaImage: "" + backup: + # controller.backup.enabled -- Enable the BackupConfig/PVCBackup/Restore controllers. + # When true, the controller watches the cluster-scoped BackupConfig named + # `default` and drives restic-based backups of matching PVCs to S3. + enabled: false + + # controller.backup.resticImage -- Container image used for the mover and + # restore Jobs. Must contain the `restic` binary. + resticImage: "restic/restic:0.17.3" + + # controller.backup.moverServiceAccount -- ServiceAccount under which the + # mover and restore Jobs run in each target namespace. Must already exist + # (or be created separately) in every namespace that contains a backed-up + # PVC. Defaults to the namespace's `default` ServiceAccount. + moverServiceAccount: "default" + leaderElection: # controller.leaderElection.enabled -- Enable leader election for controller and all sidecars. enabled: true diff --git a/cmd/topolvm-controller/app/root.go b/cmd/topolvm-controller/app/root.go index a67cba66e..c4b717f38 100644 --- a/cmd/topolvm-controller/app/root.go +++ b/cmd/topolvm-controller/app/root.go @@ -51,6 +51,10 @@ var config struct { profilingBindAddress string enableRWX bool rwxGaneshaImage string + enableBackup bool + resticImage string + backupMoverServiceAccount string + controllerNamespace string } var rootCmd = &cobra.Command{ @@ -95,6 +99,10 @@ func init() { fs.StringVar(&config.profilingBindAddress, "profiling-bind-address", "", "Bind pprof profiling to the given network address. If empty, profiling is disabled.") fs.BoolVar(&config.enableRWX, "enable-rwx", false, "Enable the NFS-backed ReadWriteMany flow. Requires csi-driver-nfs in the cluster.") fs.StringVar(&config.rwxGaneshaImage, "rwx-ganesha-image", "", "Container image for the per-volume NFS server. Empty uses the default.") + fs.BoolVar(&config.enableBackup, "enable-backup", false, "Enable BackupConfig/PVCBackup/Restore controllers for restic-based backup to S3.") + fs.StringVar(&config.resticImage, "restic-image", topolvm.DefaultResticImage, "Container image used for backup/restore mover Jobs.") + fs.StringVar(&config.backupMoverServiceAccount, "backup-mover-service-account", "default", "ServiceAccount used by backup/restore Jobs in each target namespace.") + fs.StringVar(&config.controllerNamespace, "controller-namespace", "", "Namespace where the topolvm-controller runs and where backup Secrets are sourced. Defaults to POD_NAMESPACE env var.") driver.QuantityVar(fs, &config.controllerServerSettings.Block, "minimum-allocation-block", diff --git a/cmd/topolvm-controller/app/run.go b/cmd/topolvm-controller/app/run.go index 15aca3331..3bdebdf81 100644 --- a/cmd/topolvm-controller/app/run.go +++ b/cmd/topolvm-controller/app/run.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net" + "os" "time" "github.com/container-storage-interface/spec/lib/go/csi" @@ -130,6 +131,21 @@ func subMain() error { } } + if config.enableBackup { + ns := config.controllerNamespace + if ns == "" { + ns = os.Getenv("POD_NAMESPACE") + } + if ns == "" { + setupLog.Error(nil, "backup controllers require --controller-namespace or POD_NAMESPACE to be set") + return fmt.Errorf("controller namespace is required when --enable-backup is set") + } + if err := controller.SetupBackupReconcilers(mgr, client, apiReader, ns, config.resticImage, config.backupMoverServiceAccount); err != nil { + setupLog.Error(err, "unable to create controllers", "controller", "Backup") + return err + } + } + //+kubebuilder:scaffold:builder // Add health checker to manager diff --git a/config/crd/bases/topolvm.cybozu.com_backupconfigs.yaml b/config/crd/bases/topolvm.cybozu.com_backupconfigs.yaml new file mode 100644 index 000000000..1cfc96ab7 --- /dev/null +++ b/config/crd/bases/topolvm.cybozu.com_backupconfigs.yaml @@ -0,0 +1,300 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: backupconfigs.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: BackupConfig + listKind: BackupConfigList + plural: backupconfigs + singular: backupconfig + scope: Cluster + versions: + - name: v1 + schema: + openAPIV3Schema: + description: |- + BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore + via restic. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BackupConfigSpec defines the cluster-wide backup configuration. A single + BackupConfig named "default" is expected; additional BackupConfigs are + ignored by the controller. + properties: + keepSnapshotAfterBackup: + default: false + description: |- + KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + the backup is preserved after restic completes. When false (default) the + snapshot is deleted once the backup finishes, regardless of outcome. + Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + type: boolean + resticPasswordSecretRef: + description: |- + ResticPasswordSecretRef references a Secret with a single "password" key + used as the restic repository password. Losing this secret makes existing + backups unreadable. + properties: + name: + description: name is unique within a namespace to reference a + secret resource. + type: string + namespace: + description: namespace defines the space within which the secret + name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + retention: + description: |- + Retention is the default retention policy. Per-PVC annotations of the + form "topolvm.io/backup-retention-" override individual buckets. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + s3: + description: S3 is the remote object store configuration. + properties: + bucket: + description: |- + Bucket is the target bucket name. One restic repository per PVC is + created under the key prefix "//". + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + the topolvm-controller. + properties: + name: + description: name is unique within a namespace to reference + a secret resource. + type: string + namespace: + description: namespace defines the space within which the + secret name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + endpoint: + description: |- + Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + or a MinIO endpoint. Required. + type: string + insecureTLS: + description: |- + InsecureTLS disables TLS verification against the S3 endpoint. Use only + for self-signed endpoints during testing. + type: boolean + prefix: + description: |- + Prefix is an optional key prefix prepended under the bucket root before + the per-PVC "/" path. Useful for isolating CI runs that + share a bucket, e.g. prefix="ci/". + type: string + region: + description: Region is the S3 region. Optional for providers that + do not require it. + type: string + required: + - bucket + - credentialsSecretRef + - endpoint + type: object + schedule: + description: |- + Schedule is the default cron schedule applied to every backed-up PVC. + When empty, no backup CronJobs are created unless a PVC sets its own + schedule via the "topolvm.io/backup-schedule" annotation. + type: string + selector: + description: |- + Selector restricts which PVCs are backed up. An empty selector matches + every PVC bound to a TopoLVM StorageClass. PVCs annotated + "topolvm.io/backup=false" are always skipped. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + suspend: + description: |- + Suspend pauses creation of new backup Jobs without deleting existing + CronJobs or previously taken backups. + type: boolean + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + PVCs prior to backup. If empty the controller falls back to the default + VolumeSnapshotClass for the topolvm driver. + type: string + required: + - resticPasswordSecretRef + - s3 + type: object + status: + description: BackupConfigStatus reports the observed state of the backup + fleet. + properties: + conditions: + description: |- + Conditions is the list of conditions for this BackupConfig. Typical + condition types: "Ready", "CredentialsValid". + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + managedPVCs: + description: |- + ManagedPVCs is the number of PVCs the controller currently has a + backup CronJob for. + format: int32 + type: integer + observedGeneration: + description: |- + ObservedGeneration matches BackupConfig.metadata.generation when the + status was last updated. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/topolvm.cybozu.com_pvcbackups.yaml b/config/crd/bases/topolvm.cybozu.com_pvcbackups.yaml new file mode 100644 index 000000000..7bdfaf08d --- /dev/null +++ b/config/crd/bases/topolvm.cybozu.com_pvcbackups.yaml @@ -0,0 +1,258 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: pvcbackups.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: PVCBackup + listKind: PVCBackupList + plural: pvcbackups + shortNames: + - pvcbk + singular: pvcbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.pvcName + name: PVC + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.lastSyncTime + name: LastSync + type: date + - jsonPath: .status.nextSyncTime + name: NextSync + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: |- + PVCBackup represents an ongoing backup policy for a single PVC. The + controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at + each fire time, provisions a temp PVC from the snapshot, runs a restic + mover Job against it, and cleans up the temp PVC (and optionally the + VolumeSnapshot). All child resources are owned by the PVCBackup so + deleting it cascades cleanly. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + PVCBackupSpec defines the backup policy for a single PVC. The object is + typically owned by a BackupConfig reconciler that creates/updates one + PVCBackup per matching PVC, but users may also author PVCBackup objects + directly for one-off or bespoke schedules. + properties: + keepSnapshotAfterBackup: + description: |- + KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + mover completes. The temp PVC is always deleted. + type: boolean + pvcName: + description: |- + PVCName is the name of the source PersistentVolumeClaim in the same + namespace as this PVCBackup. + type: string + retention: + description: |- + Retention is the restic forget policy applied after each successful + backup. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + schedule: + description: |- + Schedule is a cron expression evaluated in-process by the controller. + Empty disables scheduling; the controller will not take backups. + type: string + suspend: + description: |- + Suspend pauses new backup runs without affecting the current run or + existing restic data. + type: boolean + trigger: + description: |- + Trigger forces a one-shot run. Setting this to a new value that + differs from status.lastHandledTrigger causes the controller to run a + backup immediately, regardless of the schedule. A common pattern is + to set it to a timestamp. Empty means no manual trigger. + type: string + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used for the + backup snapshot. If empty the default class for the PVC's driver is + used. + type: string + required: + - pvcName + type: object + status: + description: PVCBackupStatus reports the observed state of a PVCBackup. + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + currentMoverJobName: + type: string + currentRunStartTime: + description: |- + CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + format: date-time + type: string + currentSnapshotName: + description: |- + CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + the child resources owned by this PVCBackup during an active run. + type: string + currentTempPVCName: + type: string + lastHandledTrigger: + description: |- + LastHandledTrigger mirrors .spec.trigger the last time a manual run + was accepted, so repeated reconciles of the same trigger value don't + retrigger backups. + type: string + lastSyncDuration: + description: LastSyncDuration is how long the most recent successful + backup took. + type: string + lastSyncTime: + description: LastSyncTime is when the most recent backup completed + successfully. + format: date-time + type: string + latestMoverStatus: + description: LatestMoverStatus mirrors the final state of the most + recently completed mover Job. + properties: + jobName: + type: string + logs: + type: string + succeeded: + type: boolean + type: object + message: + type: string + nextSyncTime: + description: NextSyncTime is the next scheduled fire time based on + .spec.schedule. + format: date-time + type: string + observedGeneration: + format: int64 + type: integer + phase: + description: PVCBackupPhase is the high-level phase of a PVCBackup + reconciliation. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/topolvm.cybozu.com_restores.yaml b/config/crd/bases/topolvm.cybozu.com_restores.yaml new file mode 100644 index 000000000..cd9f5792d --- /dev/null +++ b/config/crd/bases/topolvm.cybozu.com_restores.yaml @@ -0,0 +1,182 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: restores.topolvm.cybozu.com +spec: + group: topolvm.cybozu.com + names: + kind: Restore + listKind: RestoreList + plural: restores + singular: restore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.sourcePVCName + name: Source + type: string + - jsonPath: .spec.targetPVCName + name: Target + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: Restore is the Schema for restic-backed PVC restore operations. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + RestoreSpec defines a single restore operation from a restic repository + back into a fresh PersistentVolumeClaim. + properties: + size: + anyOf: + - type: integer + - type: string + description: |- + Size is the capacity for the target PVC. It should be at least as large + as the source. + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + snapshotID: + description: |- + SnapshotID is the restic snapshot id to restore. If empty, "latest" is + used. + type: string + sourceNamespace: + description: |- + SourceNamespace is the namespace of the PVC whose backups should be + restored. The restic repository key is "/". + type: string + sourcePVCName: + description: SourcePVCName is the name of the original PVC that was + backed up. + type: string + storageClassName: + description: |- + StorageClassName is the StorageClass for the target PVC. Must reference + a TopoLVM StorageClass. + type: string + targetPVCName: + description: |- + TargetPVCName is the name of the PVC to create in this Restore's + namespace. The controller provisions this PVC with the given size and + storage class, then mounts it into the restic restore Job. + type: string + required: + - size + - sourceNamespace + - sourcePVCName + - storageClassName + - targetPVCName + type: object + status: + description: RestoreStatus reports the observed state of a Restore. + properties: + completionTime: + description: CompletionTime is when the restore Job reached a terminal + state. + format: date-time + type: string + conditions: + description: Conditions is the list of conditions for this Restore. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + jobName: + description: JobName is the name of the Job running the restic restore. + type: string + message: + description: Message is a human-readable explanation of the current + phase. + type: string + phase: + description: RestorePhase captures the coarse state of a Restore. + type: string + startTime: + description: StartTime is when the restore Job was created. + format: date-time + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/topolvm.io_backupconfigs.yaml b/config/crd/bases/topolvm.io_backupconfigs.yaml new file mode 100644 index 000000000..de85a4572 --- /dev/null +++ b/config/crd/bases/topolvm.io_backupconfigs.yaml @@ -0,0 +1,300 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: backupconfigs.topolvm.io +spec: + group: topolvm.io + names: + kind: BackupConfig + listKind: BackupConfigList + plural: backupconfigs + singular: backupconfig + scope: Cluster + versions: + - name: v1 + schema: + openAPIV3Schema: + description: |- + BackupConfig is the cluster-scoped configuration for TopoLVM backup/restore + via restic. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + BackupConfigSpec defines the cluster-wide backup configuration. A single + BackupConfig named "default" is expected; additional BackupConfigs are + ignored by the controller. + properties: + keepSnapshotAfterBackup: + default: false + description: |- + KeepSnapshotAfterBackup controls whether the VolumeSnapshot created for + the backup is preserved after restic completes. When false (default) the + snapshot is deleted once the backup finishes, regardless of outcome. + Can be overridden per-PVC via "topolvm.io/backup-keep-snapshot". + type: boolean + resticPasswordSecretRef: + description: |- + ResticPasswordSecretRef references a Secret with a single "password" key + used as the restic repository password. Losing this secret makes existing + backups unreadable. + properties: + name: + description: name is unique within a namespace to reference a + secret resource. + type: string + namespace: + description: namespace defines the space within which the secret + name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + retention: + description: |- + Retention is the default retention policy. Per-PVC annotations of the + form "topolvm.io/backup-retention-" override individual buckets. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + s3: + description: S3 is the remote object store configuration. + properties: + bucket: + description: |- + Bucket is the target bucket name. One restic repository per PVC is + created under the key prefix "//". + type: string + credentialsSecretRef: + description: |- + CredentialsSecretRef references a Secret containing AWS_ACCESS_KEY_ID and + AWS_SECRET_ACCESS_KEY keys. The secret must live in the same namespace as + the topolvm-controller. + properties: + name: + description: name is unique within a namespace to reference + a secret resource. + type: string + namespace: + description: namespace defines the space within which the + secret name must be unique. + type: string + type: object + x-kubernetes-map-type: atomic + endpoint: + description: |- + Endpoint is the S3 endpoint URL, e.g. "https://s3.us-east-1.amazonaws.com" + or a MinIO endpoint. Required. + type: string + insecureTLS: + description: |- + InsecureTLS disables TLS verification against the S3 endpoint. Use only + for self-signed endpoints during testing. + type: boolean + prefix: + description: |- + Prefix is an optional key prefix prepended under the bucket root before + the per-PVC "/" path. Useful for isolating CI runs that + share a bucket, e.g. prefix="ci/". + type: string + region: + description: Region is the S3 region. Optional for providers that + do not require it. + type: string + required: + - bucket + - credentialsSecretRef + - endpoint + type: object + schedule: + description: |- + Schedule is the default cron schedule applied to every backed-up PVC. + When empty, no backup CronJobs are created unless a PVC sets its own + schedule via the "topolvm.io/backup-schedule" annotation. + type: string + selector: + description: |- + Selector restricts which PVCs are backed up. An empty selector matches + every PVC bound to a TopoLVM StorageClass. PVCs annotated + "topolvm.io/backup=false" are always skipped. + properties: + matchExpressions: + description: matchExpressions is a list of label selector requirements. + The requirements are ANDed. + items: + description: |- + A label selector requirement is a selector that contains values, a key, and an operator that + relates the key and values. + properties: + key: + description: key is the label key that the selector applies + to. + type: string + operator: + description: |- + operator represents a key's relationship to a set of values. + Valid operators are In, NotIn, Exists and DoesNotExist. + type: string + values: + description: |- + values is an array of string values. If the operator is In or NotIn, + the values array must be non-empty. If the operator is Exists or DoesNotExist, + the values array must be empty. This array is replaced during a strategic + merge patch. + items: + type: string + type: array + x-kubernetes-list-type: atomic + required: + - key + - operator + type: object + type: array + x-kubernetes-list-type: atomic + matchLabels: + additionalProperties: + type: string + description: |- + matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels + map is equivalent to an element of matchExpressions, whose key field is "key", the + operator is "In", and the values array contains only "value". The requirements are ANDed. + type: object + type: object + x-kubernetes-map-type: atomic + suspend: + description: |- + Suspend pauses creation of new backup Jobs without deleting existing + CronJobs or previously taken backups. + type: boolean + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used to snapshot + PVCs prior to backup. If empty the controller falls back to the default + VolumeSnapshotClass for the topolvm driver. + type: string + required: + - resticPasswordSecretRef + - s3 + type: object + status: + description: BackupConfigStatus reports the observed state of the backup + fleet. + properties: + conditions: + description: |- + Conditions is the list of conditions for this BackupConfig. Typical + condition types: "Ready", "CredentialsValid". + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + managedPVCs: + description: |- + ManagedPVCs is the number of PVCs the controller currently has a + backup CronJob for. + format: int32 + type: integer + observedGeneration: + description: |- + ObservedGeneration matches BackupConfig.metadata.generation when the + status was last updated. + format: int64 + type: integer + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/topolvm.io_pvcbackups.yaml b/config/crd/bases/topolvm.io_pvcbackups.yaml new file mode 100644 index 000000000..fb8f7b516 --- /dev/null +++ b/config/crd/bases/topolvm.io_pvcbackups.yaml @@ -0,0 +1,258 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: pvcbackups.topolvm.io +spec: + group: topolvm.io + names: + kind: PVCBackup + listKind: PVCBackupList + plural: pvcbackups + shortNames: + - pvcbk + singular: pvcbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.pvcName + name: PVC + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.lastSyncTime + name: LastSync + type: date + - jsonPath: .status.nextSyncTime + name: NextSync + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: |- + PVCBackup represents an ongoing backup policy for a single PVC. The + controller evaluates .spec.schedule in-process, takes a VolumeSnapshot at + each fire time, provisions a temp PVC from the snapshot, runs a restic + mover Job against it, and cleans up the temp PVC (and optionally the + VolumeSnapshot). All child resources are owned by the PVCBackup so + deleting it cascades cleanly. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + PVCBackupSpec defines the backup policy for a single PVC. The object is + typically owned by a BackupConfig reconciler that creates/updates one + PVCBackup per matching PVC, but users may also author PVCBackup objects + directly for one-off or bespoke schedules. + properties: + keepSnapshotAfterBackup: + description: |- + KeepSnapshotAfterBackup leaves the VolumeSnapshot in place after the + mover completes. The temp PVC is always deleted. + type: boolean + pvcName: + description: |- + PVCName is the name of the source PersistentVolumeClaim in the same + namespace as this PVCBackup. + type: string + retention: + description: |- + Retention is the restic forget policy applied after each successful + backup. + properties: + keepDaily: + format: int32 + minimum: 0 + type: integer + keepHourly: + format: int32 + minimum: 0 + type: integer + keepLast: + format: int32 + minimum: 0 + type: integer + keepMonthly: + format: int32 + minimum: 0 + type: integer + keepWeekly: + format: int32 + minimum: 0 + type: integer + keepYearly: + format: int32 + minimum: 0 + type: integer + type: object + schedule: + description: |- + Schedule is a cron expression evaluated in-process by the controller. + Empty disables scheduling; the controller will not take backups. + type: string + suspend: + description: |- + Suspend pauses new backup runs without affecting the current run or + existing restic data. + type: boolean + trigger: + description: |- + Trigger forces a one-shot run. Setting this to a new value that + differs from status.lastHandledTrigger causes the controller to run a + backup immediately, regardless of the schedule. A common pattern is + to set it to a timestamp. Empty means no manual trigger. + type: string + volumeSnapshotClassName: + description: |- + VolumeSnapshotClassName is the VolumeSnapshotClass used for the + backup snapshot. If empty the default class for the PVC's driver is + used. + type: string + required: + - pvcName + type: object + status: + description: PVCBackupStatus reports the observed state of a PVCBackup. + properties: + conditions: + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + currentMoverJobName: + type: string + currentRunStartTime: + description: |- + CurrentRunStartTime is the .metadata.creationTimestamp of the in-flight + VolumeSnapshot/temp PVC/mover Job, if any. Nil when phase=Idle|Synced|Failed. + format: date-time + type: string + currentSnapshotName: + description: |- + CurrentSnapshotName, CurrentTempPVCName, CurrentMoverJobName track + the child resources owned by this PVCBackup during an active run. + type: string + currentTempPVCName: + type: string + lastHandledTrigger: + description: |- + LastHandledTrigger mirrors .spec.trigger the last time a manual run + was accepted, so repeated reconciles of the same trigger value don't + retrigger backups. + type: string + lastSyncDuration: + description: LastSyncDuration is how long the most recent successful + backup took. + type: string + lastSyncTime: + description: LastSyncTime is when the most recent backup completed + successfully. + format: date-time + type: string + latestMoverStatus: + description: LatestMoverStatus mirrors the final state of the most + recently completed mover Job. + properties: + jobName: + type: string + logs: + type: string + succeeded: + type: boolean + type: object + message: + type: string + nextSyncTime: + description: NextSyncTime is the next scheduled fire time based on + .spec.schedule. + format: date-time + type: string + observedGeneration: + format: int64 + type: integer + phase: + description: PVCBackupPhase is the high-level phase of a PVCBackup + reconciliation. + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/topolvm.io_restores.yaml b/config/crd/bases/topolvm.io_restores.yaml new file mode 100644 index 000000000..92c74ac97 --- /dev/null +++ b/config/crd/bases/topolvm.io_restores.yaml @@ -0,0 +1,182 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.19.0 + name: restores.topolvm.io +spec: + group: topolvm.io + names: + kind: Restore + listKind: RestoreList + plural: restores + singular: restore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.sourcePVCName + name: Source + type: string + - jsonPath: .spec.targetPVCName + name: Target + type: string + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1 + schema: + openAPIV3Schema: + description: Restore is the Schema for restic-backed PVC restore operations. + properties: + apiVersion: + description: |- + APIVersion defines the versioned schema of this representation of an object. + Servers should convert recognized schemas to the latest internal value, and + may reject unrecognized values. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources + type: string + kind: + description: |- + Kind is a string value representing the REST resource this object represents. + Servers may infer this from the endpoint the client submits requests to. + Cannot be updated. + In CamelCase. + More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + type: string + metadata: + type: object + spec: + description: |- + RestoreSpec defines a single restore operation from a restic repository + back into a fresh PersistentVolumeClaim. + properties: + size: + anyOf: + - type: integer + - type: string + description: |- + Size is the capacity for the target PVC. It should be at least as large + as the source. + pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ + x-kubernetes-int-or-string: true + snapshotID: + description: |- + SnapshotID is the restic snapshot id to restore. If empty, "latest" is + used. + type: string + sourceNamespace: + description: |- + SourceNamespace is the namespace of the PVC whose backups should be + restored. The restic repository key is "/". + type: string + sourcePVCName: + description: SourcePVCName is the name of the original PVC that was + backed up. + type: string + storageClassName: + description: |- + StorageClassName is the StorageClass for the target PVC. Must reference + a TopoLVM StorageClass. + type: string + targetPVCName: + description: |- + TargetPVCName is the name of the PVC to create in this Restore's + namespace. The controller provisions this PVC with the given size and + storage class, then mounts it into the restic restore Job. + type: string + required: + - size + - sourceNamespace + - sourcePVCName + - storageClassName + - targetPVCName + type: object + status: + description: RestoreStatus reports the observed state of a Restore. + properties: + completionTime: + description: CompletionTime is when the restore Job reached a terminal + state. + format: date-time + type: string + conditions: + description: Conditions is the list of conditions for this Restore. + items: + description: Condition contains details for one aspect of the current + state of this API Resource. + properties: + lastTransitionTime: + description: |- + lastTransitionTime is the last time the condition transitioned from one status to another. + This should be when the underlying condition changed. If that is not known, then using the time when the API field changed is acceptable. + format: date-time + type: string + message: + description: |- + message is a human readable message indicating details about the transition. + This may be an empty string. + maxLength: 32768 + type: string + observedGeneration: + description: |- + observedGeneration represents the .metadata.generation that the condition was set based upon. + For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date + with respect to the current state of the instance. + format: int64 + minimum: 0 + type: integer + reason: + description: |- + reason contains a programmatic identifier indicating the reason for the condition's last transition. + Producers of specific condition types may define expected values and meanings for this field, + and whether the values are considered a guaranteed API. + The value should be a CamelCase string. + This field may not be empty. + maxLength: 1024 + minLength: 1 + pattern: ^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$ + type: string + status: + description: status of the condition, one of True, False, Unknown. + enum: + - "True" + - "False" + - Unknown + type: string + type: + description: type of condition in CamelCase or in foo.example.com/CamelCase. + maxLength: 316 + pattern: ^([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*/)?(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])$ + type: string + required: + - lastTransitionTime + - message + - reason + - status + - type + type: object + type: array + jobName: + description: JobName is the name of the Job running the restic restore. + type: string + message: + description: Message is a human-readable explanation of the current + phase. + type: string + phase: + description: RestorePhase captures the coarse state of a Restore. + type: string + startTime: + description: StartTime is when the restore Job was created. + format: date-time + type: string + type: object + type: object + served: true + storage: true + subresources: + status: {} diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index cab365ff3..56e52c19f 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -10,6 +10,7 @@ rules: - configmaps - persistentvolumeclaims - persistentvolumes + - secrets - services verbs: - create @@ -38,6 +39,12 @@ rules: - list - update - watch +- apiGroups: + - "" + resources: + - pods/log + verbs: + - get - apiGroups: - apps resources: @@ -50,6 +57,18 @@ rules: - patch - update - watch +- apiGroups: + - batch + resources: + - jobs + verbs: + - create + - delete + - get + - list + - patch + - update + - watch - apiGroups: - snapshot.storage.k8s.io resources: @@ -65,7 +84,6 @@ rules: - apiGroups: - storage.k8s.io resources: - - csidrivers - storageclasses verbs: - get @@ -74,10 +92,10 @@ rules: - apiGroups: - topolvm.io resources: + - backupconfigs - logicalvolumes + - restores verbs: - - create - - delete - get - list - patch @@ -86,8 +104,29 @@ rules: - apiGroups: - topolvm.io resources: + - backupconfigs/status - logicalvolumes/status + - pvcbackups/status + - restores/status verbs: - get - patch - update +- apiGroups: + - topolvm.io + resources: + - pvcbackups + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - topolvm.io + resources: + - pvcbackups/finalizers + verbs: + - update diff --git a/constants.go b/constants.go index bc217a7a5..24df60bc6 100644 --- a/constants.go +++ b/constants.go @@ -135,3 +135,43 @@ const ( RWXOwnerSnapshotNamespaceLabel = pluginName + "/rwx-snapshot-namespace" RWXOwnerSnapshotNameLabel = pluginName + "/rwx-snapshot-name" ) + +// Backup / restore (restic) constants. +const ( + // BackupConfigSingletonName is the only BackupConfig name the controller honors. + BackupConfigSingletonName = "default" + + // Annotation keys (on the source PVC) overriding BackupConfig defaults. + BackupEnabledAnnotation = pluginName + "/backup" + BackupScheduleAnnotation = pluginName + "/backup-schedule" + BackupKeepSnapshotAnnotation = pluginName + "/backup-keep-snapshot" + BackupRetentionLastAnnotation = pluginName + "/backup-retention-last" + BackupRetentionHourlyAnnotation = pluginName + "/backup-retention-hourly" + BackupRetentionDailyAnnotation = pluginName + "/backup-retention-daily" + BackupRetentionWeeklyAnnotation = pluginName + "/backup-retention-weekly" + BackupRetentionMonthlyAnnotation = pluginName + "/backup-retention-monthly" + BackupRetentionYearlyAnnotation = pluginName + "/backup-retention-yearly" + + // BackupManagedByLabel marks CronJobs/Jobs/Snapshots created by the backup controller. + BackupManagedByLabel = pluginName + "/backup-managed-by" + BackupManagedByValue = "topolvm-backup" + BackupOwnerPVCNamespaceLabel = pluginName + "/backup-pvc-namespace" + BackupOwnerPVCNameLabel = pluginName + "/backup-pvc-name" + + // BackupPVCFinalizer blocks deletion of a backed-up PVC until its CronJob is removed. + BackupPVCFinalizer = pluginName + "/backup" + + // Resource name suffixes. + BackupCronJobSuffix = "-backup" + BackupJobSnapshotInfix = "-backup-snap-" + BackupJobTempPVCInfix = "-backup-src-" + RestoreJobSuffix = "-restore" + + // Secret key names. + ResticPasswordSecretKey = "password" + S3AccessKeyIDSecretKey = "AWS_ACCESS_KEY_ID" + S3SecretKeySecretKey = "AWS_SECRET_ACCESS_KEY" + + // DefaultResticImage is the default image used for restic backup/restore Jobs. + DefaultResticImage = "restic/restic:0.17.3" +) diff --git a/docs/backup-restore.md b/docs/backup-restore.md new file mode 100644 index 000000000..e21f85b67 --- /dev/null +++ b/docs/backup-restore.md @@ -0,0 +1,176 @@ +# Backup and Restore (restic) + +TopoLVM ships an opt-in controller that backs up PVCs to an S3-compatible +object store using [restic](https://restic.net/) and restores them back into +fresh PVCs. The model is inspired by +[VolSync](https://volsync.readthedocs.io/): each backup run snapshots the +source PVC, provisions a read-only temp PVC from the snapshot, runs a restic +mover Job against it, and then tears the transient objects down. + +One restic repository is created **per source PVC** inside the configured +bucket, keyed by `/` (optionally with a cluster-wide +prefix for shared buckets). + +## Enabling the feature + +In your Helm values: + +```yaml +controller: + backup: + enabled: true + # resticImage: restic/restic:0.17.3 # override if needed + # moverServiceAccount: default # SA used by mover/restore Jobs +``` + +Then create the two Secrets in the controller's namespace +(`topolvm-system` by default) and apply a `BackupConfig`. + +## `BackupConfig` (cluster-scoped, singleton) + +Only the `BackupConfig` named `default` is honored; additional objects are +ignored. + +```yaml +apiVersion: topolvm.io/v1 +kind: BackupConfig +metadata: + name: default +spec: + s3: + endpoint: https://s3.example.com + bucket: topolvm-backups + region: us-east-1 # optional + # prefix: shared/tenant-a # optional, inserted between bucket and / + credentialsSecretRef: + name: s3-creds + namespace: topolvm-system # default: controller namespace + resticPasswordSecretRef: + name: restic-pw + namespace: topolvm-system + schedule: "0 2 * * *" # global default; empty disables backups + retention: + keepDaily: 7 + keepWeekly: 4 + keepMonthly: 12 + volumeSnapshotClassName: topolvm-provisioner-thin + keepSnapshotAfterBackup: false # delete the VolumeSnapshot after backup + selector: # optional; empty matches every TopoLVM PVC + matchLabels: + backup: "yes" + suspend: false +``` + +Required Secrets: + +```yaml +apiVersion: v1 +kind: Secret +metadata: + name: s3-creds + namespace: topolvm-system +stringData: + AWS_ACCESS_KEY_ID: ... + AWS_SECRET_ACCESS_KEY: ... +--- +apiVersion: v1 +kind: Secret +metadata: + name: restic-pw + namespace: topolvm-system +stringData: + password: +``` + +The BackupConfig controller mirrors these Secrets into every namespace that +contains a managed PVC. + +## Per-PVC overrides (annotations) + +Put these on the source `PersistentVolumeClaim`: + +| Annotation | Meaning | +| --- | --- | +| `topolvm.io/backup=false` | Skip this PVC entirely. | +| `topolvm.io/backup-schedule=` | Override global schedule. | +| `topolvm.io/backup-keep-snapshot=true` | Keep the VolumeSnapshot around after each run. | +| `topolvm.io/backup-retention-last=` | Override global `keepLast`. | +| `topolvm.io/backup-retention-hourly=` | Override `keepHourly`. | +| `topolvm.io/backup-retention-daily=` | Override `keepDaily`. | +| `topolvm.io/backup-retention-weekly=` | Override `keepWeekly`. | +| `topolvm.io/backup-retention-monthly=` | Override `keepMonthly`. | +| `topolvm.io/backup-retention-yearly=` | Override `keepYearly`. | + +## `PVCBackup` (namespaced, per PVC) + +The BackupConfig controller maintains one `PVCBackup` per matching PVC, +named after the PVC. Inspect: + +```bash +kubectl get pvcbackup -A +``` + +`.status.phase` walks through `Idle → Snapshotting → Cloning → Moving → +Cleanup → Synced|Failed`. A failed run sets `Failed` and waits for the next +fire time; it does not block future runs. + +To force an immediate run outside the schedule (e.g. before maintenance): + +```bash +kubectl patch pvcbackup -n app data --type=merge \ + -p '{"spec":{"trigger":"manual-'"$(date +%s)"'"}}' +``` + +Users may also author their own `PVCBackup` objects directly — the +BackupConfig controller never modifies objects it did not create (it keys +on the `topolvm.io/backup-managed-by` label). + +## `Restore` (namespaced) + +A `Restore` CR creates a fresh PVC in its own namespace and populates it +from a restic snapshot. + +```yaml +apiVersion: topolvm.io/v1 +kind: Restore +metadata: + name: data-restore + namespace: app +spec: + sourceNamespace: app # namespace of the original PVC + sourcePVCName: data # original PVC name (used as the repo key) + snapshotID: "" # empty = "latest" + targetPVCName: data-restored # new PVC created in this namespace + size: 10Gi + storageClassName: topolvm-provisioner-thin +``` + +The Restore target PVC is **not** owner-referenced by the Restore CR: +deleting the Restore does not delete the restored data. + +## Lifecycle details + +- **Snapshot mode** — VolumeSnapshots are used regardless of thin/thick + provisioning. Thick snapshots consume full size on the VG; factor that + into capacity planning. +- **Backup atomicity** — each run uses a dedicated VolumeSnapshot and temp + PVC (names include a `runID` suffix) so interrupted runs never collide + with the next schedule slot. +- **Cleanup guarantees** — the temp PVC is always deleted after the mover + Job completes. The VolumeSnapshot is also deleted unless + `keepSnapshotAfterBackup=true`. All three child objects carry owner + references to the `PVCBackup`, so deleting the `PVCBackup` cascades + cleanup via standard Kubernetes GC. +- **Restart safety** — phase transitions are recorded on the CR's status + subresource, so the controller can resume mid-run after a restart + without re-taking snapshots or re-running backups already in flight. + +## Operational tips + +- Give the mover Job a dedicated ServiceAccount per namespace if your + SecurityContext / PodSecurity policy needs a non-default SA. +- Monitor `PVCBackup.status.phase` + `.status.lastSyncTime` via + Prometheus/alerting for any PVC where `Failed` persists across multiple + fire times. +- `restic -r snapshots` against the bucket from any machine with + the restic password verifies the backup data is usable out-of-band. diff --git a/go.mod b/go.mod index 0db24f3d2..127712fb4 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/prometheus/client_model v0.6.1 github.com/prometheus/common v0.62.0 github.com/pseudomuto/protoc-gen-doc v1.5.1 + github.com/robfig/cron/v3 v3.0.1 github.com/spf13/cobra v1.10.1 github.com/spf13/pflag v1.0.10 github.com/spf13/viper v1.20.1 diff --git a/go.sum b/go.sum index ae313254a..a853fdfa6 100644 --- a/go.sum +++ b/go.sum @@ -162,6 +162,8 @@ github.com/pseudomuto/protoc-gen-doc v1.5.1 h1:Ah259kcrio7Ix1Rhb6u8FCaOkzf9qRBqX github.com/pseudomuto/protoc-gen-doc v1.5.1/go.mod h1:XpMKYg6zkcpgfpCfQ8GcWBDRtRxOmMR5w7pz4Xo+dYM= github.com/pseudomuto/protokit v0.2.0 h1:hlnBDcy3YEDXH7kc9gV+NLaN0cDzhDvD1s7Y6FZ8RpM= github.com/pseudomuto/protokit v0.2.0/go.mod h1:2PdH30hxVHsup8KpBTOXTBeMVhJZVio3Q8ViKSAXT0Q= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= diff --git a/internal/backup/manifests.go b/internal/backup/manifests.go new file mode 100644 index 000000000..c0a31f991 --- /dev/null +++ b/internal/backup/manifests.go @@ -0,0 +1,453 @@ +package backup + +import ( + "fmt" + "strings" + + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" +) + +// RuntimeConfig is the merged view the reconciler passes to each manifest +// helper: a PVCBackup's effective spec combined with cluster-wide +// BackupConfig settings and the resolved source PVC's storage class / size. +type RuntimeConfig struct { + // Source PVC identity. + PVCNamespace string + PVCName string + PVCSize resource.Quantity + + // Storage class of the source PVC, copied onto the temp PVC. + StorageClassName string + + // Parent PVCBackup (used for owner references and child naming). + PVCBackupName string + PVCBackupUID string + + // Effective snapshot/retention/keep settings for this run. + VolumeSnapshotClassName string + Retention topolvmv1.RetentionSpec + KeepSnapshotAfterBackup bool + + // S3 repo settings (from BackupConfig). + S3Endpoint string + S3Bucket string + S3Region string + S3InsecureTLS bool + S3Prefix string + + // Secret names (must exist in the PVC's namespace; the BackupConfig + // controller is responsible for propagating them there if needed). + S3CredentialsSecretName string + ResticPasswordSecretName string + + // Mover image and SA. + ResticImage string + ServiceAccountName string +} + +// SnapshotName, TempPVCName, and MoverJobName are deterministic per +// PVCBackup run. The runID is typically the first 8 chars of the +// VolumeSnapshot.UID (or a reconcile-generated timestamp when taking the +// snapshot for the first time). +func SnapshotName(pvcName, runID string) string { + return fmt.Sprintf("%s%s%s", pvcName, topolvm.BackupJobSnapshotInfix, runID) +} + +func TempPVCName(pvcName, runID string) string { + return fmt.Sprintf("%s%s%s", pvcName, topolvm.BackupJobTempPVCInfix, runID) +} + +func MoverJobName(pvcName, runID string) string { + return fmt.Sprintf("%s-backup-mover-%s", pvcName, runID) +} + +func RestoreJobName(restoreName string) string { + return restoreName + topolvm.RestoreJobSuffix +} + +// RepoURL returns the restic repository URL for a PVC. One repo per PVC: +// +// s3://[/]/ +// +// Prefix may be empty and is used mainly to partition shared buckets for CI. +func RepoURL(endpoint, bucket, prefix, pvcNamespace, pvcName string) string { + base := fmt.Sprintf("s3:%s/%s", strings.TrimSuffix(endpoint, "/"), bucket) + prefix = strings.Trim(prefix, "/") + if prefix != "" { + base = fmt.Sprintf("%s/%s", base, prefix) + } + return fmt.Sprintf("%s/%s/%s", base, pvcNamespace, pvcName) +} + +func commonLabels(cfg RuntimeConfig) map[string]string { + return map[string]string{ + topolvm.CreatedbyLabelKey: topolvm.CreatedbyLabelValue, + topolvm.BackupManagedByLabel: topolvm.BackupManagedByValue, + topolvm.BackupOwnerPVCNamespaceLabel: cfg.PVCNamespace, + topolvm.BackupOwnerPVCNameLabel: cfg.PVCName, + } +} + +func ownerRef(cfg RuntimeConfig) metav1.OwnerReference { + return metav1.OwnerReference{ + APIVersion: topolvmv1.GroupVersion.String(), + Kind: "PVCBackup", + Name: cfg.PVCBackupName, + UID: types.UID(cfg.PVCBackupUID), + Controller: ptr.To(true), + BlockOwnerDeletion: ptr.To(true), + } +} + +// Snapshot returns a VolumeSnapshot for the source PVC, owned by the PVCBackup. +func Snapshot(cfg RuntimeConfig, runID string) *snapshotv1.VolumeSnapshot { + var snapClass *string + if cfg.VolumeSnapshotClassName != "" { + c := cfg.VolumeSnapshotClassName + snapClass = &c + } + pvcName := cfg.PVCName + return &snapshotv1.VolumeSnapshot{ + ObjectMeta: metav1.ObjectMeta{ + Name: SnapshotName(cfg.PVCName, runID), + Namespace: cfg.PVCNamespace, + Labels: commonLabels(cfg), + OwnerReferences: []metav1.OwnerReference{ownerRef(cfg)}, + }, + Spec: snapshotv1.VolumeSnapshotSpec{ + VolumeSnapshotClassName: snapClass, + Source: snapshotv1.VolumeSnapshotSource{ + PersistentVolumeClaimName: &pvcName, + }, + }, + } +} + +// TempPVC returns the read-only PVC provisioned from the VolumeSnapshot, +// owned by the PVCBackup. +func TempPVC(cfg RuntimeConfig, runID string) *corev1.PersistentVolumeClaim { + apiGroup := "snapshot.storage.k8s.io" + return &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: TempPVCName(cfg.PVCName, runID), + Namespace: cfg.PVCNamespace, + Labels: commonLabels(cfg), + OwnerReferences: []metav1.OwnerReference{ownerRef(cfg)}, + }, + Spec: corev1.PersistentVolumeClaimSpec{ + StorageClassName: ptr.To(cfg.StorageClassName), + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.VolumeResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: cfg.PVCSize, + }, + }, + DataSource: &corev1.TypedLocalObjectReference{ + APIGroup: &apiGroup, + Kind: "VolumeSnapshot", + Name: SnapshotName(cfg.PVCName, runID), + }, + }, + } +} + +// MoverJob returns the restic mover Job. The Job Pod mounts the already-bound +// temp PVC read-only at /data and runs restic backup + restic forget. +func MoverJob(cfg RuntimeConfig, runID string) *batchv1.Job { + labels := commonLabels(cfg) + env := moverEnv(cfg) + + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{ + Name: MoverJobName(cfg.PVCName, runID), + Namespace: cfg.PVCNamespace, + Labels: labels, + OwnerReferences: []metav1.OwnerReference{ownerRef(cfg)}, + }, + Spec: batchv1.JobSpec{ + BackoffLimit: ptr.To[int32](0), + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{Labels: labels}, + Spec: corev1.PodSpec{ + RestartPolicy: corev1.RestartPolicyNever, + ServiceAccountName: cfg.ServiceAccountName, + Containers: []corev1.Container{ + { + Name: "restic", + Image: cfg.ResticImage, + Command: []string{"/bin/sh", "-c", backupScript}, + Env: env, + VolumeMounts: []corev1.VolumeMount{ + {Name: "data", MountPath: "/data", ReadOnly: true}, + }, + }, + }, + Volumes: []corev1.Volume{ + { + Name: "data", + VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ + ClaimName: TempPVCName(cfg.PVCName, runID), + ReadOnly: true, + }, + }, + }, + }, + }, + }, + }, + } +} + +func moverEnv(cfg RuntimeConfig) []corev1.EnvVar { + env := []corev1.EnvVar{ + { + Name: "RESTIC_PASSWORD", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.ResticPasswordSecretName}, + Key: topolvm.ResticPasswordSecretKey, + }, + }, + }, + { + Name: "AWS_ACCESS_KEY_ID", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.S3CredentialsSecretName}, + Key: topolvm.S3AccessKeyIDSecretKey, + }, + }, + }, + { + Name: "AWS_SECRET_ACCESS_KEY", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.S3CredentialsSecretName}, + Key: topolvm.S3SecretKeySecretKey, + }, + }, + }, + {Name: "RESTIC_REPOSITORY", Value: RepoURL(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3Prefix, cfg.PVCNamespace, cfg.PVCName)}, + {Name: "PVC_NAMESPACE", Value: cfg.PVCNamespace}, + {Name: "PVC_NAME", Value: cfg.PVCName}, + {Name: "KEEP_LAST", Value: intOrEmpty(cfg.Retention.KeepLast)}, + {Name: "KEEP_HOURLY", Value: intOrEmpty(cfg.Retention.KeepHourly)}, + {Name: "KEEP_DAILY", Value: intOrEmpty(cfg.Retention.KeepDaily)}, + {Name: "KEEP_WEEKLY", Value: intOrEmpty(cfg.Retention.KeepWeekly)}, + {Name: "KEEP_MONTHLY", Value: intOrEmpty(cfg.Retention.KeepMonthly)}, + {Name: "KEEP_YEARLY", Value: intOrEmpty(cfg.Retention.KeepYearly)}, + } + if cfg.S3Region != "" { + env = append(env, corev1.EnvVar{Name: "AWS_DEFAULT_REGION", Value: cfg.S3Region}) + } + return env +} + +func intOrEmpty(n int32) string { + if n <= 0 { + return "" + } + return fmt.Sprintf("%d", n) +} + +// backupScript runs inside the restic container. /data is the read-only +// temp PVC populated from the VolumeSnapshot. The mover never touches the +// snapshot or PVC lifecycle — the reconciler owns cleanup. +const backupScript = `#!/bin/sh +set -eu + +echo "[restic] repository: ${RESTIC_REPOSITORY}" + +if ! restic snapshots >/dev/null 2>&1; then + echo "[restic] initializing repository" + restic init +fi + +echo "[restic] backing up /data" +restic backup /data \ + --tag "pvc=${PVC_NAMESPACE}/${PVC_NAME}" \ + --host "${PVC_NAMESPACE}" + +FORGET_ARGS="" +[ -n "${KEEP_LAST:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-last ${KEEP_LAST}" +[ -n "${KEEP_HOURLY:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-hourly ${KEEP_HOURLY}" +[ -n "${KEEP_DAILY:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-daily ${KEEP_DAILY}" +[ -n "${KEEP_WEEKLY:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-weekly ${KEEP_WEEKLY}" +[ -n "${KEEP_MONTHLY:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-monthly ${KEEP_MONTHLY}" +[ -n "${KEEP_YEARLY:-}" ] && FORGET_ARGS="${FORGET_ARGS} --keep-yearly ${KEEP_YEARLY}" + +if [ -n "${FORGET_ARGS}" ]; then + echo "[restic] forget${FORGET_ARGS} --prune" + # shellcheck disable=SC2086 + restic forget ${FORGET_ARGS} --host "${PVC_NAMESPACE}" --tag "pvc=${PVC_NAMESPACE}/${PVC_NAME}" --prune +fi + +echo "[restic] done" +` + +// RestoreConfig carries everything the Restore reconciler passes to the +// restore Job builder. Mirrors RuntimeConfig but for restore-only fields. +type RestoreConfig struct { + // Restore CR identity (for naming + owner ref). + RestoreName string + RestoreNamespace string + RestoreUID string + + // Target PVC in the Restore's namespace. + TargetPVCName string + + // Source repo coordinates. + SourceNamespace string + SourcePVCName string + SnapshotID string + + // S3 settings (from BackupConfig). + S3Endpoint string + S3Bucket string + S3Region string + S3InsecureTLS bool + S3Prefix string + + S3CredentialsSecretName string + ResticPasswordSecretName string + + ResticImage string + ServiceAccountName string +} + +func restoreOwnerRef(cfg RestoreConfig) metav1.OwnerReference { + return metav1.OwnerReference{ + APIVersion: topolvmv1.GroupVersion.String(), + Kind: "Restore", + Name: cfg.RestoreName, + UID: types.UID(cfg.RestoreUID), + Controller: ptr.To(true), + BlockOwnerDeletion: ptr.To(true), + } +} + +// RestoreJob returns a one-shot Job that restores a restic snapshot into +// the target PVC. The Job is owned by the Restore CR so deletion of the +// Restore cascades to the Job (but not the target PVC — that is owned by +// the user / their namespace). +func RestoreJob(cfg RestoreConfig) *batchv1.Job { + labels := map[string]string{ + topolvm.CreatedbyLabelKey: topolvm.CreatedbyLabelValue, + topolvm.BackupManagedByLabel: topolvm.BackupManagedByValue, + } + snapID := cfg.SnapshotID + if snapID == "" { + snapID = "latest" + } + env := []corev1.EnvVar{ + { + Name: "RESTIC_PASSWORD", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.ResticPasswordSecretName}, + Key: topolvm.ResticPasswordSecretKey, + }, + }, + }, + { + Name: "AWS_ACCESS_KEY_ID", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.S3CredentialsSecretName}, + Key: topolvm.S3AccessKeyIDSecretKey, + }, + }, + }, + { + Name: "AWS_SECRET_ACCESS_KEY", + ValueFrom: &corev1.EnvVarSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + LocalObjectReference: corev1.LocalObjectReference{Name: cfg.S3CredentialsSecretName}, + Key: topolvm.S3SecretKeySecretKey, + }, + }, + }, + {Name: "RESTIC_REPOSITORY", Value: RepoURL(cfg.S3Endpoint, cfg.S3Bucket, cfg.S3Prefix, cfg.SourceNamespace, cfg.SourcePVCName)}, + {Name: "SOURCE_PVC_NAMESPACE", Value: cfg.SourceNamespace}, + {Name: "SOURCE_PVC_NAME", Value: cfg.SourcePVCName}, + {Name: "SNAPSHOT_ID", Value: snapID}, + } + if cfg.S3Region != "" { + env = append(env, corev1.EnvVar{Name: "AWS_DEFAULT_REGION", Value: cfg.S3Region}) + } + + return &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{ + Name: RestoreJobName(cfg.RestoreName), + Namespace: cfg.RestoreNamespace, + Labels: labels, + OwnerReferences: []metav1.OwnerReference{restoreOwnerRef(cfg)}, + }, + Spec: batchv1.JobSpec{ + BackoffLimit: ptr.To[int32](0), + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{Labels: labels}, + Spec: corev1.PodSpec{ + RestartPolicy: corev1.RestartPolicyNever, + ServiceAccountName: cfg.ServiceAccountName, + Containers: []corev1.Container{ + { + Name: "restic", + Image: cfg.ResticImage, + Command: []string{"/bin/sh", "-c", restoreScript}, + Env: env, + VolumeMounts: []corev1.VolumeMount{ + {Name: "data", MountPath: "/data"}, + }, + }, + }, + Volumes: []corev1.Volume{ + { + Name: "data", + VolumeSource: corev1.VolumeSource{ + PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{ + ClaimName: cfg.TargetPVCName, + }, + }, + }, + }, + }, + }, + }, + } +} + +const restoreScript = `#!/bin/sh +set -eu + +echo "[restic] repository: ${RESTIC_REPOSITORY}" +echo "[restic] restoring snapshot ${SNAPSHOT_ID} into /data" + +if [ -n "$(ls -A /data 2>/dev/null)" ]; then + echo "[restic] /data is not empty; refusing to restore" >&2 + exit 2 +fi + +restic restore "${SNAPSHOT_ID}" \ + --target /data \ + --tag "pvc=${SOURCE_PVC_NAMESPACE}/${SOURCE_PVC_NAME}" + +# restic restore --target /data places the original absolute path under /data +# (i.e. /data/data). Flatten so the PVC root mirrors the source. +if [ -d /data/data ]; then + mv /data/data/* /data/ 2>/dev/null || true + mv /data/data/.[!.]* /data/ 2>/dev/null || true + rmdir /data/data +fi + +echo "[restic] restore complete" +` diff --git a/internal/backup/manifests_test.go b/internal/backup/manifests_test.go new file mode 100644 index 000000000..bd9854373 --- /dev/null +++ b/internal/backup/manifests_test.go @@ -0,0 +1,296 @@ +package backup + +import ( + "strings" + "testing" + + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + "k8s.io/apimachinery/pkg/api/resource" +) + +func baseCfg() RuntimeConfig { + return RuntimeConfig{ + PVCNamespace: "app", + PVCName: "data", + PVCSize: resource.MustParse("10Gi"), + StorageClassName: "topolvm-provisioner", + PVCBackupName: "data", + PVCBackupUID: "pb-uid-1", + VolumeSnapshotClassName: "topolvm-provisioner", + KeepSnapshotAfterBackup: false, + S3Endpoint: "https://s3.example.com/", + S3Bucket: "backups", + S3Region: "us-east-1", + S3CredentialsSecretName: "s3-creds", + ResticPasswordSecretName: "restic-pw", + ResticImage: "restic/restic:0.17.3", + ServiceAccountName: "topolvm-backup-mover", + } +} + +func TestRepoURL_StripsTrailingSlash(t *testing.T) { + got := RepoURL("https://s3.example.com/", "backups", "", "app", "data") + want := "s3:https://s3.example.com/backups/app/data" + if got != want { + t.Fatalf("got %q, want %q", got, want) + } +} + +func TestRepoURL_PerPVCLayout(t *testing.T) { + // Two different PVCs must resolve to distinct prefixes. + a := RepoURL("https://s3", "bucket", "", "ns1", "pvc1") + b := RepoURL("https://s3", "bucket", "", "ns1", "pvc2") + c := RepoURL("https://s3", "bucket", "", "ns2", "pvc1") + if a == b || a == c || b == c { + t.Fatalf("expected distinct repo URLs, got a=%s b=%s c=%s", a, b, c) + } + if !strings.HasSuffix(a, "/ns1/pvc1") { + t.Fatalf("expected / suffix, got %s", a) + } +} + +func TestRepoURL_PrefixInsertedBetweenBucketAndNamespace(t *testing.T) { + got := RepoURL("https://s3", "bucket", "ci/42", "ns", "data") + want := "s3:https://s3/bucket/ci/42/ns/data" + if got != want { + t.Fatalf("got %q, want %q", got, want) + } + // Leading/trailing slashes on prefix must be stripped to avoid double-/ paths. + if got := RepoURL("https://s3", "bucket", "/ci/42/", "ns", "data"); got != want { + t.Fatalf("prefix with surrounding slashes produced %q, want %q", got, want) + } +} + +func TestNames_AreDeterministicAndDistinct(t *testing.T) { + const runID = "20260419120000" + snap := SnapshotName("data", runID) + tpvc := TempPVCName("data", runID) + job := MoverJobName("data", runID) + restore := RestoreJobName("my-restore") + + for _, n := range []string{snap, tpvc, job, restore} { + if n == "" { + t.Fatalf("empty name") + } + } + if snap == tpvc || snap == job || tpvc == job { + t.Fatalf("expected distinct names, got snap=%s tpvc=%s job=%s", snap, tpvc, job) + } + if !strings.HasSuffix(snap, runID) || !strings.HasSuffix(tpvc, runID) || !strings.HasSuffix(job, runID) { + t.Fatalf("names must carry the runID suffix for deterministic regeneration") + } + if !strings.HasSuffix(restore, topolvm.RestoreJobSuffix) { + t.Fatalf("restore job name missing expected suffix: %s", restore) + } +} + +func TestSnapshot_HasOwnerRefAndLabels(t *testing.T) { + cfg := baseCfg() + snap := Snapshot(cfg, "run1") + + if got := len(snap.OwnerReferences); got != 1 { + t.Fatalf("expected 1 owner ref, got %d", got) + } + or := snap.OwnerReferences[0] + if or.Kind != "PVCBackup" || or.Name != "data" || string(or.UID) != "pb-uid-1" { + t.Fatalf("owner ref mismatch: %+v", or) + } + if or.Controller == nil || !*or.Controller { + t.Fatalf("owner ref must be Controller=true") + } + if snap.Spec.Source.PersistentVolumeClaimName == nil || *snap.Spec.Source.PersistentVolumeClaimName != "data" { + t.Fatalf("snapshot source PVC name wrong") + } + if snap.Spec.VolumeSnapshotClassName == nil || *snap.Spec.VolumeSnapshotClassName != "topolvm-provisioner" { + t.Fatalf("snapshot class not propagated") + } + if snap.Labels[topolvm.BackupManagedByLabel] != topolvm.BackupManagedByValue { + t.Fatalf("missing managed-by label") + } +} + +func TestSnapshot_EmptyClassIsNil(t *testing.T) { + cfg := baseCfg() + cfg.VolumeSnapshotClassName = "" + snap := Snapshot(cfg, "run1") + if snap.Spec.VolumeSnapshotClassName != nil { + t.Fatalf("expected nil snapshot class when empty, got %q", *snap.Spec.VolumeSnapshotClassName) + } +} + +func TestTempPVC_UsesSnapshotDataSource(t *testing.T) { + cfg := baseCfg() + pvc := TempPVC(cfg, "run1") + + if pvc.Spec.DataSource == nil { + t.Fatal("temp PVC missing dataSource") + } + if pvc.Spec.DataSource.Kind != "VolumeSnapshot" { + t.Fatalf("expected VolumeSnapshot dataSource, got %s", pvc.Spec.DataSource.Kind) + } + if pvc.Spec.DataSource.Name != SnapshotName(cfg.PVCName, "run1") { + t.Fatalf("dataSource name must match Snapshot() output") + } + if pvc.Spec.StorageClassName == nil || *pvc.Spec.StorageClassName != cfg.StorageClassName { + t.Fatalf("temp PVC did not inherit source storage class") + } + if pvc.Spec.Resources.Requests["storage"] != cfg.PVCSize { + t.Fatalf("temp PVC size mismatch") + } +} + +func TestMoverJob_MountsTempPVCReadOnly(t *testing.T) { + cfg := baseCfg() + job := MoverJob(cfg, "run1") + + if got := len(job.Spec.Template.Spec.Volumes); got != 1 { + t.Fatalf("expected 1 volume, got %d", got) + } + vol := job.Spec.Template.Spec.Volumes[0] + if vol.PersistentVolumeClaim == nil { + t.Fatal("volume must be a PVC source") + } + if vol.PersistentVolumeClaim.ClaimName != TempPVCName(cfg.PVCName, "run1") { + t.Fatalf("mover must mount the temp PVC from the same runID") + } + if !vol.PersistentVolumeClaim.ReadOnly { + t.Fatal("mover must mount the temp PVC read-only to avoid mutating a snapshot copy") + } + mounts := job.Spec.Template.Spec.Containers[0].VolumeMounts + if len(mounts) != 1 || mounts[0].MountPath != "/data" || !mounts[0].ReadOnly { + t.Fatalf("unexpected volumeMounts: %+v", mounts) + } +} + +func TestMoverJob_BackoffLimitZero(t *testing.T) { + // The reconciler drives retries itself — the Job must not retry in-pod. + job := MoverJob(baseCfg(), "run1") + if job.Spec.BackoffLimit == nil || *job.Spec.BackoffLimit != 0 { + t.Fatalf("expected BackoffLimit=0, got %+v", job.Spec.BackoffLimit) + } +} + +func TestMoverEnv_SecretKeysMatchConstants(t *testing.T) { + env := moverEnv(baseCfg()) + + want := map[string]string{ + "RESTIC_PASSWORD": topolvm.ResticPasswordSecretKey, + "AWS_ACCESS_KEY_ID": topolvm.S3AccessKeyIDSecretKey, + "AWS_SECRET_ACCESS_KEY": topolvm.S3SecretKeySecretKey, + } + seen := map[string]string{} + for _, e := range env { + if e.ValueFrom != nil && e.ValueFrom.SecretKeyRef != nil { + seen[e.Name] = e.ValueFrom.SecretKeyRef.Key + } + } + for envName, expectedKey := range want { + if got, ok := seen[envName]; !ok { + t.Errorf("env %s missing SecretKeyRef", envName) + } else if got != expectedKey { + t.Errorf("env %s keyRef=%s, want %s", envName, got, expectedKey) + } + } +} + +func TestMoverEnv_RetentionFlagsPropagated(t *testing.T) { + cfg := baseCfg() + cfg.Retention = topolvmv1.RetentionSpec{ + KeepLast: 3, + KeepDaily: 7, + KeepMonthly: 0, + } + env := moverEnv(cfg) + + values := map[string]string{} + for _, e := range env { + values[e.Name] = e.Value + } + if values["KEEP_LAST"] != "3" { + t.Errorf("KEEP_LAST=%q, want 3", values["KEEP_LAST"]) + } + if values["KEEP_DAILY"] != "7" { + t.Errorf("KEEP_DAILY=%q, want 7", values["KEEP_DAILY"]) + } + if values["KEEP_MONTHLY"] != "" { + t.Errorf("KEEP_MONTHLY=%q, want empty (0 retention -> unset)", values["KEEP_MONTHLY"]) + } +} + +func TestMoverEnv_RegionOnlyWhenSet(t *testing.T) { + cfg := baseCfg() + cfg.S3Region = "" + for _, e := range moverEnv(cfg) { + if e.Name == "AWS_DEFAULT_REGION" { + t.Fatal("AWS_DEFAULT_REGION should not be set when S3Region is empty") + } + } + cfg.S3Region = "eu-west-1" + found := false + for _, e := range moverEnv(cfg) { + if e.Name == "AWS_DEFAULT_REGION" && e.Value == "eu-west-1" { + found = true + } + } + if !found { + t.Fatal("AWS_DEFAULT_REGION not set despite S3Region=eu-west-1") + } +} + +func TestRestoreJob_OwnedByRestoreNotTargetPVC(t *testing.T) { + cfg := RestoreConfig{ + RestoreName: "rs1", + RestoreNamespace: "app", + RestoreUID: "rs-uid", + TargetPVCName: "restored", + SourceNamespace: "app", + SourcePVCName: "data", + S3Endpoint: "https://s3", + S3Bucket: "b", + S3CredentialsSecretName: "s3-creds", + ResticPasswordSecretName: "restic-pw", + ResticImage: "restic/restic:0.17.3", + ServiceAccountName: "default", + } + job := RestoreJob(cfg) + + if len(job.OwnerReferences) != 1 || job.OwnerReferences[0].Kind != "Restore" { + t.Fatalf("restore Job must be owned by the Restore CR, got %+v", job.OwnerReferences) + } + // Target PVC is mounted but NOT owned by the Job — restored data must + // survive deletion of the Restore CR (and therefore the Job). + for _, v := range job.Spec.Template.Spec.Volumes { + if v.PersistentVolumeClaim != nil && v.PersistentVolumeClaim.ClaimName != cfg.TargetPVCName { + t.Fatalf("restore Job must mount target PVC, got %s", v.PersistentVolumeClaim.ClaimName) + } + } +} + +func TestRestoreJob_DefaultSnapshotIDIsLatest(t *testing.T) { + cfg := RestoreConfig{ + RestoreName: "rs1", + RestoreNamespace: "app", + RestoreUID: "rs-uid", + TargetPVCName: "restored", + SourceNamespace: "app", + SourcePVCName: "data", + S3Endpoint: "https://s3", + S3Bucket: "b", + S3CredentialsSecretName: "s3-creds", + ResticPasswordSecretName: "restic-pw", + ResticImage: "restic/restic:0.17.3", + ServiceAccountName: "default", + // SnapshotID left empty — should resolve to "latest". + } + job := RestoreJob(cfg) + var snapEnv string + for _, e := range job.Spec.Template.Spec.Containers[0].Env { + if e.Name == "SNAPSHOT_ID" { + snapEnv = e.Value + } + } + if snapEnv != "latest" { + t.Fatalf("default SnapshotID should be latest, got %q", snapEnv) + } +} diff --git a/internal/controller/backupconfig_controller.go b/internal/controller/backupconfig_controller.go new file mode 100644 index 000000000..1b28d2110 --- /dev/null +++ b/internal/controller/backupconfig_controller.go @@ -0,0 +1,422 @@ +package controller + +import ( + "context" + "fmt" + "strconv" + + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + "github.com/topolvm/topolvm/internal/backup" + corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/handler" + crlog "sigs.k8s.io/controller-runtime/pkg/log" + "sigs.k8s.io/controller-runtime/pkg/reconcile" +) + +// BackupConfigReconciler owns the cluster-scoped BackupConfig singleton. It +// watches PVCs and the singleton, and reconciles one PVCBackup per matching +// PVC. It also propagates the S3-credentials and restic-password Secrets +// from the controller namespace into each namespace that has a managed PVC. +// +// User-authored PVCBackups (those without the managed-by label) are never +// touched — this controller only acts on resources it owns. +type BackupConfigReconciler struct { + client client.Client + apiReader client.Reader + + // ControllerNamespace is where the user-authored S3 credentials and + // restic password Secrets live. Managed namespaces receive mirror copies. + ControllerNamespace string + + // ResticImage is the default image used for mover and restore Jobs. + ResticImage string + + // ServiceAccountName is the ServiceAccount under which mover and + // restore Jobs run in the target namespace. Must exist (or be created + // by the chart) in every namespace a PVCBackup fires in. + ServiceAccountName string +} + +func NewBackupConfigReconciler( + c client.Client, + apiReader client.Reader, + controllerNamespace, resticImage, serviceAccountName string, +) *BackupConfigReconciler { + return &BackupConfigReconciler{ + client: c, + apiReader: apiReader, + ControllerNamespace: controllerNamespace, + ResticImage: resticImage, + ServiceAccountName: serviceAccountName, + } +} + +//+kubebuilder:rbac:groups=topolvm.io,resources=backupconfigs,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=topolvm.io,resources=backupconfigs/status,verbs=get;update;patch +//+kubebuilder:rbac:groups=core,resources=secrets,verbs=get;list;watch;create;update;patch;delete + +func (r *BackupConfigReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := crlog.FromContext(ctx).WithValues("pvc", req.NamespacedName) + + bc, ok, err := r.loadSingleton(ctx) + if err != nil { + return ctrl.Result{}, err + } + if !ok { + log.V(1).Info("no BackupConfig singleton; skipping") + return ctrl.Result{}, nil + } + + pvc := &corev1.PersistentVolumeClaim{} + err = r.client.Get(ctx, req.NamespacedName, pvc) + if apierrors.IsNotFound(err) { + // PVC deleted — remove any managed PVCBackup with this name. + return r.deleteManagedPVCBackup(ctx, req.Namespace, req.Name) + } + if err != nil { + return ctrl.Result{}, err + } + + matches, err := r.pvcMatches(ctx, bc, pvc) + if err != nil { + return ctrl.Result{}, err + } + if !matches { + return r.deleteManagedPVCBackup(ctx, pvc.Namespace, pvc.Name) + } + + if err := r.ensurePropagatedSecrets(ctx, bc, pvc.Namespace); err != nil { + return ctrl.Result{}, fmt.Errorf("propagate secrets: %w", err) + } + + return r.ensureManagedPVCBackup(ctx, bc, pvc) +} + +// LoadSingleton returns the one BackupConfig named "default". Other +// BackupConfigs are ignored. Exported so sibling controllers (Restore) +// can share the lookup without duplicating the singleton rule. +func (r *BackupConfigReconciler) LoadSingleton(ctx context.Context) (*topolvmv1.BackupConfig, bool, error) { + return r.loadSingleton(ctx) +} + +func (r *BackupConfigReconciler) loadSingleton(ctx context.Context) (*topolvmv1.BackupConfig, bool, error) { + bc := &topolvmv1.BackupConfig{} + err := r.client.Get(ctx, client.ObjectKey{Name: topolvm.BackupConfigSingletonName}, bc) + if apierrors.IsNotFound(err) { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + return bc, true, nil +} + +// pvcMatches returns true if the PVC should be backed up under the given +// BackupConfig. The rules, in order: +// +// 1. If the PVC carries topolvm.io/backup=false, skip. +// 2. If the PVC's StorageClass provisioner is not topolvm.io (or the legacy +// name), skip — only TopoLVM-backed PVCs are supported. +// 3. If BackupConfig.spec.selector is set and does not match the PVC's +// labels, skip. +// 4. Otherwise match. +func (r *BackupConfigReconciler) pvcMatches(ctx context.Context, bc *topolvmv1.BackupConfig, pvc *corev1.PersistentVolumeClaim) (bool, error) { + if v, ok := pvc.Annotations[topolvm.BackupEnabledAnnotation]; ok && v == "false" { + return false, nil + } + if pvc.Spec.StorageClassName == nil || *pvc.Spec.StorageClassName == "" { + return false, nil + } + sc := &storagev1.StorageClass{} + if err := r.client.Get(ctx, client.ObjectKey{Name: *pvc.Spec.StorageClassName}, sc); err != nil { + if apierrors.IsNotFound(err) { + return false, nil + } + return false, err + } + if sc.Provisioner != topolvm.GetPluginName() { + return false, nil + } + if bc.Spec.Selector != nil { + sel, err := metav1.LabelSelectorAsSelector(bc.Spec.Selector) + if err != nil { + return false, err + } + if !sel.Matches(labels.Set(pvc.Labels)) { + return false, nil + } + } + return true, nil +} + +// ensureManagedPVCBackup creates or updates the managed PVCBackup for a PVC. +func (r *BackupConfigReconciler) ensureManagedPVCBackup(ctx context.Context, bc *topolvmv1.BackupConfig, pvc *corev1.PersistentVolumeClaim) (ctrl.Result, error) { + want := r.buildPVCBackup(bc, pvc) + + got := &topolvmv1.PVCBackup{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: want.Namespace, Name: want.Name}, got) + if apierrors.IsNotFound(err) { + if err := r.client.Create(ctx, want); err != nil { + return ctrl.Result{}, fmt.Errorf("create PVCBackup: %w", err) + } + return ctrl.Result{}, nil + } + if err != nil { + return ctrl.Result{}, err + } + + // Only reconcile PVCBackups we own. User-authored ones are left alone. + if got.Labels[topolvm.BackupManagedByLabel] != topolvm.BackupManagedByValue { + return ctrl.Result{}, nil + } + if pvcBackupSpecEqual(got.Spec, want.Spec) { + return ctrl.Result{}, nil + } + patched := got.DeepCopy() + patched.Spec = want.Spec + if err := r.client.Update(ctx, patched); err != nil { + return ctrl.Result{}, fmt.Errorf("update PVCBackup: %w", err) + } + return ctrl.Result{}, nil +} + +func (r *BackupConfigReconciler) deleteManagedPVCBackup(ctx context.Context, namespace, pvcName string) (ctrl.Result, error) { + got := &topolvmv1.PVCBackup{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: namespace, Name: pvcName}, got) + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + if err != nil { + return ctrl.Result{}, err + } + if got.Labels[topolvm.BackupManagedByLabel] != topolvm.BackupManagedByValue { + // User-authored — never touch it. + return ctrl.Result{}, nil + } + if err := r.client.Delete(ctx, got); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, err + } + return ctrl.Result{}, nil +} + +// buildPVCBackup computes the desired PVCBackup for a PVC, merging +// BackupConfig defaults with per-PVC annotation overrides. +func (r *BackupConfigReconciler) buildPVCBackup(bc *topolvmv1.BackupConfig, pvc *corev1.PersistentVolumeClaim) *topolvmv1.PVCBackup { + schedule := bc.Spec.Schedule + if v, ok := pvc.Annotations[topolvm.BackupScheduleAnnotation]; ok && v != "" { + schedule = v + } + keepSnap := bc.Spec.KeepSnapshotAfterBackup + if v, ok := pvc.Annotations[topolvm.BackupKeepSnapshotAnnotation]; ok { + if b, err := strconv.ParseBool(v); err == nil { + keepSnap = b + } + } + retention := bc.Spec.Retention + retention.KeepLast = overrideRetention(retention.KeepLast, pvc.Annotations[topolvm.BackupRetentionLastAnnotation]) + retention.KeepHourly = overrideRetention(retention.KeepHourly, pvc.Annotations[topolvm.BackupRetentionHourlyAnnotation]) + retention.KeepDaily = overrideRetention(retention.KeepDaily, pvc.Annotations[topolvm.BackupRetentionDailyAnnotation]) + retention.KeepWeekly = overrideRetention(retention.KeepWeekly, pvc.Annotations[topolvm.BackupRetentionWeeklyAnnotation]) + retention.KeepMonthly = overrideRetention(retention.KeepMonthly, pvc.Annotations[topolvm.BackupRetentionMonthlyAnnotation]) + retention.KeepYearly = overrideRetention(retention.KeepYearly, pvc.Annotations[topolvm.BackupRetentionYearlyAnnotation]) + + return &topolvmv1.PVCBackup{ + ObjectMeta: metav1.ObjectMeta{ + Name: pvc.Name, + Namespace: pvc.Namespace, + Labels: map[string]string{ + topolvm.CreatedbyLabelKey: topolvm.CreatedbyLabelValue, + topolvm.BackupManagedByLabel: topolvm.BackupManagedByValue, + topolvm.BackupOwnerPVCNamespaceLabel: pvc.Namespace, + topolvm.BackupOwnerPVCNameLabel: pvc.Name, + }, + }, + Spec: topolvmv1.PVCBackupSpec{ + PVCName: pvc.Name, + Schedule: schedule, + Retention: retention, + KeepSnapshotAfterBackup: keepSnap, + VolumeSnapshotClassName: bc.Spec.VolumeSnapshotClassName, + Suspend: bc.Spec.Suspend, + }, + } +} + +// overrideRetention returns an annotation-parsed int32, falling back to the +// default when the annotation is empty or malformed. +func overrideRetention(def int32, raw string) int32 { + if raw == "" { + return def + } + n, err := strconv.Atoi(raw) + if err != nil || n < 0 { + return def + } + return int32(n) +} + +func pvcBackupSpecEqual(a, b topolvmv1.PVCBackupSpec) bool { + return a.PVCName == b.PVCName && + a.Schedule == b.Schedule && + a.Retention == b.Retention && + a.KeepSnapshotAfterBackup == b.KeepSnapshotAfterBackup && + a.VolumeSnapshotClassName == b.VolumeSnapshotClassName && + a.Suspend == b.Suspend && + a.Trigger == b.Trigger +} + +// ensurePropagatedSecrets copies the two user-authored Secrets (S3 creds, +// restic password) from the controller namespace into the target namespace, +// keeping them in sync on each reconcile. We do not delete stale mirrors — +// the first cut relies on users cleaning up namespaces they no longer back +// up. (Can be tightened later with a sweep that removes mirrors with no +// matching PVCBackup.) +func (r *BackupConfigReconciler) ensurePropagatedSecrets(ctx context.Context, bc *topolvmv1.BackupConfig, targetNS string) error { + if targetNS == r.ControllerNamespace { + return nil // No need to mirror into the controller's own namespace. + } + if err := r.mirrorSecret(ctx, bc.Spec.S3.CredentialsSecretRef.Name, r.controllerNS(bc.Spec.S3.CredentialsSecretRef.Namespace), targetNS); err != nil { + return fmt.Errorf("mirror s3 creds secret: %w", err) + } + if err := r.mirrorSecret(ctx, bc.Spec.ResticPasswordSecretRef.Name, r.controllerNS(bc.Spec.ResticPasswordSecretRef.Namespace), targetNS); err != nil { + return fmt.Errorf("mirror restic password secret: %w", err) + } + return nil +} + +// controllerNS returns the namespace to read a user Secret from: honor the +// explicit SecretReference.Namespace if set, else fall back to the +// controller's own namespace. +func (r *BackupConfigReconciler) controllerNS(declared string) string { + if declared != "" { + return declared + } + return r.ControllerNamespace +} + +func (r *BackupConfigReconciler) mirrorSecret(ctx context.Context, name, sourceNS, targetNS string) error { + src := &corev1.Secret{} + if err := r.client.Get(ctx, client.ObjectKey{Namespace: sourceNS, Name: name}, src); err != nil { + return err + } + want := &corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + Namespace: targetNS, + Labels: map[string]string{ + topolvm.CreatedbyLabelKey: topolvm.CreatedbyLabelValue, + topolvm.BackupManagedByLabel: topolvm.BackupManagedByValue, + }, + }, + Type: src.Type, + Data: src.Data, + } + got := &corev1.Secret{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: targetNS, Name: name}, got) + if apierrors.IsNotFound(err) { + return r.client.Create(ctx, want) + } + if err != nil { + return err + } + if got.Labels[topolvm.BackupManagedByLabel] != topolvm.BackupManagedByValue { + // A user-authored Secret with the same name exists in the target + // namespace; don't clobber it. + return nil + } + if secretDataEqual(got.Data, want.Data) && got.Type == want.Type { + return nil + } + patched := got.DeepCopy() + patched.Data = want.Data + patched.Type = want.Type + return r.client.Update(ctx, patched) +} + +func secretDataEqual(a, b map[string][]byte) bool { + if len(a) != len(b) { + return false + } + for k, v := range a { + bv, ok := b[k] + if !ok || string(v) != string(bv) { + return false + } + } + return true +} + +// ResolveRuntimeConfig is the callback the PVCBackup reconciler invokes to +// merge cluster-wide BackupConfig settings with the per-PVCBackup spec and +// the resolved PVC's size/storage class. +func (r *BackupConfigReconciler) ResolveRuntimeConfig(ctx context.Context, pb *topolvmv1.PVCBackup, pvc *corev1.PersistentVolumeClaim) (backup.RuntimeConfig, bool, error) { + bc, ok, err := r.loadSingleton(ctx) + if err != nil || !ok { + return backup.RuntimeConfig{}, ok, err + } + size, hasSize := pvc.Spec.Resources.Requests[corev1.ResourceStorage] + if !hasSize { + return backup.RuntimeConfig{}, false, fmt.Errorf("PVC %s/%s has no storage request", pvc.Namespace, pvc.Name) + } + sc := "" + if pvc.Spec.StorageClassName != nil { + sc = *pvc.Spec.StorageClassName + } + snapClass := pb.Spec.VolumeSnapshotClassName + if snapClass == "" { + snapClass = bc.Spec.VolumeSnapshotClassName + } + return backup.RuntimeConfig{ + PVCNamespace: pvc.Namespace, + PVCName: pvc.Name, + PVCSize: size, + StorageClassName: sc, + PVCBackupName: pb.Name, + PVCBackupUID: string(pb.UID), + VolumeSnapshotClassName: snapClass, + Retention: pb.Spec.Retention, + KeepSnapshotAfterBackup: pb.Spec.KeepSnapshotAfterBackup, + S3Endpoint: bc.Spec.S3.Endpoint, + S3Bucket: bc.Spec.S3.Bucket, + S3Region: bc.Spec.S3.Region, + S3InsecureTLS: bc.Spec.S3.InsecureTLS, + S3Prefix: bc.Spec.S3.Prefix, + S3CredentialsSecretName: bc.Spec.S3.CredentialsSecretRef.Name, + ResticPasswordSecretName: bc.Spec.ResticPasswordSecretRef.Name, + ResticImage: r.ResticImage, + ServiceAccountName: r.ServiceAccountName, + }, true, nil +} + +func (r *BackupConfigReconciler) SetupWithManager(mgr ctrl.Manager) error { + // Trigger reconcile of *every* PVC when the BackupConfig singleton changes. + pvcEnqueueForBackupConfig := handler.EnqueueRequestsFromMapFunc(func(ctx context.Context, _ client.Object) []reconcile.Request { + pvcs := &corev1.PersistentVolumeClaimList{} + if err := r.client.List(ctx, pvcs); err != nil { + return nil + } + reqs := make([]reconcile.Request, 0, len(pvcs.Items)) + for _, p := range pvcs.Items { + reqs = append(reqs, reconcile.Request{NamespacedName: client.ObjectKey{Namespace: p.Namespace, Name: p.Name}}) + } + return reqs + }) + + return ctrl.NewControllerManagedBy(mgr). + Named("backupconfig"). + For(&corev1.PersistentVolumeClaim{}). + Watches(&topolvmv1.BackupConfig{}, pvcEnqueueForBackupConfig). + Complete(r) +} + +// Compile-time assertion that the scheme includes topolvmv1 (so this file +// fails early if wiring drifts). +var _ runtime.Object = &topolvmv1.BackupConfig{} diff --git a/internal/controller/backupconfig_controller_test.go b/internal/controller/backupconfig_controller_test.go new file mode 100644 index 000000000..cc07b0630 --- /dev/null +++ b/internal/controller/backupconfig_controller_test.go @@ -0,0 +1,210 @@ +package controller + +import ( + "context" + "testing" + + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + corev1 "k8s.io/api/core/v1" + storagev1 "k8s.io/api/storage/v1" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +func testScheme(t *testing.T) *runtime.Scheme { + t.Helper() + s := runtime.NewScheme() + if err := clientgoscheme.AddToScheme(s); err != nil { + t.Fatal(err) + } + if err := topolvmv1.AddToScheme(s); err != nil { + t.Fatal(err) + } + return s +} + +func TestBuildPVCBackup_UsesGlobalDefaults(t *testing.T) { + r := &BackupConfigReconciler{} + bc := &topolvmv1.BackupConfig{ + Spec: topolvmv1.BackupConfigSpec{ + Schedule: "0 2 * * *", + Retention: topolvmv1.RetentionSpec{ + KeepDaily: 7, + KeepWeekly: 4, + }, + KeepSnapshotAfterBackup: false, + VolumeSnapshotClassName: "topolvm-provisioner", + }, + } + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Namespace: "app", Name: "data"}, + } + pb := r.buildPVCBackup(bc, pvc) + + if pb.Spec.Schedule != "0 2 * * *" { + t.Errorf("schedule not inherited: %q", pb.Spec.Schedule) + } + if pb.Spec.Retention.KeepDaily != 7 || pb.Spec.Retention.KeepWeekly != 4 { + t.Errorf("retention not inherited: %+v", pb.Spec.Retention) + } + if pb.Spec.VolumeSnapshotClassName != "topolvm-provisioner" { + t.Errorf("snapshot class not inherited: %q", pb.Spec.VolumeSnapshotClassName) + } + if pb.Labels[topolvm.BackupManagedByLabel] != topolvm.BackupManagedByValue { + t.Errorf("missing managed-by label") + } + if pb.Spec.PVCName != "data" { + t.Errorf("pvcName wrong: %q", pb.Spec.PVCName) + } +} + +func TestBuildPVCBackup_AnnotationsOverrideDefaults(t *testing.T) { + r := &BackupConfigReconciler{} + bc := &topolvmv1.BackupConfig{ + Spec: topolvmv1.BackupConfigSpec{ + Schedule: "0 2 * * *", + Retention: topolvmv1.RetentionSpec{KeepDaily: 7}, + KeepSnapshotAfterBackup: false, + }, + } + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: "app", + Name: "critical", + Annotations: map[string]string{ + topolvm.BackupScheduleAnnotation: "*/15 * * * *", + topolvm.BackupRetentionDailyAnnotation: "30", + topolvm.BackupRetentionMonthlyAnnotation: "12", + topolvm.BackupKeepSnapshotAnnotation: "true", + }, + }, + } + pb := r.buildPVCBackup(bc, pvc) + + if pb.Spec.Schedule != "*/15 * * * *" { + t.Errorf("schedule not overridden: %q", pb.Spec.Schedule) + } + if pb.Spec.Retention.KeepDaily != 30 { + t.Errorf("KeepDaily not overridden: %d", pb.Spec.Retention.KeepDaily) + } + if pb.Spec.Retention.KeepMonthly != 12 { + t.Errorf("KeepMonthly not applied: %d", pb.Spec.Retention.KeepMonthly) + } + if !pb.Spec.KeepSnapshotAfterBackup { + t.Errorf("KeepSnapshotAfterBackup not flipped by annotation") + } +} + +func TestBuildPVCBackup_MalformedAnnotationFallsBack(t *testing.T) { + r := &BackupConfigReconciler{} + bc := &topolvmv1.BackupConfig{ + Spec: topolvmv1.BackupConfigSpec{ + Retention: topolvmv1.RetentionSpec{KeepDaily: 7}, + }, + } + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Annotations: map[string]string{ + topolvm.BackupRetentionDailyAnnotation: "not-a-number", + }, + }, + } + pb := r.buildPVCBackup(bc, pvc) + if pb.Spec.Retention.KeepDaily != 7 { + t.Errorf("malformed annotation should fall back to default, got %d", pb.Spec.Retention.KeepDaily) + } +} + +func TestPVCMatches_SkipAnnotation(t *testing.T) { + r := &BackupConfigReconciler{client: fake.NewClientBuilder().WithScheme(testScheme(t)).Build()} + bc := &topolvmv1.BackupConfig{} + pvc := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Annotations: map[string]string{topolvm.BackupEnabledAnnotation: "false"}, + }, + } + ok, err := r.pvcMatches(context.Background(), bc, pvc) + if err != nil { + t.Fatal(err) + } + if ok { + t.Fatal("annotation=false should skip") + } +} + +func TestPVCMatches_SkipsNonTopoLVMStorageClass(t *testing.T) { + sc := &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{Name: "ebs"}, + Provisioner: "ebs.csi.aws.com", + } + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(sc).Build() + r := &BackupConfigReconciler{client: c} + bc := &topolvmv1.BackupConfig{} + ebs := "ebs" + pvc := &corev1.PersistentVolumeClaim{ + Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: &ebs}, + } + ok, err := r.pvcMatches(context.Background(), bc, pvc) + if err != nil { + t.Fatal(err) + } + if ok { + t.Fatal("non-topolvm provisioner should not match") + } +} + +func TestPVCMatches_SelectorRespected(t *testing.T) { + sc := &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{Name: "topolvm"}, + Provisioner: topolvm.GetPluginName(), + } + c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(sc).Build() + r := &BackupConfigReconciler{client: c} + bc := &topolvmv1.BackupConfig{ + Spec: topolvmv1.BackupConfigSpec{ + Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"backup": "yes"}}, + }, + } + scName := "topolvm" + unlabeled := &corev1.PersistentVolumeClaim{ + Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: &scName}, + } + labeled := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"backup": "yes"}}, + Spec: corev1.PersistentVolumeClaimSpec{StorageClassName: &scName}, + } + if ok, err := r.pvcMatches(context.Background(), bc, unlabeled); err != nil || ok { + t.Errorf("unlabeled should not match; ok=%v err=%v", ok, err) + } + if ok, err := r.pvcMatches(context.Background(), bc, labeled); err != nil || !ok { + t.Errorf("labeled PVC should match; ok=%v err=%v", ok, err) + } +} + +func TestPVCBackupSpecEqual(t *testing.T) { + a := topolvmv1.PVCBackupSpec{ + PVCName: "data", + Schedule: "0 * * * *", + Retention: topolvmv1.RetentionSpec{KeepDaily: 7}, + } + b := a + if !pvcBackupSpecEqual(a, b) { + t.Fatal("identical specs should be equal") + } + b.Schedule = "* * * * *" + if pvcBackupSpecEqual(a, b) { + t.Fatal("different schedule should differ") + } + b = a + b.Retention.KeepDaily = 8 + if pvcBackupSpecEqual(a, b) { + t.Fatal("different retention should differ") + } +} + +// unused reference to silence the linter if resource.Quantity gets dropped later. +var _ = resource.MustParse diff --git a/internal/controller/pvcbackup_controller.go b/internal/controller/pvcbackup_controller.go new file mode 100644 index 000000000..869f34f7f --- /dev/null +++ b/internal/controller/pvcbackup_controller.go @@ -0,0 +1,445 @@ +package controller + +import ( + "context" + "fmt" + "time" + + snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" + "github.com/robfig/cron/v3" + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + "github.com/topolvm/topolvm/internal/backup" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + crlog "sigs.k8s.io/controller-runtime/pkg/log" +) + +// PVCBackupReconciler owns a PVCBackup through its backup lifecycle. One +// reconciler handles all PVCBackups in the cluster; per-PVCBackup state +// lives entirely in the CR's .status subresource so restarts are safe. +// +// Phases walked on a single run: +// +// Idle -> Snapshotting -> Cloning -> Moving -> Cleanup -> Synced +// +// Any error at any phase transitions the CR to Failed and keeps the +// schedule — the next fire time will attempt a fresh run. +type PVCBackupReconciler struct { + client client.Client + apiReader client.Reader + + // ResolveRuntimeConfig returns the merged runtime config for a PVCBackup: + // S3/credentials/image pulled from the cluster-wide BackupConfig singleton, + // merged with the PVCBackup's per-CR fields and the resolved source PVC's + // storage class and size. Returning (false, nil) means "no BackupConfig + // yet — do not attempt backups". + // + // Injected by the manager wiring so the BackupConfig controller owns the + // BackupConfig lookup + cross-namespace secret propagation. + ResolveRuntimeConfig func(ctx context.Context, pvcBackup *topolvmv1.PVCBackup, pvc *corev1.PersistentVolumeClaim) (backup.RuntimeConfig, bool, error) +} + +func NewPVCBackupReconciler( + c client.Client, + apiReader client.Reader, + resolve func(ctx context.Context, pvcBackup *topolvmv1.PVCBackup, pvc *corev1.PersistentVolumeClaim) (backup.RuntimeConfig, bool, error), +) *PVCBackupReconciler { + return &PVCBackupReconciler{ + client: c, + apiReader: apiReader, + ResolveRuntimeConfig: resolve, + } +} + +//+kubebuilder:rbac:groups=topolvm.io,resources=pvcbackups,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=topolvm.io,resources=pvcbackups/status,verbs=get;update;patch +//+kubebuilder:rbac:groups=topolvm.io,resources=pvcbackups/finalizers,verbs=update +//+kubebuilder:rbac:groups=core,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=core,resources=pods,verbs=get;list;watch +//+kubebuilder:rbac:groups=core,resources=pods/log,verbs=get +//+kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;update;patch;delete +//+kubebuilder:rbac:groups=snapshot.storage.k8s.io,resources=volumesnapshots,verbs=get;list;watch;create;update;patch;delete + +func (r *PVCBackupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := crlog.FromContext(ctx).WithValues("pvcbackup", req.NamespacedName) + + pb := &topolvmv1.PVCBackup{} + if err := r.client.Get(ctx, req.NamespacedName, pb); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + return ctrl.Result{}, err + } + + if pb.DeletionTimestamp != nil { + // Children carry owner refs with Controller=true so garbage + // collection handles cleanup. Nothing to do here. + return ctrl.Result{}, nil + } + + pvc := &corev1.PersistentVolumeClaim{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: pb.Namespace, Name: pb.Spec.PVCName}, pvc) + if apierrors.IsNotFound(err) { + return r.setFailed(ctx, pb, fmt.Sprintf("source PVC %q not found", pb.Spec.PVCName)) + } + if err != nil { + return ctrl.Result{}, fmt.Errorf("get source PVC: %w", err) + } + + cfg, ok, err := r.ResolveRuntimeConfig(ctx, pb, pvc) + if err != nil { + return ctrl.Result{}, fmt.Errorf("resolve runtime config: %w", err) + } + if !ok { + log.Info("no BackupConfig yet; skipping") + return ctrl.Result{RequeueAfter: time.Minute}, nil + } + + // Active run — advance the state machine. + if pb.Status.Phase != "" && + pb.Status.Phase != topolvmv1.PVCBackupPhaseIdle && + pb.Status.Phase != topolvmv1.PVCBackupPhaseSynced && + pb.Status.Phase != topolvmv1.PVCBackupPhaseFailed { + return r.advance(ctx, pb, cfg) + } + + // Idle / Synced / Failed / empty — decide whether to start a new run. + return r.maybeStartRun(ctx, pb, cfg) +} + +// maybeStartRun checks the cron schedule and manual trigger and, if a run +// is due, transitions the CR to Snapshotting and creates the VolumeSnapshot. +func (r *PVCBackupReconciler) maybeStartRun( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + if pb.Spec.Suspend { + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseIdle + s.Message = "suspended" + }) + } + + now := time.Now() + manualTrigger := pb.Spec.Trigger != "" && pb.Spec.Trigger != pb.Status.LastHandledTrigger + nextTime := nextFireTime(pb, now) + + due := manualTrigger || (!nextTime.IsZero() && !now.Before(nextTime)) + if !due { + // Requeue at the next fire time (or in 1h if no schedule — keeps + // the controller alive to pick up spec changes). + wait := time.Hour + if !nextTime.IsZero() { + wait = time.Until(nextTime) + if wait < time.Second { + wait = time.Second + } + } + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + if s.Phase == "" { + s.Phase = topolvmv1.PVCBackupPhaseIdle + } + if !nextTime.IsZero() { + t := metav1.NewTime(nextTime) + s.NextSyncTime = &t + } else { + s.NextSyncTime = nil + } + }, withRequeueAfter(wait)) + } + + // Due to fire — transition to Snapshotting and create the child + // VolumeSnapshot. The runID survives restarts via status.currentSnapshotName. + runID := now.UTC().Format("20060102150405") + snap := backup.Snapshot(cfg, runID) + if err := r.client.Create(ctx, snap); err != nil && !apierrors.IsAlreadyExists(err) { + return ctrl.Result{}, fmt.Errorf("create VolumeSnapshot: %w", err) + } + + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseSnapshotting + s.Message = "" + s.CurrentSnapshotName = snap.Name + s.CurrentTempPVCName = backup.TempPVCName(cfg.PVCName, runID) + s.CurrentMoverJobName = backup.MoverJobName(cfg.PVCName, runID) + t := metav1.NewTime(now) + s.CurrentRunStartTime = &t + if manualTrigger { + s.LastHandledTrigger = pb.Spec.Trigger + } + }) +} + +// advance walks one step of the state machine based on the current phase +// and the observed state of child objects. +func (r *PVCBackupReconciler) advance( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + switch pb.Status.Phase { + case topolvmv1.PVCBackupPhaseSnapshotting: + return r.advanceSnapshotting(ctx, pb, cfg) + case topolvmv1.PVCBackupPhaseCloning: + return r.advanceCloning(ctx, pb, cfg) + case topolvmv1.PVCBackupPhaseMoving: + return r.advanceMoving(ctx, pb, cfg) + case topolvmv1.PVCBackupPhaseCleanup: + return r.advanceCleanup(ctx, pb, cfg) + } + return ctrl.Result{}, nil +} + +func (r *PVCBackupReconciler) advanceSnapshotting( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + snap := &snapshotv1.VolumeSnapshot{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: pb.Namespace, Name: pb.Status.CurrentSnapshotName}, snap) + if apierrors.IsNotFound(err) { + return r.setFailed(ctx, pb, "VolumeSnapshot disappeared mid-run") + } + if err != nil { + return ctrl.Result{}, err + } + if snap.Status == nil || snap.Status.ReadyToUse == nil || !*snap.Status.ReadyToUse { + // still provisioning — poll. + return ctrl.Result{RequeueAfter: 5 * time.Second}, nil + } + + // Snapshot ready; derive the runID from the stored temp PVC name to + // ensure deterministic naming across reconciles. + runID := extractRunIDFromTempPVC(pb.Spec.PVCName, pb.Status.CurrentTempPVCName) + if runID == "" { + return r.setFailed(ctx, pb, "could not derive run id from status") + } + tempPVC := backup.TempPVC(cfg, runID) + if err := r.client.Create(ctx, tempPVC); err != nil && !apierrors.IsAlreadyExists(err) { + return ctrl.Result{}, fmt.Errorf("create temp PVC: %w", err) + } + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseCloning + }) +} + +func (r *PVCBackupReconciler) advanceCloning( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + tempPVC := &corev1.PersistentVolumeClaim{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: pb.Namespace, Name: pb.Status.CurrentTempPVCName}, tempPVC) + if apierrors.IsNotFound(err) { + return r.setFailed(ctx, pb, "temp PVC disappeared mid-run") + } + if err != nil { + return ctrl.Result{}, err + } + if tempPVC.Status.Phase != corev1.ClaimBound { + return ctrl.Result{RequeueAfter: 5 * time.Second}, nil + } + + runID := extractRunIDFromTempPVC(pb.Spec.PVCName, pb.Status.CurrentTempPVCName) + if runID == "" { + return r.setFailed(ctx, pb, "could not derive run id from status") + } + job := backup.MoverJob(cfg, runID) + if err := r.client.Create(ctx, job); err != nil && !apierrors.IsAlreadyExists(err) { + return ctrl.Result{}, fmt.Errorf("create mover job: %w", err) + } + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseMoving + }) +} + +func (r *PVCBackupReconciler) advanceMoving( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + job := &batchv1.Job{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: pb.Namespace, Name: pb.Status.CurrentMoverJobName}, job) + if apierrors.IsNotFound(err) { + return r.setFailed(ctx, pb, "mover Job disappeared mid-run") + } + if err != nil { + return ctrl.Result{}, err + } + + switch { + case job.Status.Succeeded > 0: + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseCleanup + s.LatestMoverStatus = &topolvmv1.MoverStatus{ + JobName: job.Name, + Succeeded: true, + } + }) + case job.Status.Failed > 0: + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseCleanup + s.LatestMoverStatus = &topolvmv1.MoverStatus{ + JobName: job.Name, + Succeeded: false, + } + s.Message = "mover Job failed" + }) + default: + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } +} + +func (r *PVCBackupReconciler) advanceCleanup( + ctx context.Context, + pb *topolvmv1.PVCBackup, + cfg backup.RuntimeConfig, +) (ctrl.Result, error) { + // Always delete the temp PVC. Delete the mover Job so a subsequent run + // can reuse the deterministic name for Cleanup diagnostics — the user + // can still see status.latestMoverStatus. + if name := pb.Status.CurrentTempPVCName; name != "" { + tempPVC := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{Namespace: pb.Namespace, Name: name}, + } + if err := r.client.Delete(ctx, tempPVC); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, fmt.Errorf("delete temp PVC: %w", err) + } + } + if name := pb.Status.CurrentMoverJobName; name != "" { + // Use propagation=Background so the Job's Pod is GC'd; otherwise + // the Pod lingers and blocks re-running with the same deterministic name. + bg := metav1.DeletePropagationBackground + job := &batchv1.Job{ + ObjectMeta: metav1.ObjectMeta{Namespace: pb.Namespace, Name: name}, + } + if err := r.client.Delete(ctx, job, &client.DeleteOptions{PropagationPolicy: &bg}); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, fmt.Errorf("delete mover Job: %w", err) + } + } + if !pb.Spec.KeepSnapshotAfterBackup { + if name := pb.Status.CurrentSnapshotName; name != "" { + snap := &snapshotv1.VolumeSnapshot{ + ObjectMeta: metav1.ObjectMeta{Namespace: pb.Namespace, Name: name}, + } + if err := r.client.Delete(ctx, snap); err != nil && !apierrors.IsNotFound(err) { + return ctrl.Result{}, fmt.Errorf("delete VolumeSnapshot: %w", err) + } + } + } + + succeeded := pb.Status.LatestMoverStatus != nil && pb.Status.LatestMoverStatus.Succeeded + now := metav1.Now() + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + if succeeded { + s.Phase = topolvmv1.PVCBackupPhaseSynced + s.LastSyncTime = &now + if s.CurrentRunStartTime != nil { + d := metav1.Duration{Duration: now.Sub(s.CurrentRunStartTime.Time)} + s.LastSyncDuration = &d + } + s.Message = "" + } else { + s.Phase = topolvmv1.PVCBackupPhaseFailed + } + s.CurrentRunStartTime = nil + s.CurrentSnapshotName = "" + s.CurrentTempPVCName = "" + s.CurrentMoverJobName = "" + }) +} + +// setFailed transitions the PVCBackup to Failed with a message and clears +// any in-flight child tracking. Child resources may still exist; the next +// reconcile will retry the run and recreate them (controllerutil.CreateOrUpdate +// pattern with IsAlreadyExists handling). +func (r *PVCBackupReconciler) setFailed(ctx context.Context, pb *topolvmv1.PVCBackup, msg string) (ctrl.Result, error) { + return r.updateStatus(ctx, pb, func(s *topolvmv1.PVCBackupStatus) { + s.Phase = topolvmv1.PVCBackupPhaseFailed + s.Message = msg + s.CurrentRunStartTime = nil + s.CurrentSnapshotName = "" + s.CurrentTempPVCName = "" + s.CurrentMoverJobName = "" + }) +} + +type updateOpt func(*ctrl.Result) + +func withRequeueAfter(d time.Duration) updateOpt { + return func(r *ctrl.Result) { r.RequeueAfter = d } +} + +// updateStatus applies mutate to a copy of .status, patches, and returns a +// Result configured by the optional updateOpts. +func (r *PVCBackupReconciler) updateStatus( + ctx context.Context, + pb *topolvmv1.PVCBackup, + mutate func(*topolvmv1.PVCBackupStatus), + opts ...updateOpt, +) (ctrl.Result, error) { + patched := pb.DeepCopy() + mutate(&patched.Status) + patched.Status.ObservedGeneration = pb.Generation + if err := r.client.Status().Patch(ctx, patched, client.MergeFrom(pb)); err != nil { + return ctrl.Result{}, err + } + res := ctrl.Result{} + for _, o := range opts { + o(&res) + } + return res, nil +} + +// nextFireTime parses .spec.schedule and returns the next fire time after +// the latest of lastSyncTime / currentRunStartTime. Zero time means no +// schedule. +func nextFireTime(pb *topolvmv1.PVCBackup, now time.Time) time.Time { + if pb.Spec.Schedule == "" { + return time.Time{} + } + parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow) + schedule, err := parser.Parse(pb.Spec.Schedule) + if err != nil { + return time.Time{} + } + anchor := pb.CreationTimestamp.Time + if pb.Status.LastSyncTime != nil && pb.Status.LastSyncTime.Time.After(anchor) { + anchor = pb.Status.LastSyncTime.Time + } + next := schedule.Next(anchor) + // Step forward until strictly after now to avoid re-firing the same slot. + for !next.After(now) { + next = schedule.Next(next) + } + return next +} + +// extractRunIDFromTempPVC recovers the run id from a deterministic temp PVC +// name. Returns "" if the name is malformed. +func extractRunIDFromTempPVC(pvcName, tempPVCName string) string { + prefix := pvcName + topolvm.BackupJobTempPVCInfix + if len(tempPVCName) <= len(prefix) { + return "" + } + if tempPVCName[:len(prefix)] != prefix { + return "" + } + return tempPVCName[len(prefix):] +} + +func (r *PVCBackupReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + Named("pvcbackup"). + For(&topolvmv1.PVCBackup{}). + Owns(&snapshotv1.VolumeSnapshot{}). + Owns(&corev1.PersistentVolumeClaim{}). + Owns(&batchv1.Job{}). + Complete(r) +} diff --git a/internal/controller/restore_controller.go b/internal/controller/restore_controller.go new file mode 100644 index 000000000..c5fda0605 --- /dev/null +++ b/internal/controller/restore_controller.go @@ -0,0 +1,226 @@ +package controller + +import ( + "context" + "fmt" + "time" + + "github.com/topolvm/topolvm" + topolvmv1 "github.com/topolvm/topolvm/api/v1" + "github.com/topolvm/topolvm/internal/backup" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + crlog "sigs.k8s.io/controller-runtime/pkg/log" +) + +// RestoreReconciler walks a Restore CR through: +// +// Pending -> provision target PVC -> wait for Bound -> Running (restore Job) +// -> Succeeded | Failed +// +// The target PVC is deliberately NOT owned by the Restore CR — if the +// Restore is deleted, the restored data should remain. The restore Job is +// owned by the Restore CR so deleting the CR cascades the Job away. +type RestoreReconciler struct { + client client.Client + apiReader client.Reader + + // LoadBackupConfig returns the cluster-wide BackupConfig singleton, + // injected so this controller does not duplicate loadSingleton logic. + LoadBackupConfig func(ctx context.Context) (*topolvmv1.BackupConfig, bool, error) + + ControllerNamespace string + ResticImage string + ServiceAccountName string +} + +func NewRestoreReconciler( + c client.Client, + apiReader client.Reader, + loadBC func(ctx context.Context) (*topolvmv1.BackupConfig, bool, error), + controllerNamespace, resticImage, serviceAccountName string, +) *RestoreReconciler { + return &RestoreReconciler{ + client: c, + apiReader: apiReader, + LoadBackupConfig: loadBC, + ControllerNamespace: controllerNamespace, + ResticImage: resticImage, + ServiceAccountName: serviceAccountName, + } +} + +//+kubebuilder:rbac:groups=topolvm.io,resources=restores,verbs=get;list;watch;update;patch +//+kubebuilder:rbac:groups=topolvm.io,resources=restores/status,verbs=get;update;patch + +func (r *RestoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + log := crlog.FromContext(ctx).WithValues("restore", req.NamespacedName) + + rs := &topolvmv1.Restore{} + if err := r.client.Get(ctx, req.NamespacedName, rs); err != nil { + if apierrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + return ctrl.Result{}, err + } + if rs.DeletionTimestamp != nil { + return ctrl.Result{}, nil + } + + // Terminal phases never re-enter the flow. + if rs.Status.Phase == topolvmv1.RestorePhaseSucceeded || rs.Status.Phase == topolvmv1.RestorePhaseFailed { + return ctrl.Result{}, nil + } + + bc, ok, err := r.LoadBackupConfig(ctx) + if err != nil { + return ctrl.Result{}, fmt.Errorf("load BackupConfig: %w", err) + } + if !ok { + log.Info("no BackupConfig yet; cannot restore") + return ctrl.Result{RequeueAfter: time.Minute}, nil + } + + if err := r.ensureTargetPVC(ctx, rs); err != nil { + return ctrl.Result{}, fmt.Errorf("ensure target PVC: %w", err) + } + + pvc := &corev1.PersistentVolumeClaim{} + err = r.client.Get(ctx, client.ObjectKey{Namespace: rs.Namespace, Name: rs.Spec.TargetPVCName}, pvc) + if err != nil { + return ctrl.Result{}, fmt.Errorf("get target PVC: %w", err) + } + if pvc.Status.Phase != corev1.ClaimBound { + return r.setRestoreStatus(ctx, rs, topolvmv1.RestorePhasePending, "waiting for target PVC to bind") + } + + // PVC is Bound — ensure the restore Job exists and watch for completion. + cfg := backup.RestoreConfig{ + RestoreName: rs.Name, + RestoreNamespace: rs.Namespace, + RestoreUID: string(rs.UID), + TargetPVCName: rs.Spec.TargetPVCName, + SourceNamespace: rs.Spec.SourceNamespace, + SourcePVCName: rs.Spec.SourcePVCName, + SnapshotID: rs.Spec.SnapshotID, + S3Endpoint: bc.Spec.S3.Endpoint, + S3Bucket: bc.Spec.S3.Bucket, + S3Region: bc.Spec.S3.Region, + S3InsecureTLS: bc.Spec.S3.InsecureTLS, + S3Prefix: bc.Spec.S3.Prefix, + S3CredentialsSecretName: bc.Spec.S3.CredentialsSecretRef.Name, + ResticPasswordSecretName: bc.Spec.ResticPasswordSecretRef.Name, + ResticImage: r.ResticImage, + ServiceAccountName: r.ServiceAccountName, + } + job := backup.RestoreJob(cfg) + got := &batchv1.Job{} + err = r.client.Get(ctx, client.ObjectKey{Namespace: job.Namespace, Name: job.Name}, got) + if apierrors.IsNotFound(err) { + if err := r.client.Create(ctx, job); err != nil { + return ctrl.Result{}, fmt.Errorf("create restore Job: %w", err) + } + return r.setRestoreStatus(ctx, rs, topolvmv1.RestorePhaseRunning, "restore Job created", withJobName(job.Name)) + } + if err != nil { + return ctrl.Result{}, err + } + + switch { + case got.Status.Succeeded > 0: + return r.setRestoreStatus(ctx, rs, topolvmv1.RestorePhaseSucceeded, "restore complete", withJobName(got.Name), withCompletion()) + case got.Status.Failed > 0: + return r.setRestoreStatus(ctx, rs, topolvmv1.RestorePhaseFailed, "restore Job failed", withJobName(got.Name), withCompletion()) + default: + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } +} + +// ensureTargetPVC creates the target PVC if missing. The target PVC is NOT +// owned by the Restore CR — deleting the Restore must not delete the +// restored data. +func (r *RestoreReconciler) ensureTargetPVC(ctx context.Context, rs *topolvmv1.Restore) error { + got := &corev1.PersistentVolumeClaim{} + err := r.client.Get(ctx, client.ObjectKey{Namespace: rs.Namespace, Name: rs.Spec.TargetPVCName}, got) + if err == nil { + return nil + } + if !apierrors.IsNotFound(err) { + return err + } + sc := rs.Spec.StorageClassName + want := &corev1.PersistentVolumeClaim{ + ObjectMeta: metav1.ObjectMeta{ + Name: rs.Spec.TargetPVCName, + Namespace: rs.Namespace, + Labels: map[string]string{ + topolvm.CreatedbyLabelKey: topolvm.CreatedbyLabelValue, + topolvm.BackupManagedByLabel: topolvm.BackupManagedByValue, + }, + }, + Spec: corev1.PersistentVolumeClaimSpec{ + StorageClassName: &sc, + AccessModes: []corev1.PersistentVolumeAccessMode{corev1.ReadWriteOnce}, + Resources: corev1.VolumeResourceRequirements{ + Requests: corev1.ResourceList{ + corev1.ResourceStorage: rs.Spec.Size, + }, + }, + }, + } + return r.client.Create(ctx, want) +} + +type restoreStatusOpt func(*topolvmv1.RestoreStatus) + +func withJobName(name string) restoreStatusOpt { + return func(s *topolvmv1.RestoreStatus) { + s.JobName = name + if s.StartTime == nil { + now := metav1.Now() + s.StartTime = &now + } + } +} + +func withCompletion() restoreStatusOpt { + return func(s *topolvmv1.RestoreStatus) { + now := metav1.Now() + s.CompletionTime = &now + } +} + +func (r *RestoreReconciler) setRestoreStatus( + ctx context.Context, + rs *topolvmv1.Restore, + phase topolvmv1.RestorePhase, + msg string, + opts ...restoreStatusOpt, +) (ctrl.Result, error) { + patched := rs.DeepCopy() + patched.Status.Phase = phase + patched.Status.Message = msg + for _, o := range opts { + o(&patched.Status) + } + if err := r.client.Status().Patch(ctx, patched, client.MergeFrom(rs)); err != nil { + return ctrl.Result{}, err + } + // Pending/Running phases requeue so we keep watching until terminal. + if phase == topolvmv1.RestorePhasePending || phase == topolvmv1.RestorePhaseRunning { + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } + return ctrl.Result{}, nil +} + +func (r *RestoreReconciler) SetupWithManager(mgr ctrl.Manager) error { + return ctrl.NewControllerManagedBy(mgr). + Named("restore"). + For(&topolvmv1.Restore{}). + Owns(&batchv1.Job{}). + Complete(r) +} diff --git a/pkg/controller/backup_controllers.go b/pkg/controller/backup_controllers.go new file mode 100644 index 000000000..d2ccc5ef3 --- /dev/null +++ b/pkg/controller/backup_controllers.go @@ -0,0 +1,34 @@ +package controller + +import ( + internalController "github.com/topolvm/topolvm/internal/controller" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// SetupBackupReconcilers wires the three backup/restore reconcilers: +// BackupConfig (PVC -> PVCBackup + Secret propagation), PVCBackup (runs the +// actual backup state machine), and Restore (one-shot restore flow). +// +// controllerNamespace is the namespace where the user-authored S3 creds and +// restic password Secrets live; the BackupConfig controller mirrors them +// into every namespace that has a managed PVC. +func SetupBackupReconcilers( + mgr ctrl.Manager, + c client.Client, + apiReader client.Reader, + controllerNamespace, resticImage, moverServiceAccountName string, +) error { + bc := internalController.NewBackupConfigReconciler(c, apiReader, controllerNamespace, resticImage, moverServiceAccountName) + if err := bc.SetupWithManager(mgr); err != nil { + return err + } + + pb := internalController.NewPVCBackupReconciler(c, apiReader, bc.ResolveRuntimeConfig) + if err := pb.SetupWithManager(mgr); err != nil { + return err + } + + rs := internalController.NewRestoreReconciler(c, apiReader, bc.LoadSingleton, controllerNamespace, resticImage, moverServiceAccountName) + return rs.SetupWithManager(mgr) +} diff --git a/test/e2e/Makefile b/test/e2e/Makefile index e60446413..9b47d659f 100644 --- a/test/e2e/Makefile +++ b/test/e2e/Makefile @@ -9,6 +9,8 @@ TEST_LEGACY ?= false TEST_LVMD_TYPE ?= systemd-service # 1 to enable RWX tests and install csi-driver-nfs RWX_ENABLED ?= +# 1 to enable restic-backed backup/restore tests (requires BACKUP_S3_* secrets in env) +BACKUP_ENABLED ?= BACKING_STORE := ./build BINDIR := $(shell pwd)/bin @@ -61,6 +63,10 @@ ifeq ($(RWX_ENABLED),1) HELM_VALUES_FILES += manifests/values/rwx.yaml endif +ifeq ($(BACKUP_ENABLED),1) +HELM_VALUES_FILES += manifests/values/backup.yaml +endif + ifeq ($(shell [ $(STORAGE_CAPACITY) = "true" ] && [ $(KUBERNETES_MINOR) -ge 33 ] && echo yes),yes) STORAGE_CAPACITY_SCORING := true MINIKUBE_FEATURE_GATES := $(MINIKUBE_FEATURE_GATES),StorageCapacityScoring=true @@ -342,4 +348,11 @@ common/test: $(GINKGO) STORAGE_CAPACITY_SCORING=$(STORAGE_CAPACITY_SCORING) \ USE_LEGACY=$(USE_LEGACY) \ RWX_ENABLED=$(RWX_ENABLED) \ + BACKUP_ENABLED=$(BACKUP_ENABLED) \ + BACKUP_S3_ENDPOINT="$(BACKUP_S3_ENDPOINT)" \ + BACKUP_S3_BUCKET="$(BACKUP_S3_BUCKET)" \ + BACKUP_S3_ACCESS_KEY="$(BACKUP_S3_ACCESS_KEY)" \ + BACKUP_S3_SECRET_KEY="$(BACKUP_S3_SECRET_KEY)" \ + BACKUP_RESTIC_PASSWORD="$(BACKUP_RESTIC_PASSWORD)" \ + BACKUP_S3_PREFIX="$(BACKUP_S3_PREFIX)" \ $(GINKGO) --fail-fast -v $(GINKGO_FLAGS) . diff --git a/test/e2e/backup_test.go b/test/e2e/backup_test.go new file mode 100644 index 000000000..894e68f0e --- /dev/null +++ b/test/e2e/backup_test.go @@ -0,0 +1,267 @@ +package e2e + +import ( + _ "embed" + "fmt" + "os" + "strings" + "time" + + . "github.com/onsi/ginkgo/v2" + "github.com/onsi/ginkgo/v2/types" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" +) + +var ( + //go:embed testdata/backup/pvc-template.yaml + backupPVCTemplateYAML string + + //go:embed testdata/backup/writer-pod-template.yaml + backupWriterPodTemplateYAML string + + //go:embed testdata/backup/reader-pod-template.yaml + backupReaderPodTemplateYAML string + + //go:embed testdata/backup/s3-creds-secret.yaml + backupS3CredsSecretYAML string + + //go:embed testdata/backup/restic-password-secret.yaml + backupResticPasswordSecretYAML string + + //go:embed testdata/backup/backupconfig-template.yaml + backupConfigTemplateYAML string + + //go:embed testdata/backup/restore-template.yaml + backupRestoreTemplateYAML string +) + +const ( + backupPVCName = "backup-src" + backupWriterPodName = "backup-writer" + backupReaderPodName = "backup-reader" + backupRestoreName = "backup-restore" + backupRestorePVCName = "backup-restored" + backupS3CredsSecret = "s3-creds" + backupResticPwSecret = "restic-pw" + backupPVCSizeMi = 512 + backupFileContents = "hello-from-backup" + backupControllerNS = "topolvm-system" +) + +type backupEnv struct { + endpoint string + bucket string + accessKey string + secretKey string + resticPassword string + prefix string +} + +func (e backupEnv) complete() bool { + return e.endpoint != "" && e.bucket != "" && + e.accessKey != "" && e.secretKey != "" && e.resticPassword != "" +} + +func loadBackupEnv() backupEnv { + return backupEnv{ + endpoint: os.Getenv("BACKUP_S3_ENDPOINT"), + bucket: os.Getenv("BACKUP_S3_BUCKET"), + accessKey: os.Getenv("BACKUP_S3_ACCESS_KEY"), + secretKey: os.Getenv("BACKUP_S3_SECRET_KEY"), + resticPassword: os.Getenv("BACKUP_RESTIC_PASSWORD"), + prefix: os.Getenv("BACKUP_S3_PREFIX"), + } +} + +func isBackupEnabled() bool { + return os.Getenv("BACKUP_ENABLED") == "1" +} + +func dumpBackupDiagnostics(ns string) { + logf("\n===== backup diagnostics for namespace %s =====\n", ns) + for _, cmd := range [][]string{ + {"get", "pvc", "-n", ns, "-o", "wide"}, + {"get", "pods", "-n", ns, "-o", "wide"}, + {"get", "volumesnapshot", "-n", ns}, + {"get", "jobs", "-n", ns}, + {"get", "pvcbackup", "-n", ns, "-o", "yaml"}, + {"get", "restore", "-n", ns, "-o", "yaml"}, + {"describe", "pvcbackup", "-n", ns}, + {"describe", "restore", "-n", ns}, + {"get", "events", "-n", ns, "--sort-by=.metadata.creationTimestamp"}, + {"get", "backupconfig"}, + {"get", "pods", "-n", backupControllerNS}, + {"logs", "-n", backupControllerNS, "-l", "app.kubernetes.io/component=controller", "-c", "topolvm-controller", "--tail=300"}, + } { + out, err := kubectl(cmd...) + logf("\n--- kubectl %v ---\n", cmd) + logf("%s\n", string(out)) + if err != nil { + logf("(error: %v)\n", err) + } + } + logf("===== end diagnostics =====\n\n") +} + +func testBackup() { + if !isBackupEnabled() { + return + } + + var ( + ns string + bkpEnv backupEnv + applied bool + ) + + BeforeEach(func() { + bkpEnv = loadBackupEnv() + if !bkpEnv.complete() { + Skip("BACKUP_* env vars not set; cannot run backup e2e") + } + // Per-run prefix keeps parallel or retried CI runs isolated inside the + // shared bucket. If the caller (CI) set BACKUP_S3_PREFIX explicitly + // (e.g. based on $GITHUB_RUN_ID) we honor it; otherwise fall back to a + // locally-generated random prefix. + if bkpEnv.prefix == "" { + bkpEnv.prefix = "e2e/" + randomString() + } + ns = "backup-test-" + randomString() + createNamespace(ns) + }) + + AfterEach(func() { + if CurrentSpecReport().State.Is(types.SpecStateFailureStates) { + dumpBackupDiagnostics(ns) + } + // Delete the BackupConfig first so the BackupConfig controller stops + // reconciling PVCBackups while the namespace is torn down — otherwise + // it may keep recreating objects in a doomed namespace. + if applied { + _, _ = kubectl("delete", "backupconfig", "default", "--ignore-not-found", "--wait=false") + } + _, err := kubectl("delete", "namespaces", ns, "--wait=true", "--timeout=120s") + if err != nil { + logf("namespace teardown did not complete cleanly: %v\n", err) + dumpBackupDiagnostics(ns) + } + }) + + It("backs up a PVC to restic and restores it into a fresh PVC", func() { + By("creating S3 + restic password Secrets in the controller namespace") + s3Yaml := fmt.Sprintf(backupS3CredsSecretYAML, backupS3CredsSecret, backupControllerNS, bkpEnv.accessKey, bkpEnv.secretKey) + _, err := kubectlWithInput([]byte(s3Yaml), "apply", "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + pwYaml := fmt.Sprintf(backupResticPasswordSecretYAML, backupResticPwSecret, backupControllerNS, bkpEnv.resticPassword) + _, err = kubectlWithInput([]byte(pwYaml), "apply", "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + By("applying the cluster-wide BackupConfig") + bcYAML := fmt.Sprintf(backupConfigTemplateYAML, + bkpEnv.endpoint, bkpEnv.bucket, bkpEnv.prefix, + backupS3CredsSecret, backupControllerNS, + backupResticPwSecret, backupControllerNS, + ) + _, err = kubectlWithInput([]byte(bcYAML), "apply", "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + applied = true + + By("creating the source PVC and writing a sentinel file") + pvcYAML := fmt.Sprintf(backupPVCTemplateYAML, backupPVCName, backupPVCSizeMi) + _, err = kubectlWithInput([]byte(pvcYAML), "apply", "-n", ns, "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + Eventually(func() error { + var pvc corev1.PersistentVolumeClaim + if err := getObjects(&pvc, "pvc", "-n", ns, backupPVCName); err != nil { + return err + } + if pvc.Status.Phase != corev1.ClaimBound { + return fmt.Errorf("source PVC not bound: %s", pvc.Status.Phase) + } + return nil + }).WithTimeout(2 * time.Minute).Should(Succeed()) + + writerYAML := fmt.Sprintf(backupWriterPodTemplateYAML, backupWriterPodName, backupFileContents, backupPVCName) + _, err = kubectlWithInput([]byte(writerYAML), "apply", "-n", ns, "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + Eventually(func() error { + var p corev1.Pod + if err := getObjects(&p, "pod", "-n", ns, backupWriterPodName); err != nil { + return err + } + if p.Status.Phase != corev1.PodSucceeded { + return fmt.Errorf("writer pod phase=%s", p.Status.Phase) + } + return nil + }).WithTimeout(2 * time.Minute).Should(Succeed()) + + By("waiting for the BackupConfig controller to create a managed PVCBackup") + Eventually(func() error { + _, err := kubectl("get", "pvcbackup", "-n", ns, backupPVCName) + return err + }).WithTimeout(1 * time.Minute).Should(Succeed()) + + By("triggering an immediate backup run via .spec.trigger") + trigger := fmt.Sprintf("e2e-%d", time.Now().UnixNano()) + patch := fmt.Sprintf(`{"spec":{"trigger":%q}}`, trigger) + _, err = kubectl("patch", "pvcbackup", "-n", ns, backupPVCName, "--type=merge", "-p", patch) + Expect(err).ShouldNot(HaveOccurred()) + + By("waiting for the PVCBackup to reach Synced") + Eventually(func() (string, error) { + out, err := kubectl("get", "pvcbackup", "-n", ns, backupPVCName, "-o", "jsonpath={.status.phase}") + if err != nil { + return "", err + } + return strings.TrimSpace(string(out)), nil + }).WithTimeout(8 * time.Minute).WithPolling(5 * time.Second).Should(Equal("Synced")) + + By("deleting the source pod + PVC so the restore is against a clean slate") + _, _ = kubectl("delete", "pod", "-n", ns, backupWriterPodName, "--ignore-not-found", "--wait=true") + _, _ = kubectl("delete", "pvcbackup", "-n", ns, backupPVCName, "--wait=true") + _, _ = kubectl("delete", "pvc", "-n", ns, backupPVCName, "--wait=true") + + By("creating a Restore CR targeting a fresh PVC") + restoreYAML := fmt.Sprintf(backupRestoreTemplateYAML, + backupRestoreName, ns, + ns, backupPVCName, + backupRestorePVCName, backupPVCSizeMi, + ) + _, err = kubectlWithInput([]byte(restoreYAML), "apply", "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + By("waiting for the Restore to reach Succeeded") + Eventually(func() (string, error) { + out, err := kubectl("get", "restore", "-n", ns, backupRestoreName, "-o", "jsonpath={.status.phase}") + if err != nil { + return "", err + } + return strings.TrimSpace(string(out)), nil + }).WithTimeout(8 * time.Minute).WithPolling(5 * time.Second).Should(Equal("Succeeded")) + + By("mounting the restored PVC and verifying the sentinel file") + readerYAML := fmt.Sprintf(backupReaderPodTemplateYAML, backupReaderPodName, backupRestorePVCName) + _, err = kubectlWithInput([]byte(readerYAML), "apply", "-n", ns, "-f", "-") + Expect(err).ShouldNot(HaveOccurred()) + + Eventually(func() error { + var p corev1.Pod + if err := getObjects(&p, "pod", "-n", ns, backupReaderPodName); err != nil { + return err + } + if p.Status.Phase != corev1.PodSucceeded { + return fmt.Errorf("reader pod phase=%s", p.Status.Phase) + } + return nil + }).WithTimeout(3 * time.Minute).Should(Succeed()) + + out, err := kubectl("logs", "-n", ns, backupReaderPodName) + Expect(err).ShouldNot(HaveOccurred()) + Expect(strings.TrimSpace(string(out))).To(Equal(backupFileContents), + "restored PVC did not contain the pre-backup sentinel file") + }) +} diff --git a/test/e2e/manifests/values/backup.yaml b/test/e2e/manifests/values/backup.yaml new file mode 100644 index 000000000..5553687cc --- /dev/null +++ b/test/e2e/manifests/values/backup.yaml @@ -0,0 +1,3 @@ +controller: + backup: + enabled: true diff --git a/test/e2e/suite_test.go b/test/e2e/suite_test.go index cf9020c92..52dcc0ef6 100644 --- a/test/e2e/suite_test.go +++ b/test/e2e/suite_test.go @@ -142,4 +142,5 @@ var _ = Describe("TopoLVM", func() { Context("empty storageclass", testEmptyStorageClass) Context("CSI sanity", testSanity) Context("rwx", testRWX) + Context("backup", testBackup) }) diff --git a/test/e2e/testdata/backup/backupconfig-template.yaml b/test/e2e/testdata/backup/backupconfig-template.yaml new file mode 100644 index 000000000..b5e92cc22 --- /dev/null +++ b/test/e2e/testdata/backup/backupconfig-template.yaml @@ -0,0 +1,17 @@ +apiVersion: topolvm.io/v1 +kind: BackupConfig +metadata: + name: default +spec: + s3: + endpoint: %q + bucket: %q + prefix: %q + credentialsSecretRef: + name: %s + namespace: %s + resticPasswordSecretRef: + name: %s + namespace: %s + volumeSnapshotClassName: topolvm-provisioner-thin + # Leave schedule empty so the controller only backs up on manual trigger. diff --git a/test/e2e/testdata/backup/pvc-template.yaml b/test/e2e/testdata/backup/pvc-template.yaml new file mode 100644 index 000000000..e11fa101b --- /dev/null +++ b/test/e2e/testdata/backup/pvc-template.yaml @@ -0,0 +1,10 @@ +apiVersion: v1 +kind: PersistentVolumeClaim +metadata: + name: %s +spec: + accessModes: [ReadWriteOnce] + storageClassName: topolvm-provisioner-thin + resources: + requests: + storage: %dMi diff --git a/test/e2e/testdata/backup/reader-pod-template.yaml b/test/e2e/testdata/backup/reader-pod-template.yaml new file mode 100644 index 000000000..70203941a --- /dev/null +++ b/test/e2e/testdata/backup/reader-pod-template.yaml @@ -0,0 +1,27 @@ +apiVersion: v1 +kind: Pod +metadata: + name: %s +spec: + restartPolicy: Never + containers: + - name: reader + image: busybox:1.36 + command: + - /bin/sh + - -c + - | + set -eu + # Wait up to 30s for the file to exist, then emit it. + for i in $(seq 1 30); do + if [ -f /data/hello.txt ]; then break; fi + sleep 1 + done + cat /data/hello.txt + volumeMounts: + - mountPath: /data + name: data + volumes: + - name: data + persistentVolumeClaim: + claimName: %s diff --git a/test/e2e/testdata/backup/restic-password-secret.yaml b/test/e2e/testdata/backup/restic-password-secret.yaml new file mode 100644 index 000000000..ede2ed9bf --- /dev/null +++ b/test/e2e/testdata/backup/restic-password-secret.yaml @@ -0,0 +1,8 @@ +apiVersion: v1 +kind: Secret +metadata: + name: %s + namespace: %s +type: Opaque +stringData: + password: %q diff --git a/test/e2e/testdata/backup/restore-template.yaml b/test/e2e/testdata/backup/restore-template.yaml new file mode 100644 index 000000000..250195a5f --- /dev/null +++ b/test/e2e/testdata/backup/restore-template.yaml @@ -0,0 +1,11 @@ +apiVersion: topolvm.io/v1 +kind: Restore +metadata: + name: %s + namespace: %s +spec: + sourceNamespace: %s + sourcePVCName: %s + targetPVCName: %s + size: %dMi + storageClassName: topolvm-provisioner-thin diff --git a/test/e2e/testdata/backup/s3-creds-secret.yaml b/test/e2e/testdata/backup/s3-creds-secret.yaml new file mode 100644 index 000000000..d16465a05 --- /dev/null +++ b/test/e2e/testdata/backup/s3-creds-secret.yaml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: Secret +metadata: + name: %s + namespace: %s +type: Opaque +stringData: + AWS_ACCESS_KEY_ID: %q + AWS_SECRET_ACCESS_KEY: %q diff --git a/test/e2e/testdata/backup/writer-pod-template.yaml b/test/e2e/testdata/backup/writer-pod-template.yaml new file mode 100644 index 000000000..a3d6f51b2 --- /dev/null +++ b/test/e2e/testdata/backup/writer-pod-template.yaml @@ -0,0 +1,23 @@ +apiVersion: v1 +kind: Pod +metadata: + name: %s +spec: + restartPolicy: Never + containers: + - name: writer + image: busybox:1.36 + command: + - /bin/sh + - -c + - | + set -eu + echo -n "%s" > /data/hello.txt + sync + volumeMounts: + - mountPath: /data + name: data + volumes: + - name: data + persistentVolumeClaim: + claimName: %s From 9c3dd3f0d0048546e40e69fdff6529cc2ce886e6 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 10:48:29 -0700 Subject: [PATCH 2/8] chart: regenerate README.md for new backup values helm-docs picks up the three new controller.backup.* rows introduced by the prior commit. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- charts/topolvm/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/charts/topolvm/README.md b/charts/topolvm/README.md index f209f91ca..67f6fad13 100644 --- a/charts/topolvm/README.md +++ b/charts/topolvm/README.md @@ -17,6 +17,9 @@ See [Getting Started](https://github.com/topolvm/topolvm/blob/topolvm-chart-v16. | controller.additionalContainers | list | `[]` | Define extra containers to add to the Deployment. Please ensure not to use any existing container names. | | controller.affinity | string | `"podAntiAffinity:\n requiredDuringSchedulingIgnoredDuringExecution:\n - labelSelector:\n matchExpressions:\n - key: app.kubernetes.io/component\n operator: In\n values:\n - controller\n - key: app.kubernetes.io/name\n operator: In\n values:\n - {{ include \"topolvm.name\" . }}\n topologyKey: kubernetes.io/hostname\n"` | Specify affinity. # ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity | | controller.args | list | `[]` | Arguments to be passed to the command. | +| controller.backup.enabled | bool | `false` | Enable the BackupConfig/PVCBackup/Restore controllers. When true, the controller watches the cluster-scoped BackupConfig named `default` and drives restic-based backups of matching PVCs to S3. | +| controller.backup.moverServiceAccount | string | `"default"` | ServiceAccount under which the mover and restore Jobs run in each target namespace. Must already exist (or be created separately) in every namespace that contains a backed-up PVC. Defaults to the namespace's `default` ServiceAccount. | +| controller.backup.resticImage | string | `"restic/restic:0.17.3"` | Container image used for the mover and restore Jobs. Must contain the `restic` binary. | | controller.initContainers | list | `[]` | Additional initContainers for the controller service. | | controller.labels | object | `{}` | Additional labels to be added to the Deployment. | | controller.leaderElection.enabled | bool | `true` | Enable leader election for controller and all sidecars. | From ce5b63fbe99db1fe1912904aa187e96a824bbf28 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 11:13:02 -0700 Subject: [PATCH 3/8] generated: fix chart CRD wrapping and regenerate role.yaml - Re-emit the 6 chart CRD templates with the trailing layout `make manifests` produces: content, blank line, `{{ end }}`, newline. The previous pattern (`{{ end }}` then trailing blank) diverged from the Makefile's xargs-printf template and broke `make check-uncommitted`. - Regenerate config/rbac/role.yaml across every package that carries +kubebuilder:rbac markers. Earlier I only ran controller-gen against internal/controller/... which dropped the `csidrivers` resource and collapsed `logicalvolumes` into the wrong rule group. No runtime behavior change; CI parity only. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- .../templates/crds/topolvm.cybozu.com_backupconfigs.yaml | 2 +- .../topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml | 2 +- charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml | 2 +- charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml | 2 +- charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml | 2 +- charts/topolvm/templates/crds/topolvm.io_restores.yaml | 2 +- config/rbac/role.yaml | 3 ++- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml index b8a3ce528..033125373 100644 --- a/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_backupconfigs.yaml @@ -299,5 +299,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml index 5485d94dd..dd673594e 100644 --- a/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_pvcbackups.yaml @@ -257,5 +257,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml b/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml index e548dd3c6..8aa2a3534 100644 --- a/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml +++ b/charts/topolvm/templates/crds/topolvm.cybozu.com_restores.yaml @@ -181,5 +181,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml b/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml index 7be78466e..e20ce3bec 100644 --- a/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml +++ b/charts/topolvm/templates/crds/topolvm.io_backupconfigs.yaml @@ -299,5 +299,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml b/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml index 90843c5b2..247519c71 100644 --- a/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml +++ b/charts/topolvm/templates/crds/topolvm.io_pvcbackups.yaml @@ -257,5 +257,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/charts/topolvm/templates/crds/topolvm.io_restores.yaml b/charts/topolvm/templates/crds/topolvm.io_restores.yaml index 65be9c711..5c4d50f54 100644 --- a/charts/topolvm/templates/crds/topolvm.io_restores.yaml +++ b/charts/topolvm/templates/crds/topolvm.io_restores.yaml @@ -181,5 +181,5 @@ spec: storage: true subresources: status: {} -{{ end }} +{{ end }} diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 56e52c19f..a670d46cf 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -84,6 +84,7 @@ rules: - apiGroups: - storage.k8s.io resources: + - csidrivers - storageclasses verbs: - get @@ -93,7 +94,6 @@ rules: - topolvm.io resources: - backupconfigs - - logicalvolumes - restores verbs: - get @@ -115,6 +115,7 @@ rules: - apiGroups: - topolvm.io resources: + - logicalvolumes - pvcbackups verbs: - create From 92c4844ee7b45b8b44352d889bc10f05ebc7f31e Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 11:17:06 -0700 Subject: [PATCH 4/8] fix: do not wait for Bound with WaitForFirstConsumer storage classes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TopoLVM's default StorageClass uses volumeBindingMode: WaitForFirstConsumer, meaning a PVC stays Pending until a Pod references it. Both the PVCBackup and Restore controllers were waiting for their PVCs to reach Bound before creating the mover/restore Job — a deadlock: the PVC never binds because no Pod exists, and the controller never creates the Pod because it's waiting on bind. The mover and restore Jobs are the *intended* first consumers. Create them eagerly; the scheduler picks a node when the Pod is scheduled, which triggers TopoLVM provisioning and binds the PVC. The e2e test had the same shape mistake: it waited for the source PVC to bind before creating the writer pod. Replaced with just waiting for the writer pod to reach Succeeded, which is an implicit (and correct) bind-and-provision check. This is why the first backup e2e run failed at `source PVC not bound: Pending` — the Eventually timed out at 120s because nothing was consuming the PVC. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- internal/controller/pvcbackup_controller.go | 8 +++++--- internal/controller/restore_controller.go | 9 +++++---- test/e2e/backup_test.go | 16 ++++------------ 3 files changed, 14 insertions(+), 19 deletions(-) diff --git a/internal/controller/pvcbackup_controller.go b/internal/controller/pvcbackup_controller.go index 869f34f7f..b05f899bd 100644 --- a/internal/controller/pvcbackup_controller.go +++ b/internal/controller/pvcbackup_controller.go @@ -242,9 +242,11 @@ func (r *PVCBackupReconciler) advanceCloning( if err != nil { return ctrl.Result{}, err } - if tempPVC.Status.Phase != corev1.ClaimBound { - return ctrl.Result{RequeueAfter: 5 * time.Second}, nil - } + // Do NOT wait for the temp PVC to reach Bound here. TopoLVM's default + // StorageClass uses WaitForFirstConsumer, so the PVC will stay Pending + // until a Pod references it. The mover Job we're about to create is + // exactly that first consumer — creating it triggers the scheduler to + // pick a node and TopoLVM to provision the underlying LV. runID := extractRunIDFromTempPVC(pb.Spec.PVCName, pb.Status.CurrentTempPVCName) if runID == "" { diff --git a/internal/controller/restore_controller.go b/internal/controller/restore_controller.go index c5fda0605..4324163de 100644 --- a/internal/controller/restore_controller.go +++ b/internal/controller/restore_controller.go @@ -94,11 +94,12 @@ func (r *RestoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct if err != nil { return ctrl.Result{}, fmt.Errorf("get target PVC: %w", err) } - if pvc.Status.Phase != corev1.ClaimBound { - return r.setRestoreStatus(ctx, rs, topolvmv1.RestorePhasePending, "waiting for target PVC to bind") - } + // Do NOT wait for Bound: TopoLVM's default StorageClass uses + // WaitForFirstConsumer, so the target PVC stays Pending until the + // restore Job's Pod references it. Creating the Job here is the + // trigger for provisioning. - // PVC is Bound — ensure the restore Job exists and watch for completion. + // Ensure the restore Job exists and watch for completion. cfg := backup.RestoreConfig{ RestoreName: rs.Name, RestoreNamespace: rs.Namespace, diff --git a/test/e2e/backup_test.go b/test/e2e/backup_test.go index 894e68f0e..79a1064b3 100644 --- a/test/e2e/backup_test.go +++ b/test/e2e/backup_test.go @@ -173,17 +173,9 @@ func testBackup() { _, err = kubectlWithInput([]byte(pvcYAML), "apply", "-n", ns, "-f", "-") Expect(err).ShouldNot(HaveOccurred()) - Eventually(func() error { - var pvc corev1.PersistentVolumeClaim - if err := getObjects(&pvc, "pvc", "-n", ns, backupPVCName); err != nil { - return err - } - if pvc.Status.Phase != corev1.ClaimBound { - return fmt.Errorf("source PVC not bound: %s", pvc.Status.Phase) - } - return nil - }).WithTimeout(2 * time.Minute).Should(Succeed()) - + // The TopoLVM StorageClass uses WaitForFirstConsumer, so the PVC + // stays Pending until a Pod references it. Create the writer Pod + // right away and use its completion as the implicit bind check. writerYAML := fmt.Sprintf(backupWriterPodTemplateYAML, backupWriterPodName, backupFileContents, backupPVCName) _, err = kubectlWithInput([]byte(writerYAML), "apply", "-n", ns, "-f", "-") Expect(err).ShouldNot(HaveOccurred()) @@ -197,7 +189,7 @@ func testBackup() { return fmt.Errorf("writer pod phase=%s", p.Status.Phase) } return nil - }).WithTimeout(2 * time.Minute).Should(Succeed()) + }).WithTimeout(3 * time.Minute).Should(Succeed()) By("waiting for the BackupConfig controller to create a managed PVCBackup") Eventually(func() error { From c5303ab90b9592145bde308afcafabcf204db388 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 11:36:22 -0700 Subject: [PATCH 5/8] chore: gofmt -s the three new backup/restore files `make test` runs `gofmt -s -l` via the lint target; these three files were out of the canonical form: - import group ordering in internal/backup/manifests.go - const/field alignment in api/v1/restore_types.go - map literal alignment in internal/controller/backupconfig_controller_test.go No code behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- api/v1/restore_types.go | 8 ++++---- internal/backup/manifests.go | 2 +- .../controller/backupconfig_controller_test.go | 16 ++++++++-------- 3 files changed, 13 insertions(+), 13 deletions(-) diff --git a/api/v1/restore_types.go b/api/v1/restore_types.go index f12e2e708..8b83692c9 100644 --- a/api/v1/restore_types.go +++ b/api/v1/restore_types.go @@ -12,10 +12,10 @@ import ( type RestorePhase string const ( - RestorePhasePending RestorePhase = "Pending" - RestorePhaseRunning RestorePhase = "Running" - RestorePhaseSucceeded RestorePhase = "Succeeded" - RestorePhaseFailed RestorePhase = "Failed" + RestorePhasePending RestorePhase = "Pending" + RestorePhaseRunning RestorePhase = "Running" + RestorePhaseSucceeded RestorePhase = "Succeeded" + RestorePhaseFailed RestorePhase = "Failed" ) // RestoreSpec defines a single restore operation from a restic repository diff --git a/internal/backup/manifests.go b/internal/backup/manifests.go index c0a31f991..223aa3a4b 100644 --- a/internal/backup/manifests.go +++ b/internal/backup/manifests.go @@ -4,9 +4,9 @@ import ( "fmt" "strings" + snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" "github.com/topolvm/topolvm" topolvmv1 "github.com/topolvm/topolvm/api/v1" - snapshotv1 "github.com/kubernetes-csi/external-snapshotter/client/v8/apis/volumesnapshot/v1" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" diff --git a/internal/controller/backupconfig_controller_test.go b/internal/controller/backupconfig_controller_test.go index cc07b0630..a650fa012 100644 --- a/internal/controller/backupconfig_controller_test.go +++ b/internal/controller/backupconfig_controller_test.go @@ -33,7 +33,7 @@ func TestBuildPVCBackup_UsesGlobalDefaults(t *testing.T) { Spec: topolvmv1.BackupConfigSpec{ Schedule: "0 2 * * *", Retention: topolvmv1.RetentionSpec{ - KeepDaily: 7, + KeepDaily: 7, KeepWeekly: 4, }, KeepSnapshotAfterBackup: false, @@ -76,10 +76,10 @@ func TestBuildPVCBackup_AnnotationsOverrideDefaults(t *testing.T) { Namespace: "app", Name: "critical", Annotations: map[string]string{ - topolvm.BackupScheduleAnnotation: "*/15 * * * *", - topolvm.BackupRetentionDailyAnnotation: "30", + topolvm.BackupScheduleAnnotation: "*/15 * * * *", + topolvm.BackupRetentionDailyAnnotation: "30", topolvm.BackupRetentionMonthlyAnnotation: "12", - topolvm.BackupKeepSnapshotAnnotation: "true", + topolvm.BackupKeepSnapshotAnnotation: "true", }, }, } @@ -138,7 +138,7 @@ func TestPVCMatches_SkipAnnotation(t *testing.T) { func TestPVCMatches_SkipsNonTopoLVMStorageClass(t *testing.T) { sc := &storagev1.StorageClass{ - ObjectMeta: metav1.ObjectMeta{Name: "ebs"}, + ObjectMeta: metav1.ObjectMeta{Name: "ebs"}, Provisioner: "ebs.csi.aws.com", } c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(sc).Build() @@ -159,7 +159,7 @@ func TestPVCMatches_SkipsNonTopoLVMStorageClass(t *testing.T) { func TestPVCMatches_SelectorRespected(t *testing.T) { sc := &storagev1.StorageClass{ - ObjectMeta: metav1.ObjectMeta{Name: "topolvm"}, + ObjectMeta: metav1.ObjectMeta{Name: "topolvm"}, Provisioner: topolvm.GetPluginName(), } c := fake.NewClientBuilder().WithScheme(testScheme(t)).WithObjects(sc).Build() @@ -187,8 +187,8 @@ func TestPVCMatches_SelectorRespected(t *testing.T) { func TestPVCBackupSpecEqual(t *testing.T) { a := topolvmv1.PVCBackupSpec{ - PVCName: "data", - Schedule: "0 * * * *", + PVCName: "data", + Schedule: "0 * * * *", Retention: topolvmv1.RetentionSpec{KeepDaily: 7}, } b := a From 03007e5bbbd7dbc61b84f1f66e67de6760299479 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 12:32:59 -0700 Subject: [PATCH 6/8] chore: sync legacy restore_types.go with gofmt'd v1 copy `generate-legacy-api` in the Makefile copies api/v1/* over api/legacy/v1/ verbatim. The prior commit ran gofmt -s on api/v1/restore_types.go but I forgot to propagate that same formatting to the legacy mirror, so check-uncommitted saw a drift on CI. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- api/legacy/v1/restore_types.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/api/legacy/v1/restore_types.go b/api/legacy/v1/restore_types.go index f12e2e708..8b83692c9 100644 --- a/api/legacy/v1/restore_types.go +++ b/api/legacy/v1/restore_types.go @@ -12,10 +12,10 @@ import ( type RestorePhase string const ( - RestorePhasePending RestorePhase = "Pending" - RestorePhaseRunning RestorePhase = "Running" - RestorePhaseSucceeded RestorePhase = "Succeeded" - RestorePhaseFailed RestorePhase = "Failed" + RestorePhasePending RestorePhase = "Pending" + RestorePhaseRunning RestorePhase = "Running" + RestorePhaseSucceeded RestorePhase = "Succeeded" + RestorePhaseFailed RestorePhase = "Failed" ) // RestoreSpec defines a single restore operation from a restic repository From dc052e53d132c2181c32d8cfbfbe3171a8c8d201 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 13:01:52 -0700 Subject: [PATCH 7/8] chore: gofmt -s constants.go and test/e2e/backup_test.go The lint step in `make test` runs `gofmt -s -l .` across the entire repo. These two files had const-block alignment that diverged from gofmt's canonical form after my edits. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- constants.go | 18 +++++++++--------- test/e2e/backup_test.go | 20 ++++++++++---------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/constants.go b/constants.go index 24df60bc6..636c89026 100644 --- a/constants.go +++ b/constants.go @@ -142,9 +142,9 @@ const ( BackupConfigSingletonName = "default" // Annotation keys (on the source PVC) overriding BackupConfig defaults. - BackupEnabledAnnotation = pluginName + "/backup" - BackupScheduleAnnotation = pluginName + "/backup-schedule" - BackupKeepSnapshotAnnotation = pluginName + "/backup-keep-snapshot" + BackupEnabledAnnotation = pluginName + "/backup" + BackupScheduleAnnotation = pluginName + "/backup-schedule" + BackupKeepSnapshotAnnotation = pluginName + "/backup-keep-snapshot" BackupRetentionLastAnnotation = pluginName + "/backup-retention-last" BackupRetentionHourlyAnnotation = pluginName + "/backup-retention-hourly" BackupRetentionDailyAnnotation = pluginName + "/backup-retention-daily" @@ -153,8 +153,8 @@ const ( BackupRetentionYearlyAnnotation = pluginName + "/backup-retention-yearly" // BackupManagedByLabel marks CronJobs/Jobs/Snapshots created by the backup controller. - BackupManagedByLabel = pluginName + "/backup-managed-by" - BackupManagedByValue = "topolvm-backup" + BackupManagedByLabel = pluginName + "/backup-managed-by" + BackupManagedByValue = "topolvm-backup" BackupOwnerPVCNamespaceLabel = pluginName + "/backup-pvc-namespace" BackupOwnerPVCNameLabel = pluginName + "/backup-pvc-name" @@ -162,10 +162,10 @@ const ( BackupPVCFinalizer = pluginName + "/backup" // Resource name suffixes. - BackupCronJobSuffix = "-backup" - BackupJobSnapshotInfix = "-backup-snap-" - BackupJobTempPVCInfix = "-backup-src-" - RestoreJobSuffix = "-restore" + BackupCronJobSuffix = "-backup" + BackupJobSnapshotInfix = "-backup-snap-" + BackupJobTempPVCInfix = "-backup-src-" + RestoreJobSuffix = "-restore" // Secret key names. ResticPasswordSecretKey = "password" diff --git a/test/e2e/backup_test.go b/test/e2e/backup_test.go index 79a1064b3..41767a849 100644 --- a/test/e2e/backup_test.go +++ b/test/e2e/backup_test.go @@ -37,16 +37,16 @@ var ( ) const ( - backupPVCName = "backup-src" - backupWriterPodName = "backup-writer" - backupReaderPodName = "backup-reader" - backupRestoreName = "backup-restore" - backupRestorePVCName = "backup-restored" - backupS3CredsSecret = "s3-creds" - backupResticPwSecret = "restic-pw" - backupPVCSizeMi = 512 - backupFileContents = "hello-from-backup" - backupControllerNS = "topolvm-system" + backupPVCName = "backup-src" + backupWriterPodName = "backup-writer" + backupReaderPodName = "backup-reader" + backupRestoreName = "backup-restore" + backupRestorePVCName = "backup-restored" + backupS3CredsSecret = "s3-creds" + backupResticPwSecret = "restic-pw" + backupPVCSizeMi = 512 + backupFileContents = "hello-from-backup" + backupControllerNS = "topolvm-system" ) type backupEnv struct { From c274a53448159a4097b583b9465c5e82b1767b86 Mon Sep 17 00:00:00 2001 From: Dean Kamali Date: Mon, 20 Apr 2026 14:22:30 -0700 Subject: [PATCH 8/8] chore: address golangci-lint findings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Eight findings surfaced by CI's golangci-lint that local build didn't catch: - lll (max 120 chars): five long lines split across run.go, pkg/controller/backup_controllers.go, and test/e2e/backup_test.go. - unparam: removed unused `cfg backup.RuntimeConfig` parameter from PVCBackupReconciler.advanceMoving and .advanceCleanup — neither touched the config, only the CR status and child objects. - staticcheck QF1008: simplified pb.Status.LastSyncTime.Time.After(anchor) to pb.Status.LastSyncTime.After(anchor) — metav1.Time embeds time.Time so the selector is redundant. No behavior change. Co-Authored-By: Claude Opus 4.7 (1M context) Signed-off-by: Dean Kamali --- cmd/topolvm-controller/app/run.go | 6 +++++- internal/controller/pvcbackup_controller.go | 8 +++----- pkg/controller/backup_controllers.go | 9 +++++++-- test/e2e/backup_test.go | 11 +++++++++-- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/cmd/topolvm-controller/app/run.go b/cmd/topolvm-controller/app/run.go index 3bdebdf81..8fbd52f91 100644 --- a/cmd/topolvm-controller/app/run.go +++ b/cmd/topolvm-controller/app/run.go @@ -140,7 +140,11 @@ func subMain() error { setupLog.Error(nil, "backup controllers require --controller-namespace or POD_NAMESPACE to be set") return fmt.Errorf("controller namespace is required when --enable-backup is set") } - if err := controller.SetupBackupReconcilers(mgr, client, apiReader, ns, config.resticImage, config.backupMoverServiceAccount); err != nil { + err := controller.SetupBackupReconcilers( + mgr, client, apiReader, ns, + config.resticImage, config.backupMoverServiceAccount, + ) + if err != nil { setupLog.Error(err, "unable to create controllers", "controller", "Backup") return err } diff --git a/internal/controller/pvcbackup_controller.go b/internal/controller/pvcbackup_controller.go index b05f899bd..50962c6dc 100644 --- a/internal/controller/pvcbackup_controller.go +++ b/internal/controller/pvcbackup_controller.go @@ -189,9 +189,9 @@ func (r *PVCBackupReconciler) advance( case topolvmv1.PVCBackupPhaseCloning: return r.advanceCloning(ctx, pb, cfg) case topolvmv1.PVCBackupPhaseMoving: - return r.advanceMoving(ctx, pb, cfg) + return r.advanceMoving(ctx, pb) case topolvmv1.PVCBackupPhaseCleanup: - return r.advanceCleanup(ctx, pb, cfg) + return r.advanceCleanup(ctx, pb) } return ctrl.Result{}, nil } @@ -264,7 +264,6 @@ func (r *PVCBackupReconciler) advanceCloning( func (r *PVCBackupReconciler) advanceMoving( ctx context.Context, pb *topolvmv1.PVCBackup, - cfg backup.RuntimeConfig, ) (ctrl.Result, error) { job := &batchv1.Job{} err := r.client.Get(ctx, client.ObjectKey{Namespace: pb.Namespace, Name: pb.Status.CurrentMoverJobName}, job) @@ -301,7 +300,6 @@ func (r *PVCBackupReconciler) advanceMoving( func (r *PVCBackupReconciler) advanceCleanup( ctx context.Context, pb *topolvmv1.PVCBackup, - cfg backup.RuntimeConfig, ) (ctrl.Result, error) { // Always delete the temp PVC. Delete the mover Job so a subsequent run // can reuse the deterministic name for Cleanup diagnostics — the user @@ -412,7 +410,7 @@ func nextFireTime(pb *topolvmv1.PVCBackup, now time.Time) time.Time { return time.Time{} } anchor := pb.CreationTimestamp.Time - if pb.Status.LastSyncTime != nil && pb.Status.LastSyncTime.Time.After(anchor) { + if pb.Status.LastSyncTime != nil && pb.Status.LastSyncTime.After(anchor) { anchor = pb.Status.LastSyncTime.Time } next := schedule.Next(anchor) diff --git a/pkg/controller/backup_controllers.go b/pkg/controller/backup_controllers.go index d2ccc5ef3..ec6a88bcd 100644 --- a/pkg/controller/backup_controllers.go +++ b/pkg/controller/backup_controllers.go @@ -19,7 +19,9 @@ func SetupBackupReconcilers( apiReader client.Reader, controllerNamespace, resticImage, moverServiceAccountName string, ) error { - bc := internalController.NewBackupConfigReconciler(c, apiReader, controllerNamespace, resticImage, moverServiceAccountName) + bc := internalController.NewBackupConfigReconciler( + c, apiReader, controllerNamespace, resticImage, moverServiceAccountName, + ) if err := bc.SetupWithManager(mgr); err != nil { return err } @@ -29,6 +31,9 @@ func SetupBackupReconcilers( return err } - rs := internalController.NewRestoreReconciler(c, apiReader, bc.LoadSingleton, controllerNamespace, resticImage, moverServiceAccountName) + rs := internalController.NewRestoreReconciler( + c, apiReader, bc.LoadSingleton, + controllerNamespace, resticImage, moverServiceAccountName, + ) return rs.SetupWithManager(mgr) } diff --git a/test/e2e/backup_test.go b/test/e2e/backup_test.go index 41767a849..04386c774 100644 --- a/test/e2e/backup_test.go +++ b/test/e2e/backup_test.go @@ -92,7 +92,11 @@ func dumpBackupDiagnostics(ns string) { {"get", "events", "-n", ns, "--sort-by=.metadata.creationTimestamp"}, {"get", "backupconfig"}, {"get", "pods", "-n", backupControllerNS}, - {"logs", "-n", backupControllerNS, "-l", "app.kubernetes.io/component=controller", "-c", "topolvm-controller", "--tail=300"}, + { + "logs", "-n", backupControllerNS, + "-l", "app.kubernetes.io/component=controller", + "-c", "topolvm-controller", "--tail=300", + }, } { out, err := kubectl(cmd...) logf("\n--- kubectl %v ---\n", cmd) @@ -150,7 +154,10 @@ func testBackup() { It("backs up a PVC to restic and restores it into a fresh PVC", func() { By("creating S3 + restic password Secrets in the controller namespace") - s3Yaml := fmt.Sprintf(backupS3CredsSecretYAML, backupS3CredsSecret, backupControllerNS, bkpEnv.accessKey, bkpEnv.secretKey) + s3Yaml := fmt.Sprintf(backupS3CredsSecretYAML, + backupS3CredsSecret, backupControllerNS, + bkpEnv.accessKey, bkpEnv.secretKey, + ) _, err := kubectlWithInput([]byte(s3Yaml), "apply", "-f", "-") Expect(err).ShouldNot(HaveOccurred())