From 97f813237f9e94adc519acabf59370a64ad148cc Mon Sep 17 00:00:00 2001 From: Tal Efraim Date: Thu, 12 Nov 2026 16:07:46 +0200 Subject: [PATCH 1/3] feat: automated backups to S3 and restores --- AGENTS.md | 6 +- PROJECT | 24 + README.md | 2 + api/v1alpha1/clickhousebackup_types.go | 221 +++++ api/v1alpha1/clickhouserestore_types.go | 87 ++ .../clickhousescheduledbackup_types.go | 111 +++ api/v1alpha1/conditions.go | 27 + api/v1alpha1/events.go | 16 + api/v1alpha1/groupversion_info.go | 6 + api/v1alpha1/zz_generated.deepcopy.go | 579 +++++++++++- .../clickhouse.com_clickhousebackups.yaml | 344 +++++++ .../clickhouse.com_clickhouserestores.yaml | 340 +++++++ ...khouse.com_clickhousescheduledbackups.yaml | 361 ++++++++ config/crd/kustomization.yaml | 3 + ...khouse-operator.clusterserviceversion.yaml | 25 + config/rbac/clickhousebackup_admin_role.yaml | 28 + config/rbac/clickhousebackup_editor_role.yaml | 34 + config/rbac/clickhousebackup_viewer_role.yaml | 30 + config/rbac/clickhouserestore_admin_role.yaml | 28 + .../rbac/clickhouserestore_editor_role.yaml | 34 + .../rbac/clickhouserestore_viewer_role.yaml | 30 + .../clickhousescheduledbackup_admin_role.yaml | 28 + ...clickhousescheduledbackup_editor_role.yaml | 34 + ...clickhousescheduledbackup_viewer_role.yaml | 30 + config/rbac/kustomization.yaml | 9 + config/rbac/role.yaml | 9 + config/samples/kustomization.yaml | 3 + config/samples/v1alpha1_clickhousebackup.yaml | 17 + .../samples/v1alpha1_clickhouserestore.yaml | 9 + .../v1alpha1_clickhousescheduledbackup.yaml | 22 + .../crd/clickhousebackups.clickhouse.com.yaml | 348 +++++++ .../clickhouserestores.clickhouse.com.yaml | 344 +++++++ ...khousescheduledbackups.clickhouse.com.yaml | 365 ++++++++ .../rbac/clickhousebackup-admin-role.yaml | 32 + .../rbac/clickhousebackup-editor-role.yaml | 38 + .../rbac/clickhousebackup-viewer-role.yaml | 34 + .../rbac/clickhouserestore-admin-role.yaml | 32 + .../rbac/clickhouserestore-editor-role.yaml | 38 + .../rbac/clickhouserestore-viewer-role.yaml | 34 + .../clickhousescheduledbackup-admin-role.yaml | 32 + ...clickhousescheduledbackup-editor-role.yaml | 38 + ...clickhousescheduledbackup-viewer-role.yaml | 34 + dist/chart/templates/rbac/manager-role.yaml | 9 + docs/README.md | 1 + docs/guides/backup.mdx | 239 +++++ docs/guides/kubernetes-events.mdx | 16 + docs/navigation.json | 3 +- docs/overview.mdx | 2 + docs/reference/api-reference.mdx | 341 +++++++ examples/scheduled_backup_s3.yaml | 43 + go.mod | 1 + go.sum | 2 + .../controller/clickhouse/backup_commands.go | 275 ++++++ .../clickhouse/backup_commands_test.go | 176 ++++ .../clickhouse/backup_controller.go | 657 +++++++++++++ .../clickhouse/backup_controller_test.go | 871 ++++++++++++++++++ .../controller/clickhouse/commands_test.go | 150 +++ internal/controller/clickhouse/controller.go | 2 +- .../clickhouse/scheduledbackup_controller.go | 401 ++++++++ internal/controllerutil/labels.go | 1 + test/e2e/backup_e2e_test.go | 229 +++++ 61 files changed, 7258 insertions(+), 27 deletions(-) create mode 100644 api/v1alpha1/clickhousebackup_types.go create mode 100644 api/v1alpha1/clickhouserestore_types.go create mode 100644 api/v1alpha1/clickhousescheduledbackup_types.go create mode 100644 config/crd/bases/clickhouse.com_clickhousebackups.yaml create mode 100644 config/crd/bases/clickhouse.com_clickhouserestores.yaml create mode 100644 config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml create mode 100644 config/rbac/clickhousebackup_admin_role.yaml create mode 100644 config/rbac/clickhousebackup_editor_role.yaml create mode 100644 config/rbac/clickhousebackup_viewer_role.yaml create mode 100644 config/rbac/clickhouserestore_admin_role.yaml create mode 100644 config/rbac/clickhouserestore_editor_role.yaml create mode 100644 config/rbac/clickhouserestore_viewer_role.yaml create mode 100644 config/rbac/clickhousescheduledbackup_admin_role.yaml create mode 100644 config/rbac/clickhousescheduledbackup_editor_role.yaml create mode 100644 config/rbac/clickhousescheduledbackup_viewer_role.yaml create mode 100644 config/samples/v1alpha1_clickhousebackup.yaml create mode 100644 config/samples/v1alpha1_clickhouserestore.yaml create mode 100644 config/samples/v1alpha1_clickhousescheduledbackup.yaml create mode 100644 dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml create mode 100644 dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml create mode 100644 dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml create mode 100644 dist/chart/templates/rbac/clickhousebackup-admin-role.yaml create mode 100644 dist/chart/templates/rbac/clickhousebackup-editor-role.yaml create mode 100644 dist/chart/templates/rbac/clickhousebackup-viewer-role.yaml create mode 100644 dist/chart/templates/rbac/clickhouserestore-admin-role.yaml create mode 100644 dist/chart/templates/rbac/clickhouserestore-editor-role.yaml create mode 100644 dist/chart/templates/rbac/clickhouserestore-viewer-role.yaml create mode 100644 dist/chart/templates/rbac/clickhousescheduledbackup-admin-role.yaml create mode 100644 dist/chart/templates/rbac/clickhousescheduledbackup-editor-role.yaml create mode 100644 dist/chart/templates/rbac/clickhousescheduledbackup-viewer-role.yaml create mode 100644 docs/guides/backup.mdx create mode 100644 examples/scheduled_backup_s3.yaml create mode 100644 internal/controller/clickhouse/backup_commands.go create mode 100644 internal/controller/clickhouse/backup_commands_test.go create mode 100644 internal/controller/clickhouse/backup_controller.go create mode 100644 internal/controller/clickhouse/backup_controller_test.go create mode 100644 internal/controller/clickhouse/scheduledbackup_controller.go create mode 100644 test/e2e/backup_e2e_test.go diff --git a/AGENTS.md b/AGENTS.md index 276a2f5ac..b8ebb837a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ This file provides guidance to coding agents when working with code in this repo ## Project Overview -Kubernetes operator for managing ClickHouse database clusters and ClickHouse Keeper clusters. Built with `Kubebuilder` and `controller-runtime`. Manages two CRDs: `ClickHouseCluster` and `KeeperCluster` (both `v1alpha1` in the `clickhouse.com` API group). +Kubernetes operator for managing ClickHouse database clusters and ClickHouse Keeper clusters. Built with `Kubebuilder` and `controller-runtime`. Manages two CRDs: `ClickHouseCluster` and `KeeperCluster` (both `v1alpha1` in the `clickhouse.com` API group). Backups are driven by three more CRDs in the same group: `ClickHouseBackup`, `ClickHouseScheduledBackup` and `ClickHouseRestore`. ## Common Commands @@ -97,6 +97,7 @@ make check-crd-compat # Check CRD backward compatibility against origin/ma ### CRD API Types (`api/v1alpha1/`) - `clickhousecluster_types.go` — ClickHouseCluster spec: shards, replicas per shard, keeper reference, storage, settings - `keepercluster_types.go` — KeeperCluster spec: replicas (odd, 0-15), storage, settings +- `clickhousebackup_types.go`, `clickhousescheduledbackup_types.go`, `clickhouserestore_types.go` — Backup resources: one-shot backup, schedule, one-shot restore - `common.go` — Shared types: ContainerImage, LoggerConfig, PodDisruptionBudgetSpec, ClickHouseSettings, KeeperSettings - `defaults.go` — Default value logic applied by webhooks - `conditions.go` — Status condition helpers @@ -113,6 +114,9 @@ Both controllers follow the same pattern, extending a shared base: - `clickhouse/templates.go`, `keeper/templates.go` — Generate Kubernetes resource specs - `clickhouse/config.go` — Generate ClickHouse YAML configuration - `clickhouse/commands.go`, `keeper/commands.go` — Interfaces to communicate to running containers +- `clickhouse/backup_controller.go` — ClickHouseBackup and ClickHouseRestore reconcilers: submit an asynchronous `BACKUP`/`RESTORE ... ON CLUSTER` statement to one replica and poll `system.backups` +- `clickhouse/backup_commands.go` — Statement rendering and the replica commands used by backups +- `clickhouse/scheduledbackup_controller.go` — ClickHouseScheduledBackup reconciler: creates ClickHouseBackup resources on a cron schedule and prunes old ones - `overrides.go` — Pod/container spec overrides helpers via strategic merge patch - `versionprobe.go` — Creates Jobs to detect actual ClickHouse/Keeper versions - `upgradecheck.go` — Checks for newer version availability diff --git a/PROJECT b/PROJECT index 455007740..4930a32dc 100644 --- a/PROJECT +++ b/PROJECT @@ -38,4 +38,28 @@ resources: defaulting: true validation: true webhookVersion: v1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: clickhouse.com + kind: ClickHouseBackup + path: github.com/ClickHouse/clickhouse-operator/api/v1alpha1 + version: v1alpha1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: clickhouse.com + kind: ClickHouseRestore + path: github.com/ClickHouse/clickhouse-operator/api/v1alpha1 + version: v1alpha1 +- api: + crdVersion: v1 + namespaced: true + controller: true + domain: clickhouse.com + kind: ClickHouseScheduledBackup + path: github.com/ClickHouse/clickhouse-operator/api/v1alpha1 + version: v1alpha1 version: "3" diff --git a/README.md b/README.md index 2cd395edb..c10057dc0 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,7 @@ The Operator handles the full lifecycle of ClickHouse clusters, including scalin - **High Availability**: Fault-tolerant installations for ClickHouse and Keeper clusters - **Security**: Built-in security features TLS/SSL support for secure cluster communication - **Monitoring**: Prometheus metrics integration for observability +- **Backup and Restore**: Scheduled full and incremental backups to S3 and restores using native ClickHouse backups ## Getting Started @@ -105,6 +106,7 @@ The `examples/` directory contains various ClickHouse cluster configurations: - **aws_eks_gp3.yaml**: Configuration for AWS EKS with gp3 storage - **gcp_gke_ssd.yaml**: Configuration for GCP GKE with SSD storage - **custom_configuration.yaml**: ClickHouse cluster with configuration overrides +- **scheduled_backup_s3.yaml**: Nightly full and incremental backups of a cluster to S3 - **prometheus_secure_metrics_scraper.yaml**: Configuration for secure operator metrics scraping. Requires Prometheus operator and enabled secure metrics endpoint To deploy any example: diff --git a/api/v1alpha1/clickhousebackup_types.go b/api/v1alpha1/clickhousebackup_types.go new file mode 100644 index 000000000..8d05ca267 --- /dev/null +++ b/api/v1alpha1/clickhousebackup_types.go @@ -0,0 +1,221 @@ +package v1alpha1 + +import ( + "strings" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// BackupStorage selects the storage that holds backups. +// +kubebuilder:validation:XValidation:rule="has(self.s3)",message="s3 storage must be set" +type BackupStorage struct { + // S3 stores backups in an S3-compatible object storage. + // +optional + S3 *S3BackupStorage `json:"s3,omitempty"` +} + +// S3BackupStorage describes an S3-compatible backup storage. +type S3BackupStorage struct { + // Endpoint is the URL of the bucket and the prefix that holds backups, for example + // `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + // Every backup is written to its own directory under this URL. + // +kubebuilder:validation:Pattern=`^https?://[^\s'\\]+$` + // +kubebuilder:validation:MaxLength=2048 + Endpoint string `json:"endpoint"` + + // Credentials used to access the storage. + // When omitted, ClickHouse uses the credentials available to the server itself, + // such as an IAM role attached to the Pod or the node. + // +optional + Credentials *S3Credentials `json:"credentials,omitempty"` +} + +// S3Credentials references the access key used to access an S3-compatible storage. +type S3Credentials struct { + // AccessKeyID selects the Secret key that holds the access key ID. + AccessKeyID SecretKeySelector `json:"accessKeyID"` + // SecretAccessKey selects the Secret key that holds the secret access key. + SecretAccessKey SecretKeySelector `json:"secretAccessKey"` +} + +// Location returns the URL of the backup with the given name in the storage. +func (s *S3BackupStorage) Location(name string) string { + return strings.TrimRight(s.Endpoint, "/") + "/" + name +} + +// BackupScope limits a backup or a restore to a subset of the cluster data. +// When no databases and no tables are listed, everything except the `system` database is included. +type BackupScope struct { + // Databases lists the databases to include. + // +optional + // +listType=set + // +kubebuilder:validation:MaxItems=256 + // +kubebuilder:validation:items:MinLength=1 + Databases []string `json:"databases,omitempty"` + + // Tables lists the individual tables to include. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=1024 + Tables []BackupTable `json:"tables,omitempty"` +} + +// BackupTable identifies a table. +type BackupTable struct { + // Database is the name of the database that holds the table. + // +kubebuilder:validation:MinLength=1 + Database string `json:"database"` + // Table is the name of the table. + // +kubebuilder:validation:MinLength=1 + Table string `json:"table"` +} + +// BackupPhase is the lifecycle phase of a backup or a restore. +// +kubebuilder:validation:Enum=Pending;Running;Completed;Failed +type BackupPhase string + +const ( + // BackupPhasePending means that the operation is not started yet. + BackupPhasePending BackupPhase = "Pending" + // BackupPhaseRunning means that ClickHouse is executing the operation. + BackupPhaseRunning BackupPhase = "Running" + // BackupPhaseCompleted means that the operation finished successfully. + BackupPhaseCompleted BackupPhase = "Completed" + // BackupPhaseFailed means that the operation failed. Failed operations are not retried. + BackupPhaseFailed BackupPhase = "Failed" +) + +// Finished returns true if the phase is terminal. +func (p BackupPhase) Finished() bool { + return p == BackupPhaseCompleted || p == BackupPhaseFailed +} + +// BackupReplica identifies the cluster replica that executes a backup or a restore. +type BackupReplica struct { + // ShardID is the shard of the replica. + ShardID int32 `json:"shardID"` + // Index is the index of the replica within the shard. + Index int32 `json:"index"` +} + +// BackupOperationStatus is the observed state shared by backups and restores. +type BackupOperationStatus struct { + // +listType=map + // +listMapKey=type + // +patchStrategy=merge + // +patchMergeKey=type + // +optional + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // Phase is the lifecycle phase of the operation. + // +optional + Phase BackupPhase `json:"phase,omitempty"` + + // ID identifies the operation in the `system.backups` table of the replica that executes it. + // +optional + ID string `json:"id,omitempty"` + + // Replica is the cluster replica that executes the operation. + // +optional + Replica *BackupReplica `json:"replica,omitempty"` + + // Location is the URL of the backup in the storage. + // +optional + Location string `json:"location,omitempty"` + + // StartTime is the time the operation was submitted to ClickHouse. + // +optional + StartTime *metav1.Time `json:"startTime,omitempty"` + + // CompletionTime is the time the operation finished. + // +optional + CompletionTime *metav1.Time `json:"completionTime,omitempty"` +} + +// ClickHouseBackupSpec defines the desired state of ClickHouseBackup. +// +kubebuilder:validation:XValidation:rule="!has(self.settings) || self.settings.all(k, !(k in ['id', 'async', 'base_backup']))",message="settings id, async and base_backup are managed by the operator" +type ClickHouseBackupSpec struct { + // ClusterRef references the ClickHouseCluster to back up. The cluster must be in the namespace of the backup. + ClusterRef corev1.LocalObjectReference `json:"clusterRef"` + + // Storage is the storage the backup is written to. + // The backup is stored in the directory named after this resource. + Storage BackupStorage `json:"storage"` + + // Scope limits the backup to the listed databases and tables. + // When omitted, everything except the `system` database is backed up. + // +optional + Scope *BackupScope `json:"scope,omitempty"` + + // BaseBackupRef makes the backup incremental: only the data that is missing from the referenced + // ClickHouseBackup is stored. The base backup must be completed and must stay in the storage + // for as long as this backup is needed. + // +optional + BaseBackupRef *corev1.LocalObjectReference `json:"baseBackupRef,omitempty"` + + // Settings are additional settings passed to the BACKUP statement. + // +optional + // +kubebuilder:validation:MaxProperties=64 + // +kubebuilder:validation:XValidation:rule="self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$'))",message="setting names must be valid identifiers" + Settings map[string]string `json:"settings,omitempty"` +} + +// ClickHouseBackupStatus defines the observed state of ClickHouseBackup. +type ClickHouseBackupStatus struct { + BackupOperationStatus `json:",inline"` + + // BaseLocation is the URL of the base backup of an incremental backup. + // +optional + BaseLocation string `json:"baseLocation,omitempty"` + + // NumFiles is the number of files stored in the backup. + // +optional + NumFiles int64 `json:"numFiles,omitempty"` + + // TotalSize is the size in bytes of the data covered by the backup, including the data stored in base backups. + // +optional + TotalSize int64 `json:"totalSize,omitempty"` + + // CompressedSize is the size in bytes the backup takes in the storage. + // +optional + CompressedSize int64 `json:"compressedSize,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// ClickHouseBackup is the Schema for the `clickhousebackups` API. +// It runs a single backup of a ClickHouseCluster using the ClickHouse BACKUP statement. +// +kubebuilder:resource:shortName=chbackup +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterRef.name" +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase" +// +kubebuilder:printcolumn:name="Base",type="string",JSONPath=".spec.baseBackupRef.name" +// +kubebuilder:printcolumn:name="Size",type="integer",JSONPath=".status.compressedSize" +// +kubebuilder:printcolumn:name="Completed",type="date",JSONPath=".status.completionTime" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" +// +operator-sdk:csv:customresourcedefinitions:displayName="ClickHouse Backup" +// +kubebuilder:validation:XValidation:rule="has(self.spec)",message="spec is required" +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.spec) || self.spec == oldSelf.spec",message="spec is immutable" +type ClickHouseBackup struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ClickHouseBackupSpec `json:"spec,omitempty"` + Status ClickHouseBackupStatus `json:"status,omitempty"` +} + +// IsIncremental returns true if the backup stores only the difference from a base backup. +func (v *ClickHouseBackup) IsIncremental() bool { + return v.Spec.BaseBackupRef != nil +} + +// +kubebuilder:object:root=true + +// ClickHouseBackupList contains a list of ClickHouseBackup. +type ClickHouseBackupList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + + Items []ClickHouseBackup `json:"items"` +} diff --git a/api/v1alpha1/clickhouserestore_types.go b/api/v1alpha1/clickhouserestore_types.go new file mode 100644 index 000000000..2efbf8f54 --- /dev/null +++ b/api/v1alpha1/clickhouserestore_types.go @@ -0,0 +1,87 @@ +package v1alpha1 + +import ( + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// RestoreSource locates a backup that is not described by a ClickHouseBackup resource, +// for example a backup taken in another Kubernetes cluster. +type RestoreSource struct { + // Storage is the storage that holds the backup. + Storage BackupStorage `json:"storage"` + + // Name is the name of the backup directory in the storage. + // It is the name of the ClickHouseBackup resource that created the backup. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + // +kubebuilder:validation:Pattern=`^[^\s'\\]+$` + Name string `json:"name"` +} + +// ClickHouseRestoreSpec defines the desired state of ClickHouseRestore. +// +kubebuilder:validation:XValidation:rule="has(self.backupRef) != has(self.source)",message="exactly one of backupRef or source must be set" +// +kubebuilder:validation:XValidation:rule="!has(self.settings) || self.settings.all(k, !(k in ['id', 'async', 'base_backup']))",message="settings id, async and base_backup are managed by the operator" +type ClickHouseRestoreSpec struct { + // ClusterRef references the ClickHouseCluster to restore into. The cluster must be in the namespace of the restore. + ClusterRef corev1.LocalObjectReference `json:"clusterRef"` + + // BackupRef references the completed ClickHouseBackup to restore from. + // Mutually exclusive with `source`, exactly one of them must be set. + // +optional + BackupRef *corev1.LocalObjectReference `json:"backupRef,omitempty"` + + // Source locates the backup to restore from directly in the storage. + // Mutually exclusive with `backupRef`, exactly one of them must be set. + // +optional + Source *RestoreSource `json:"source,omitempty"` + + // Scope limits the restore to the listed databases and tables. + // When omitted, everything except the `system` database is restored. + // +optional + Scope *BackupScope `json:"scope,omitempty"` + + // Settings are additional settings passed to the RESTORE statement, + // for example `allow_non_empty_tables` or `structure_only`. + // +optional + // +kubebuilder:validation:MaxProperties=64 + // +kubebuilder:validation:XValidation:rule="self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$'))",message="setting names must be valid identifiers" + Settings map[string]string `json:"settings,omitempty"` +} + +// ClickHouseRestoreStatus defines the observed state of ClickHouseRestore. +type ClickHouseRestoreStatus struct { + BackupOperationStatus `json:",inline"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// ClickHouseRestore is the Schema for the `clickhouserestores` API. +// It restores a backup into a ClickHouseCluster once using the ClickHouse RESTORE statement. +// +kubebuilder:resource:shortName=chrestore +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.clusterRef.name" +// +kubebuilder:printcolumn:name="Backup",type="string",JSONPath=".spec.backupRef.name" +// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase" +// +kubebuilder:printcolumn:name="Completed",type="date",JSONPath=".status.completionTime" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" +// +operator-sdk:csv:customresourcedefinitions:displayName="ClickHouse Restore" +// +kubebuilder:validation:XValidation:rule="has(self.spec)",message="spec is required" +// +kubebuilder:validation:XValidation:rule="!has(oldSelf.spec) || self.spec == oldSelf.spec",message="spec is immutable" +type ClickHouseRestore struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ClickHouseRestoreSpec `json:"spec,omitempty"` + Status ClickHouseRestoreStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// ClickHouseRestoreList contains a list of ClickHouseRestore. +type ClickHouseRestoreList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + + Items []ClickHouseRestore `json:"items"` +} diff --git a/api/v1alpha1/clickhousescheduledbackup_types.go b/api/v1alpha1/clickhousescheduledbackup_types.go new file mode 100644 index 000000000..95ca6c5b6 --- /dev/null +++ b/api/v1alpha1/clickhousescheduledbackup_types.go @@ -0,0 +1,111 @@ +package v1alpha1 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// ClickHouseBackupTemplate describes the ClickHouseBackup resources created by a ClickHouseScheduledBackup. +type ClickHouseBackupTemplate struct { + // Spec of the created backups. `baseBackupRef` is managed by the schedule and must not be set. + // +kubebuilder:validation:XValidation:rule="!has(self.baseBackupRef)",message="baseBackupRef is managed by the schedule" + Spec ClickHouseBackupSpec `json:"spec"` +} + +// ClickHouseScheduledBackupSpec defines the desired state of ClickHouseScheduledBackup. +type ClickHouseScheduledBackupSpec struct { + // Schedule in the cron format, see https://en.wikipedia.org/wiki/Cron. + // +kubebuilder:validation:MinLength=1 + Schedule string `json:"schedule"` + + // TimeZone is the IANA time zone name the schedule is evaluated in. Defaults to UTC. + // +optional + TimeZone *string `json:"timeZone,omitempty"` + + // Suspend stops the creation of new backups. Backups that are already running are not affected. + // +optional + Suspend *bool `json:"suspend,omitempty"` + + // FullBackupInterval makes the schedule take incremental backups: every full backup is followed by + // `fullBackupInterval - 1` incremental backups based on it. + // When unset or 1, every backup is a full backup. + // +optional + // +kubebuilder:validation:Minimum=1 + FullBackupInterval *int32 `json:"fullBackupInterval,omitempty"` + + // SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. + // The most recent full backup and the base backups of the kept incremental backups are always kept. + // Deleting a ClickHouseBackup resource does not delete the backup data from the storage. + // +optional + // +kubebuilder:default:=10 + // +kubebuilder:validation:Minimum=1 + SuccessfulBackupsHistoryLimit *int32 `json:"successfulBackupsHistoryLimit,omitempty"` + + // FailedBackupsHistoryLimit is the number of failed ClickHouseBackup resources to keep. + // +optional + // +kubebuilder:default:=3 + // +kubebuilder:validation:Minimum=0 + FailedBackupsHistoryLimit *int32 `json:"failedBackupsHistoryLimit,omitempty"` + + // Template describes the backups created by the schedule. + Template ClickHouseBackupTemplate `json:"template"` +} + +// ClickHouseScheduledBackupStatus defines the observed state of ClickHouseScheduledBackup. +type ClickHouseScheduledBackupStatus struct { + // +listType=map + // +listMapKey=type + // +patchStrategy=merge + // +patchMergeKey=type + // +optional + Conditions []metav1.Condition `json:"conditions,omitempty"` + + // LastScheduleTime is the schedule time of the most recent backup created by the schedule. + // +optional + LastScheduleTime *metav1.Time `json:"lastScheduleTime,omitempty"` + + // LastBackupName is the name of the most recent ClickHouseBackup created by the schedule. + // +optional + LastBackupName string `json:"lastBackupName,omitempty"` + + // LastSuccessfulTime is the completion time of the most recent successful backup. + // +optional + LastSuccessfulTime *metav1.Time `json:"lastSuccessfulTime,omitempty"` + + // LastSuccessfulBackupName is the name of the most recent successful ClickHouseBackup. + // +optional + LastSuccessfulBackupName string `json:"lastSuccessfulBackupName,omitempty"` +} + +// +kubebuilder:object:root=true +// +kubebuilder:subresource:status + +// ClickHouseScheduledBackup is the Schema for the `clickhousescheduledbackups` API. +// It creates ClickHouseBackup resources on a schedule. +// +kubebuilder:resource:shortName=chscheduledbackup +// +kubebuilder:printcolumn:name="Cluster",type="string",JSONPath=".spec.template.spec.clusterRef.name" +// +kubebuilder:printcolumn:name="Schedule",type="string",JSONPath=".spec.schedule" +// +kubebuilder:printcolumn:name="Suspend",type="boolean",JSONPath=".spec.suspend" +// +kubebuilder:printcolumn:name="LastSchedule",type="date",JSONPath=".status.lastScheduleTime" +// +kubebuilder:printcolumn:name="LastSuccessful",type="date",JSONPath=".status.lastSuccessfulTime" +// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp" +// +operator-sdk:csv:customresourcedefinitions:displayName="ClickHouse Scheduled Backup" +// +operator-sdk:csv:customresourcedefinitions:resources={{ClickHouseBackup,v1alpha1}} +// +kubebuilder:validation:XValidation:rule="has(self.spec)",message="spec is required" +// +kubebuilder:validation:XValidation:rule="self.metadata.name.size() <= 48",message="name must be no more than 48 characters" +type ClickHouseScheduledBackup struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata,omitempty"` + + Spec ClickHouseScheduledBackupSpec `json:"spec,omitempty"` + Status ClickHouseScheduledBackupStatus `json:"status,omitempty"` +} + +// +kubebuilder:object:root=true + +// ClickHouseScheduledBackupList contains a list of ClickHouseScheduledBackup. +type ClickHouseScheduledBackupList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata,omitempty"` + + Items []ClickHouseScheduledBackup `json:"items"` +} diff --git a/api/v1alpha1/conditions.go b/api/v1alpha1/conditions.go index 51fe3e2fd..a49c5b81a 100644 --- a/api/v1alpha1/conditions.go +++ b/api/v1alpha1/conditions.go @@ -106,6 +106,33 @@ const ( KeeperConditionReasonReadyToScale ConditionReason = "ReadyToScale" ) +// ClickHouseBackup and ClickHouseRestore specific condition types and reasons. +const ( + // BackupConditionTypeCompleted indicates that the backup or the restore finished successfully. + BackupConditionTypeCompleted ConditionType = "Completed" + + BackupConditionReasonSucceeded ConditionReason = "Succeeded" + BackupConditionReasonInProgress ConditionReason = "InProgress" + BackupConditionReasonFailed ConditionReason = "Failed" + BackupConditionReasonStateLost ConditionReason = "StateLost" + BackupConditionReasonClusterNotFound ConditionReason = "ClusterNotFound" + BackupConditionReasonClusterNotReady ConditionReason = "ClusterNotReady" + BackupConditionReasonCredentialsInvalid ConditionReason = "CredentialsInvalid" + BackupConditionReasonBackupNotFound ConditionReason = "BackupNotFound" + BackupConditionReasonBackupNotCompleted ConditionReason = "BackupNotCompleted" + BackupConditionReasonBackupFailed ConditionReason = "BackupFailed" +) + +// ClickHouseScheduledBackup specific condition types and reasons. +const ( + // ScheduledBackupConditionTypeScheduled indicates that the schedule is valid and creates backups. + ScheduledBackupConditionTypeScheduled ConditionType = "Scheduled" + + ScheduledBackupConditionReasonActive ConditionReason = "Active" + ScheduledBackupConditionReasonSuspended ConditionReason = "Suspended" + ScheduledBackupConditionReasonInvalidSchedule ConditionReason = "InvalidSchedule" +) + // Special condition added to the ClickHouseCluster pods to indicate that replica is initialized by the operator. const ( ReplicaInitializedCondition corev1.PodConditionType = "clickhouse.com/ReplicaInitialized" diff --git a/api/v1alpha1/events.go b/api/v1alpha1/events.go index 959b2e0f7..013ca183b 100644 --- a/api/v1alpha1/events.go +++ b/api/v1alpha1/events.go @@ -43,6 +43,19 @@ const ( EventReasonClickHouseWarning EventReason = "ClickHouseWarning" ) +// Event reasons for backups and restores. +const ( + EventReasonBackupStarted EventReason = "BackupStarted" + EventReasonBackupCompleted EventReason = "BackupCompleted" + EventReasonBackupFailed EventReason = "BackupFailed" + EventReasonRestoreStarted EventReason = "RestoreStarted" + EventReasonRestoreCompleted EventReason = "RestoreCompleted" + EventReasonRestoreFailed EventReason = "RestoreFailed" + EventReasonBackupScheduled EventReason = "BackupScheduled" + EventReasonBackupSkipped EventReason = "BackupSkipped" + EventReasonInvalidSchedule EventReason = "InvalidSchedule" +) + // EventAction represents the action associated with an event. type EventAction = string @@ -52,4 +65,7 @@ const ( EventActionBecameReady EventAction = "BecameReady" EventActionBecameNotReady EventAction = "BecameNotReady" EventActionVersionCheck EventAction = "VersionCheck" + EventActionBackup EventAction = "Backup" + EventActionRestore EventAction = "Restore" + EventActionScheduling EventAction = "Scheduling" ) diff --git a/api/v1alpha1/groupversion_info.go b/api/v1alpha1/groupversion_info.go index 031005250..7fc1d12b0 100644 --- a/api/v1alpha1/groupversion_info.go +++ b/api/v1alpha1/groupversion_info.go @@ -26,6 +26,12 @@ func addKnownTypes(scheme *runtime.Scheme) error { &KeeperClusterList{}, &ClickHouseCluster{}, &ClickHouseClusterList{}, + &ClickHouseBackup{}, + &ClickHouseBackupList{}, + &ClickHouseRestore{}, + &ClickHouseRestoreList{}, + &ClickHouseScheduledBackup{}, + &ClickHouseScheduledBackupList{}, ) metav1.AddToGroupVersion(scheme, GroupVersion) diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index c4891e2ce..fed031dae 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -21,9 +21,9 @@ limitations under the License. package v1alpha1 import ( - "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" policyv1 "k8s.io/api/policy/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/intstr" ) @@ -43,6 +43,116 @@ func (in *AdditionalPort) DeepCopy() *AdditionalPort { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupOperationStatus) DeepCopyInto(out *BackupOperationStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Replica != nil { + in, out := &in.Replica, &out.Replica + *out = new(BackupReplica) + **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() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupOperationStatus. +func (in *BackupOperationStatus) DeepCopy() *BackupOperationStatus { + if in == nil { + return nil + } + out := new(BackupOperationStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupReplica) DeepCopyInto(out *BackupReplica) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupReplica. +func (in *BackupReplica) DeepCopy() *BackupReplica { + if in == nil { + return nil + } + out := new(BackupReplica) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupScope) DeepCopyInto(out *BackupScope) { + *out = *in + if in.Databases != nil { + in, out := &in.Databases, &out.Databases + *out = make([]string, len(*in)) + copy(*out, *in) + } + if in.Tables != nil { + in, out := &in.Tables, &out.Tables + *out = make([]BackupTable, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupScope. +func (in *BackupScope) DeepCopy() *BackupScope { + if in == nil { + return nil + } + out := new(BackupScope) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupStorage) DeepCopyInto(out *BackupStorage) { + *out = *in + if in.S3 != nil { + in, out := &in.S3, &out.S3 + *out = new(S3BackupStorage) + (*in).DeepCopyInto(*out) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupStorage. +func (in *BackupStorage) DeepCopy() *BackupStorage { + if in == nil { + return nil + } + out := new(BackupStorage) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *BackupTable) DeepCopyInto(out *BackupTable) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BackupTable. +func (in *BackupTable) DeepCopy() *BackupTable { + if in == nil { + return nil + } + out := new(BackupTable) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CABundleSelector) DeepCopyInto(out *CABundleSelector) { *out = *in @@ -58,6 +168,131 @@ func (in *CABundleSelector) DeepCopy() *CABundleSelector { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseBackup) DeepCopyInto(out *ClickHouseBackup) { + *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 ClickHouseBackup. +func (in *ClickHouseBackup) DeepCopy() *ClickHouseBackup { + if in == nil { + return nil + } + out := new(ClickHouseBackup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseBackup) 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 *ClickHouseBackupList) DeepCopyInto(out *ClickHouseBackupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClickHouseBackup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseBackupList. +func (in *ClickHouseBackupList) DeepCopy() *ClickHouseBackupList { + if in == nil { + return nil + } + out := new(ClickHouseBackupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseBackupList) 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 *ClickHouseBackupSpec) DeepCopyInto(out *ClickHouseBackupSpec) { + *out = *in + out.ClusterRef = in.ClusterRef + in.Storage.DeepCopyInto(&out.Storage) + if in.Scope != nil { + in, out := &in.Scope, &out.Scope + *out = new(BackupScope) + (*in).DeepCopyInto(*out) + } + if in.BaseBackupRef != nil { + in, out := &in.BaseBackupRef, &out.BaseBackupRef + *out = new(corev1.LocalObjectReference) + **out = **in + } + if in.Settings != nil { + in, out := &in.Settings, &out.Settings + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseBackupSpec. +func (in *ClickHouseBackupSpec) DeepCopy() *ClickHouseBackupSpec { + if in == nil { + return nil + } + out := new(ClickHouseBackupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseBackupStatus) DeepCopyInto(out *ClickHouseBackupStatus) { + *out = *in + in.BackupOperationStatus.DeepCopyInto(&out.BackupOperationStatus) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseBackupStatus. +func (in *ClickHouseBackupStatus) DeepCopy() *ClickHouseBackupStatus { + if in == nil { + return nil + } + out := new(ClickHouseBackupStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseBackupTemplate) DeepCopyInto(out *ClickHouseBackupTemplate) { + *out = *in + in.Spec.DeepCopyInto(&out.Spec) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseBackupTemplate. +func (in *ClickHouseBackupTemplate) DeepCopy() *ClickHouseBackupTemplate { + if in == nil { + return nil + } + out := new(ClickHouseBackupTemplate) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClickHouseCluster) DeepCopyInto(out *ClickHouseCluster) { *out = *in @@ -144,7 +379,7 @@ func (in *ClickHouseClusterSpec) DeepCopyInto(out *ClickHouseClusterSpec) { in.ContainerTemplate.DeepCopyInto(&out.ContainerTemplate) if in.DataVolumeClaimSpec != nil { in, out := &in.DataVolumeClaimSpec, &out.DataVolumeClaimSpec - *out = new(v1.PersistentVolumeClaimSpec) + *out = new(corev1.PersistentVolumeClaimSpec) (*in).DeepCopyInto(*out) } if in.AdditionalVolumeClaimTemplates != nil { @@ -211,7 +446,7 @@ func (in *ClickHouseClusterStatus) DeepCopyInto(out *ClickHouseClusterStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -243,6 +478,249 @@ func (in *ClickHouseNetworkPolicySpec) DeepCopy() *ClickHouseNetworkPolicySpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseRestore) DeepCopyInto(out *ClickHouseRestore) { + *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 ClickHouseRestore. +func (in *ClickHouseRestore) DeepCopy() *ClickHouseRestore { + if in == nil { + return nil + } + out := new(ClickHouseRestore) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseRestore) 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 *ClickHouseRestoreList) DeepCopyInto(out *ClickHouseRestoreList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClickHouseRestore, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseRestoreList. +func (in *ClickHouseRestoreList) DeepCopy() *ClickHouseRestoreList { + if in == nil { + return nil + } + out := new(ClickHouseRestoreList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseRestoreList) 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 *ClickHouseRestoreSpec) DeepCopyInto(out *ClickHouseRestoreSpec) { + *out = *in + out.ClusterRef = in.ClusterRef + if in.BackupRef != nil { + in, out := &in.BackupRef, &out.BackupRef + *out = new(corev1.LocalObjectReference) + **out = **in + } + if in.Source != nil { + in, out := &in.Source, &out.Source + *out = new(RestoreSource) + (*in).DeepCopyInto(*out) + } + if in.Scope != nil { + in, out := &in.Scope, &out.Scope + *out = new(BackupScope) + (*in).DeepCopyInto(*out) + } + if in.Settings != nil { + in, out := &in.Settings, &out.Settings + *out = make(map[string]string, len(*in)) + for key, val := range *in { + (*out)[key] = val + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseRestoreSpec. +func (in *ClickHouseRestoreSpec) DeepCopy() *ClickHouseRestoreSpec { + if in == nil { + return nil + } + out := new(ClickHouseRestoreSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseRestoreStatus) DeepCopyInto(out *ClickHouseRestoreStatus) { + *out = *in + in.BackupOperationStatus.DeepCopyInto(&out.BackupOperationStatus) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseRestoreStatus. +func (in *ClickHouseRestoreStatus) DeepCopy() *ClickHouseRestoreStatus { + if in == nil { + return nil + } + out := new(ClickHouseRestoreStatus) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseScheduledBackup) DeepCopyInto(out *ClickHouseScheduledBackup) { + *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 ClickHouseScheduledBackup. +func (in *ClickHouseScheduledBackup) DeepCopy() *ClickHouseScheduledBackup { + if in == nil { + return nil + } + out := new(ClickHouseScheduledBackup) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseScheduledBackup) 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 *ClickHouseScheduledBackupList) DeepCopyInto(out *ClickHouseScheduledBackupList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClickHouseScheduledBackup, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseScheduledBackupList. +func (in *ClickHouseScheduledBackupList) DeepCopy() *ClickHouseScheduledBackupList { + if in == nil { + return nil + } + out := new(ClickHouseScheduledBackupList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClickHouseScheduledBackupList) 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 *ClickHouseScheduledBackupSpec) DeepCopyInto(out *ClickHouseScheduledBackupSpec) { + *out = *in + if in.TimeZone != nil { + in, out := &in.TimeZone, &out.TimeZone + *out = new(string) + **out = **in + } + if in.Suspend != nil { + in, out := &in.Suspend, &out.Suspend + *out = new(bool) + **out = **in + } + if in.FullBackupInterval != nil { + in, out := &in.FullBackupInterval, &out.FullBackupInterval + *out = new(int32) + **out = **in + } + if in.SuccessfulBackupsHistoryLimit != nil { + in, out := &in.SuccessfulBackupsHistoryLimit, &out.SuccessfulBackupsHistoryLimit + *out = new(int32) + **out = **in + } + if in.FailedBackupsHistoryLimit != nil { + in, out := &in.FailedBackupsHistoryLimit, &out.FailedBackupsHistoryLimit + *out = new(int32) + **out = **in + } + in.Template.DeepCopyInto(&out.Template) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseScheduledBackupSpec. +func (in *ClickHouseScheduledBackupSpec) DeepCopy() *ClickHouseScheduledBackupSpec { + if in == nil { + return nil + } + out := new(ClickHouseScheduledBackupSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClickHouseScheduledBackupStatus) DeepCopyInto(out *ClickHouseScheduledBackupStatus) { + *out = *in + if in.Conditions != nil { + in, out := &in.Conditions, &out.Conditions + *out = make([]v1.Condition, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.LastScheduleTime != nil { + in, out := &in.LastScheduleTime, &out.LastScheduleTime + *out = (*in).DeepCopy() + } + if in.LastSuccessfulTime != nil { + in, out := &in.LastSuccessfulTime, &out.LastSuccessfulTime + *out = (*in).DeepCopy() + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClickHouseScheduledBackupStatus. +func (in *ClickHouseScheduledBackupStatus) DeepCopy() *ClickHouseScheduledBackupStatus { + if in == nil { + return nil + } + out := new(ClickHouseScheduledBackupStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClickHouseSettings) DeepCopyInto(out *ClickHouseSettings) { *out = *in @@ -288,7 +766,7 @@ func (in *ClusterTLSSpec) DeepCopyInto(out *ClusterTLSSpec) { *out = *in if in.ServerCertSecret != nil { in, out := &in.ServerCertSecret, &out.ServerCertSecret - *out = new(v1.LocalObjectReference) + *out = new(corev1.LocalObjectReference) **out = **in } if in.CABundle != nil { @@ -345,41 +823,41 @@ func (in *ContainerTemplateSpec) DeepCopyInto(out *ContainerTemplateSpec) { in.Resources.DeepCopyInto(&out.Resources) if in.VolumeMounts != nil { in, out := &in.VolumeMounts, &out.VolumeMounts - *out = make([]v1.VolumeMount, len(*in)) + *out = make([]corev1.VolumeMount, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Env != nil { in, out := &in.Env, &out.Env - *out = make([]v1.EnvVar, len(*in)) + *out = make([]corev1.EnvVar, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.SecurityContext != nil { in, out := &in.SecurityContext, &out.SecurityContext - *out = new(v1.SecurityContext) + *out = new(corev1.SecurityContext) (*in).DeepCopyInto(*out) } if in.LivenessProbe != nil { in, out := &in.LivenessProbe, &out.LivenessProbe - *out = new(v1.Probe) + *out = new(corev1.Probe) (*in).DeepCopyInto(*out) } if in.ReadinessProbe != nil { in, out := &in.ReadinessProbe, &out.ReadinessProbe - *out = new(v1.Probe) + *out = new(corev1.Probe) (*in).DeepCopyInto(*out) } if in.StartupProbe != nil { in, out := &in.StartupProbe, &out.StartupProbe - *out = new(v1.Probe) + *out = new(corev1.Probe) (*in).DeepCopyInto(*out) } if in.Lifecycle != nil { in, out := &in.Lifecycle, &out.Lifecycle - *out = new(v1.Lifecycle) + *out = new(corev1.Lifecycle) (*in).DeepCopyInto(*out) } } @@ -570,7 +1048,7 @@ func (in *KeeperClusterSpec) DeepCopyInto(out *KeeperClusterSpec) { in.ContainerTemplate.DeepCopyInto(&out.ContainerTemplate) if in.DataVolumeClaimSpec != nil { in, out := &in.DataVolumeClaimSpec, &out.DataVolumeClaimSpec - *out = new(v1.PersistentVolumeClaimSpec) + *out = new(corev1.PersistentVolumeClaimSpec) (*in).DeepCopyInto(*out) } if in.Labels != nil { @@ -620,7 +1098,7 @@ func (in *KeeperClusterStatus) DeepCopyInto(out *KeeperClusterStatus) { *out = *in if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions - *out = make([]metav1.Condition, len(*in)) + *out = make([]v1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -776,14 +1254,14 @@ func (in *PodTemplateSpec) DeepCopyInto(out *PodTemplateSpec) { } if in.TopologySpreadConstraints != nil { in, out := &in.TopologySpreadConstraints, &out.TopologySpreadConstraints - *out = make([]v1.TopologySpreadConstraint, len(*in)) + *out = make([]corev1.TopologySpreadConstraint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.ImagePullSecrets != nil { in, out := &in.ImagePullSecrets, &out.ImagePullSecrets - *out = make([]v1.LocalObjectReference, len(*in)) + *out = make([]corev1.LocalObjectReference, len(*in)) copy(*out, *in) } if in.NodeSelector != nil { @@ -795,12 +1273,12 @@ func (in *PodTemplateSpec) DeepCopyInto(out *PodTemplateSpec) { } if in.Affinity != nil { in, out := &in.Affinity, &out.Affinity - *out = new(v1.Affinity) + *out = new(corev1.Affinity) (*in).DeepCopyInto(*out) } if in.Tolerations != nil { in, out := &in.Tolerations, &out.Tolerations - *out = make([]v1.Toleration, len(*in)) + *out = make([]corev1.Toleration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -817,14 +1295,14 @@ func (in *PodTemplateSpec) DeepCopyInto(out *PodTemplateSpec) { } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes - *out = make([]v1.Volume, len(*in)) + *out = make([]corev1.Volume, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.SecurityContext != nil { in, out := &in.SecurityContext, &out.SecurityContext - *out = new(v1.PodSecurityContext) + *out = new(corev1.PodSecurityContext) (*in).DeepCopyInto(*out) } if in.TopologyZoneKey != nil { @@ -844,7 +1322,7 @@ func (in *PodTemplateSpec) DeepCopyInto(out *PodTemplateSpec) { } if in.InitContainers != nil { in, out := &in.InitContainers, &out.InitContainers - *out = make([]v1.Container, len(*in)) + *out = make([]corev1.Container, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } @@ -861,6 +1339,59 @@ func (in *PodTemplateSpec) DeepCopy() *PodTemplateSpec { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *RestoreSource) DeepCopyInto(out *RestoreSource) { + *out = *in + in.Storage.DeepCopyInto(&out.Storage) +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RestoreSource. +func (in *RestoreSource) DeepCopy() *RestoreSource { + if in == nil { + return nil + } + out := new(RestoreSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *S3BackupStorage) DeepCopyInto(out *S3BackupStorage) { + *out = *in + if in.Credentials != nil { + in, out := &in.Credentials, &out.Credentials + *out = new(S3Credentials) + **out = **in + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new S3BackupStorage. +func (in *S3BackupStorage) DeepCopy() *S3BackupStorage { + if in == nil { + return nil + } + out := new(S3BackupStorage) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *S3Credentials) DeepCopyInto(out *S3Credentials) { + *out = *in + out.AccessKeyID = in.AccessKeyID + out.SecretAccessKey = in.SecretAccessKey +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new S3Credentials. +func (in *S3Credentials) DeepCopy() *S3Credentials { + if in == nil { + return nil + } + out := new(S3Credentials) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SecretKeySelector) DeepCopyInto(out *SecretKeySelector) { *out = *in @@ -911,7 +1442,7 @@ func (in *VersionProbeContainer) DeepCopyInto(out *VersionProbeContainer) { in.Resources.DeepCopyInto(&out.Resources) if in.SecurityContext != nil { in, out := &in.SecurityContext, &out.SecurityContext - *out = new(v1.SecurityContext) + *out = new(corev1.SecurityContext) (*in).DeepCopyInto(*out) } } @@ -959,14 +1490,14 @@ func (in *VersionProbePodSpec) DeepCopyInto(out *VersionProbePodSpec) { } if in.Tolerations != nil { in, out := &in.Tolerations, &out.Tolerations - *out = make([]v1.Toleration, len(*in)) + *out = make([]corev1.Toleration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.SecurityContext != nil { in, out := &in.SecurityContext, &out.SecurityContext - *out = new(v1.PodSecurityContext) + *out = new(corev1.PodSecurityContext) (*in).DeepCopyInto(*out) } if in.Containers != nil { diff --git a/config/crd/bases/clickhouse.com_clickhousebackups.yaml b/config/crd/bases/clickhouse.com_clickhousebackups.yaml new file mode 100644 index 000000000..d66d36ca6 --- /dev/null +++ b/config/crd/bases/clickhouse.com_clickhousebackups.yaml @@ -0,0 +1,344 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhousebackups.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseBackup + listKind: ClickHouseBackupList + plural: clickhousebackups + shortNames: + - chbackup + singular: clickhousebackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.baseBackupRef.name + name: Base + type: string + - jsonPath: .status.compressedSize + name: Size + type: integer + - jsonPath: .status.completionTime + name: Completed + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseBackup is the Schema for the `clickhousebackups` API. + It runs a single backup of a ClickHouseCluster using the ClickHouse BACKUP statement. + 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: ClickHouseBackupSpec defines the desired state of ClickHouseBackup. + properties: + baseBackupRef: + description: |- + BaseBackupRef makes the backup incremental: only the data that is missing from the referenced + ClickHouseBackup is stored. The base backup must be completed and must stay in the storage + for as long as this backup is needed. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to back up. + The cluster must be in the namespace of the backup. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the backup to the listed databases and tables. + When omitted, everything except the `system` database is backed up. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database that holds + the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: Settings are additional settings passed to the BACKUP + statement. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + storage: + description: |- + Storage is the storage the backup is written to. + The backup is stored in the directory named after this resource. + properties: + s3: + description: S3 stores backups in an S3-compatible object storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key that holds + the access key ID. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret key that + holds the secret access key. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - clusterRef + - storage + type: object + x-kubernetes-validations: + - message: settings id, async and base_backup are managed by the operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', ''async'', + ''base_backup'']))' + status: + description: ClickHouseBackupStatus defines the observed state of ClickHouseBackup. + properties: + baseLocation: + description: BaseLocation is the URL of the base backup of an incremental + backup. + type: string + completionTime: + description: CompletionTime is the time the operation finished. + format: date-time + type: string + compressedSize: + description: CompressedSize is the size in bytes the backup takes + in the storage. + format: int64 + type: integer + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + id: + description: ID identifies the operation in the `system.backups` table + of the replica that executes it. + type: string + location: + description: Location is the URL of the backup in the storage. + type: string + numFiles: + description: NumFiles is the number of files stored in the backup. + format: int64 + type: integer + phase: + description: Phase is the lifecycle phase of the operation. + enum: + - Pending + - Running + - Completed + - Failed + type: string + replica: + description: Replica is the cluster replica that executes the operation. + properties: + index: + description: Index is the index of the replica within the shard. + format: int32 + type: integer + shardID: + description: ShardID is the shard of the replica. + format: int32 + type: integer + required: + - index + - shardID + type: object + startTime: + description: StartTime is the time the operation was submitted to + ClickHouse. + format: date-time + type: string + totalSize: + description: TotalSize is the size in bytes of the data covered by + the backup, including the data stored in base backups. + format: int64 + type: integer + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: spec is immutable + rule: '!has(oldSelf.spec) || self.spec == oldSelf.spec' + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/clickhouse.com_clickhouserestores.yaml b/config/crd/bases/clickhouse.com_clickhouserestores.yaml new file mode 100644 index 000000000..4dcddf073 --- /dev/null +++ b/config/crd/bases/clickhouse.com_clickhouserestores.yaml @@ -0,0 +1,340 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhouserestores.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseRestore + listKind: ClickHouseRestoreList + plural: clickhouserestores + shortNames: + - chrestore + singular: clickhouserestore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .spec.backupRef.name + name: Backup + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.completionTime + name: Completed + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseRestore is the Schema for the `clickhouserestores` API. + It restores a backup into a ClickHouseCluster once using the ClickHouse RESTORE statement. + 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: ClickHouseRestoreSpec defines the desired state of ClickHouseRestore. + properties: + backupRef: + description: |- + BackupRef references the completed ClickHouseBackup to restore from. + Mutually exclusive with `source`, exactly one of them must be set. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to restore + into. The cluster must be in the namespace of the restore. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the restore to the listed databases and tables. + When omitted, everything except the `system` database is restored. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database that holds + the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: |- + Settings are additional settings passed to the RESTORE statement, + for example `allow_non_empty_tables` or `structure_only`. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + source: + description: |- + Source locates the backup to restore from directly in the storage. + Mutually exclusive with `backupRef`, exactly one of them must be set. + properties: + name: + description: |- + Name is the name of the backup directory in the storage. + It is the name of the ClickHouseBackup resource that created the backup. + maxLength: 253 + minLength: 1 + pattern: ^[^\s'\\]+$ + type: string + storage: + description: Storage is the storage that holds the backup. + properties: + s3: + description: S3 stores backups in an S3-compatible object + storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key that + holds the access key ID. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret key + that holds the secret access key. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - name + - storage + type: object + required: + - clusterRef + type: object + x-kubernetes-validations: + - message: exactly one of backupRef or source must be set + rule: has(self.backupRef) != has(self.source) + - message: settings id, async and base_backup are managed by the operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', ''async'', + ''base_backup'']))' + status: + description: ClickHouseRestoreStatus defines the observed state of ClickHouseRestore. + properties: + completionTime: + description: CompletionTime is the time the operation finished. + format: date-time + type: string + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + id: + description: ID identifies the operation in the `system.backups` table + of the replica that executes it. + type: string + location: + description: Location is the URL of the backup in the storage. + type: string + phase: + description: Phase is the lifecycle phase of the operation. + enum: + - Pending + - Running + - Completed + - Failed + type: string + replica: + description: Replica is the cluster replica that executes the operation. + properties: + index: + description: Index is the index of the replica within the shard. + format: int32 + type: integer + shardID: + description: ShardID is the shard of the replica. + format: int32 + type: integer + required: + - index + - shardID + type: object + startTime: + description: StartTime is the time the operation was submitted to + ClickHouse. + format: date-time + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: spec is immutable + rule: '!has(oldSelf.spec) || self.spec == oldSelf.spec' + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml b/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml new file mode 100644 index 000000000..a69b8fa3f --- /dev/null +++ b/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml @@ -0,0 +1,361 @@ +--- +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhousescheduledbackups.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseScheduledBackup + listKind: ClickHouseScheduledBackupList + plural: clickhousescheduledbackups + shortNames: + - chscheduledbackup + singular: clickhousescheduledbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.template.spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .spec.suspend + name: Suspend + type: boolean + - jsonPath: .status.lastScheduleTime + name: LastSchedule + type: date + - jsonPath: .status.lastSuccessfulTime + name: LastSuccessful + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseScheduledBackup is the Schema for the `clickhousescheduledbackups` API. + It creates ClickHouseBackup resources on a schedule. + 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: ClickHouseScheduledBackupSpec defines the desired state of + ClickHouseScheduledBackup. + properties: + failedBackupsHistoryLimit: + default: 3 + description: FailedBackupsHistoryLimit is the number of failed ClickHouseBackup + resources to keep. + format: int32 + minimum: 0 + type: integer + fullBackupInterval: + description: |- + FullBackupInterval makes the schedule take incremental backups: every full backup is followed by + `fullBackupInterval - 1` incremental backups based on it. + When unset or 1, every backup is a full backup. + format: int32 + minimum: 1 + type: integer + schedule: + description: Schedule in the cron format, see https://en.wikipedia.org/wiki/Cron. + minLength: 1 + type: string + successfulBackupsHistoryLimit: + default: 10 + description: |- + SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. + The most recent full backup and the base backups of the kept incremental backups are always kept. + Deleting a ClickHouseBackup resource does not delete the backup data from the storage. + format: int32 + minimum: 1 + type: integer + suspend: + description: Suspend stops the creation of new backups. Backups that + are already running are not affected. + type: boolean + template: + description: Template describes the backups created by the schedule. + properties: + spec: + description: Spec of the created backups. `baseBackupRef` is managed + by the schedule and must not be set. + properties: + baseBackupRef: + description: |- + BaseBackupRef makes the backup incremental: only the data that is missing from the referenced + ClickHouseBackup is stored. The base backup must be completed and must stay in the storage + for as long as this backup is needed. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to + back up. The cluster must be in the namespace of the backup. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the backup to the listed databases and tables. + When omitted, everything except the `system` database is backed up. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database + that holds the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: Settings are additional settings passed to the + BACKUP statement. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + storage: + description: |- + Storage is the storage the backup is written to. + The backup is stored in the directory named after this resource. + properties: + s3: + description: S3 stores backups in an S3-compatible object + storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key + that holds the access key ID. + properties: + key: + description: The key of the secret to select + from. Must be a valid secret key. + type: string + name: + description: The name of the secret in the + cluster's namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret + key that holds the secret access key. + properties: + key: + description: The key of the secret to select + from. Must be a valid secret key. + type: string + name: + description: The name of the secret in the + cluster's namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - clusterRef + - storage + type: object + x-kubernetes-validations: + - message: baseBackupRef is managed by the schedule + rule: '!has(self.baseBackupRef)' + - message: settings id, async and base_backup are managed by the + operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', + ''async'', ''base_backup'']))' + required: + - spec + type: object + timeZone: + description: TimeZone is the IANA time zone name the schedule is evaluated + in. Defaults to UTC. + type: string + required: + - schedule + - template + type: object + status: + description: ClickHouseScheduledBackupStatus defines the observed state + of ClickHouseScheduledBackup. + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + lastBackupName: + description: LastBackupName is the name of the most recent ClickHouseBackup + created by the schedule. + type: string + lastScheduleTime: + description: LastScheduleTime is the schedule time of the most recent + backup created by the schedule. + format: date-time + type: string + lastSuccessfulBackupName: + description: LastSuccessfulBackupName is the name of the most recent + successful ClickHouseBackup. + type: string + lastSuccessfulTime: + description: LastSuccessfulTime is the completion time of the most + recent successful backup. + format: date-time + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: name must be no more than 48 characters + rule: self.metadata.name.size() <= 48 + served: true + storage: true + subresources: + status: {} diff --git a/config/crd/kustomization.yaml b/config/crd/kustomization.yaml index d08ff27c5..db9d8e13d 100644 --- a/config/crd/kustomization.yaml +++ b/config/crd/kustomization.yaml @@ -4,4 +4,7 @@ resources: - bases/clickhouse.com_keeperclusters.yaml - bases/clickhouse.com_clickhouseclusters.yaml +- bases/clickhouse.com_clickhousebackups.yaml +- bases/clickhouse.com_clickhouserestores.yaml +- bases/clickhouse.com_clickhousescheduledbackups.yaml # +kubebuilder:scaffold:crdkustomizeresource diff --git a/config/manifests/bases/clickhouse-operator.clusterserviceversion.yaml b/config/manifests/bases/clickhouse-operator.clusterserviceversion.yaml index 05b22e5e8..d855cc410 100644 --- a/config/manifests/bases/clickhouse-operator.clusterserviceversion.yaml +++ b/config/manifests/bases/clickhouse-operator.clusterserviceversion.yaml @@ -15,6 +15,13 @@ spec: apiservicedefinitions: {} customresourcedefinitions: owned: + - description: |- + ClickHouseBackup is the Schema for the `clickhousebackups` API. + It runs a single backup of a ClickHouseCluster using the ClickHouse BACKUP statement. + displayName: ClickHouse Backup + kind: ClickHouseBackup + name: clickhousebackups.clickhouse.com + version: v1alpha1 - description: ClickHouseCluster is the Schema for the `clickhouseclusters` API. displayName: ClickHouse Cluster kind: ClickHouseCluster @@ -94,6 +101,24 @@ spec: displayName: Version Probe Revision path: versionProbeRevision version: v1alpha1 + - description: |- + ClickHouseRestore is the Schema for the `clickhouserestores` API. + It restores a backup into a ClickHouseCluster once using the ClickHouse RESTORE statement. + displayName: ClickHouse Restore + kind: ClickHouseRestore + name: clickhouserestores.clickhouse.com + version: v1alpha1 + - description: |- + ClickHouseScheduledBackup is the Schema for the `clickhousescheduledbackups` API. + It creates ClickHouseBackup resources on a schedule. + displayName: ClickHouse Scheduled Backup + kind: ClickHouseScheduledBackup + name: clickhousescheduledbackups.clickhouse.com + resources: + - kind: ClickHouseBackup + name: "" + version: v1alpha1 + version: v1alpha1 - description: KeeperCluster is the Schema for the `keeperclusters` API. displayName: Keeper Cluster kind: KeeperCluster diff --git a/config/rbac/clickhousebackup_admin_role.yaml b/config/rbac/clickhousebackup_admin_role.yaml new file mode 100644 index 000000000..bcbdae8d9 --- /dev/null +++ b/config/rbac/clickhousebackup_admin_role.yaml @@ -0,0 +1,28 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over clickhouse.com. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: clickhousebackup-admin-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get diff --git a/config/rbac/clickhousebackup_editor_role.yaml b/config/rbac/clickhousebackup_editor_role.yaml new file mode 100644 index 000000000..d9e1b75c2 --- /dev/null +++ b/config/rbac/clickhousebackup_editor_role.yaml @@ -0,0 +1,34 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the clickhouse.com. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: clickhousebackup-editor-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get diff --git a/config/rbac/clickhousebackup_viewer_role.yaml b/config/rbac/clickhousebackup_viewer_role.yaml new file mode 100644 index 000000000..2217d8d8f --- /dev/null +++ b/config/rbac/clickhousebackup_viewer_role.yaml @@ -0,0 +1,30 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to clickhouse.com resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: clickhousebackup-viewer-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get diff --git a/config/rbac/clickhouserestore_admin_role.yaml b/config/rbac/clickhouserestore_admin_role.yaml new file mode 100644 index 000000000..f5c4e04e4 --- /dev/null +++ b/config/rbac/clickhouserestore_admin_role.yaml @@ -0,0 +1,28 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over clickhouse.com. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: clickhouserestore-admin-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get diff --git a/config/rbac/clickhouserestore_editor_role.yaml b/config/rbac/clickhouserestore_editor_role.yaml new file mode 100644 index 000000000..b0d6af890 --- /dev/null +++ b/config/rbac/clickhouserestore_editor_role.yaml @@ -0,0 +1,34 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the clickhouse.com. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: clickhouserestore-editor-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get diff --git a/config/rbac/clickhouserestore_viewer_role.yaml b/config/rbac/clickhouserestore_viewer_role.yaml new file mode 100644 index 000000000..cd147d919 --- /dev/null +++ b/config/rbac/clickhouserestore_viewer_role.yaml @@ -0,0 +1,30 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to clickhouse.com resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: clickhouserestore-viewer-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get diff --git a/config/rbac/clickhousescheduledbackup_admin_role.yaml b/config/rbac/clickhousescheduledbackup_admin_role.yaml new file mode 100644 index 000000000..50f3aacdc --- /dev/null +++ b/config/rbac/clickhousescheduledbackup_admin_role.yaml @@ -0,0 +1,28 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants full permissions ('*') over clickhouse.com. +# This role is intended for users authorized to modify roles and bindings within the cluster, +# enabling them to delegate specific permissions to other users or groups as needed. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: clickhousescheduledbackup-admin-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get diff --git a/config/rbac/clickhousescheduledbackup_editor_role.yaml b/config/rbac/clickhousescheduledbackup_editor_role.yaml new file mode 100644 index 000000000..11398580d --- /dev/null +++ b/config/rbac/clickhousescheduledbackup_editor_role.yaml @@ -0,0 +1,34 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants permissions to create, update, and delete resources within the clickhouse.com. +# This role is intended for users who need to manage these resources +# but should not control RBAC or manage permissions for others. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: clickhousescheduledbackup-editor-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get diff --git a/config/rbac/clickhousescheduledbackup_viewer_role.yaml b/config/rbac/clickhousescheduledbackup_viewer_role.yaml new file mode 100644 index 000000000..825297b9a --- /dev/null +++ b/config/rbac/clickhousescheduledbackup_viewer_role.yaml @@ -0,0 +1,30 @@ +# This rule is not used by the project tmp itself. +# It is provided to allow the cluster admin to help manage permissions for users. +# +# Grants read-only access to clickhouse.com resources. +# This role is intended for users who need visibility into these resources +# without permissions to modify them. It is ideal for monitoring purposes and limited-access viewing. + +apiVersion: rbac.authorization.k8s.io/v1 +kind: ClusterRole +metadata: + labels: + app.kubernetes.io/name: clickhouse-operator + app.kubernetes.io/managed-by: kustomize + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: clickhousescheduledbackup-viewer-role +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get diff --git a/config/rbac/kustomization.yaml b/config/rbac/kustomization.yaml index 501be4147..b6d421ef7 100644 --- a/config/rbac/kustomization.yaml +++ b/config/rbac/kustomization.yaml @@ -28,4 +28,13 @@ resources: - keepercluster_admin_role.yaml - keepercluster_editor_role.yaml - keepercluster_viewer_role.yaml +- clickhousebackup_admin_role.yaml +- clickhousebackup_editor_role.yaml +- clickhousebackup_viewer_role.yaml +- clickhouserestore_admin_role.yaml +- clickhouserestore_editor_role.yaml +- clickhouserestore_viewer_role.yaml +- clickhousescheduledbackup_admin_role.yaml +- clickhousescheduledbackup_editor_role.yaml +- clickhousescheduledbackup_viewer_role.yaml diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 9cdf173d1..69c3a6c90 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -57,7 +57,10 @@ rules: - apiGroups: - clickhouse.com resources: + - clickhousebackups - clickhouseclusters + - clickhouserestores + - clickhousescheduledbackups - keeperclusters verbs: - create @@ -70,14 +73,20 @@ rules: - apiGroups: - clickhouse.com resources: + - clickhousebackups/finalizers - clickhouseclusters/finalizers + - clickhouserestores/finalizers + - clickhousescheduledbackups/finalizers - keeperclusters/finalizers verbs: - update - apiGroups: - clickhouse.com resources: + - clickhousebackups/status - clickhouseclusters/status + - clickhouserestores/status + - clickhousescheduledbackups/status - keeperclusters/status verbs: - get diff --git a/config/samples/kustomization.yaml b/config/samples/kustomization.yaml index 15bfa3f43..59ae76423 100644 --- a/config/samples/kustomization.yaml +++ b/config/samples/kustomization.yaml @@ -2,4 +2,7 @@ resources: - v1alpha1_keeper.yaml - v1alpha1_clickhouse.yaml +- v1alpha1_clickhousebackup.yaml +- v1alpha1_clickhousescheduledbackup.yaml +- v1alpha1_clickhouserestore.yaml # +kubebuilder:scaffold:manifestskustomizesamples diff --git a/config/samples/v1alpha1_clickhousebackup.yaml b/config/samples/v1alpha1_clickhousebackup.yaml new file mode 100644 index 000000000..6bfdd799e --- /dev/null +++ b/config/samples/v1alpha1_clickhousebackup.yaml @@ -0,0 +1,17 @@ +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackup +metadata: + name: sample +spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample + credentials: + accessKeyID: + name: sample-backup-storage + key: access-key-id + secretAccessKey: + name: sample-backup-storage + key: secret-access-key diff --git a/config/samples/v1alpha1_clickhouserestore.yaml b/config/samples/v1alpha1_clickhouserestore.yaml new file mode 100644 index 000000000..1171aa213 --- /dev/null +++ b/config/samples/v1alpha1_clickhouserestore.yaml @@ -0,0 +1,9 @@ +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseRestore +metadata: + name: sample +spec: + clusterRef: + name: sample + backupRef: + name: sample diff --git a/config/samples/v1alpha1_clickhousescheduledbackup.yaml b/config/samples/v1alpha1_clickhousescheduledbackup.yaml new file mode 100644 index 000000000..7c29249d4 --- /dev/null +++ b/config/samples/v1alpha1_clickhousescheduledbackup.yaml @@ -0,0 +1,22 @@ +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseScheduledBackup +metadata: + name: sample +spec: + schedule: "0 2 * * *" + fullBackupInterval: 7 + successfulBackupsHistoryLimit: 14 + template: + spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample + credentials: + accessKeyID: + name: sample-backup-storage + key: access-key-id + secretAccessKey: + name: sample-backup-storage + key: secret-access-key diff --git a/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml b/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml new file mode 100644 index 000000000..871bd5164 --- /dev/null +++ b/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml @@ -0,0 +1,348 @@ +{{- if .Values.crd.enabled }} +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + {{- if .Values.crd.keep }} + "helm.sh/resource-policy": keep + {{- end }} + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhousebackups.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseBackup + listKind: ClickHouseBackupList + plural: clickhousebackups + shortNames: + - chbackup + singular: clickhousebackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .spec.baseBackupRef.name + name: Base + type: string + - jsonPath: .status.compressedSize + name: Size + type: integer + - jsonPath: .status.completionTime + name: Completed + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseBackup is the Schema for the `clickhousebackups` API. + It runs a single backup of a ClickHouseCluster using the ClickHouse BACKUP statement. + 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: ClickHouseBackupSpec defines the desired state of ClickHouseBackup. + properties: + baseBackupRef: + description: |- + BaseBackupRef makes the backup incremental: only the data that is missing from the referenced + ClickHouseBackup is stored. The base backup must be completed and must stay in the storage + for as long as this backup is needed. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to back up. + The cluster must be in the namespace of the backup. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the backup to the listed databases and tables. + When omitted, everything except the `system` database is backed up. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database that holds + the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: Settings are additional settings passed to the BACKUP + statement. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + storage: + description: |- + Storage is the storage the backup is written to. + The backup is stored in the directory named after this resource. + properties: + s3: + description: S3 stores backups in an S3-compatible object storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key that holds + the access key ID. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret key that + holds the secret access key. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - clusterRef + - storage + type: object + x-kubernetes-validations: + - message: settings id, async and base_backup are managed by the operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', ''async'', + ''base_backup'']))' + status: + description: ClickHouseBackupStatus defines the observed state of ClickHouseBackup. + properties: + baseLocation: + description: BaseLocation is the URL of the base backup of an incremental + backup. + type: string + completionTime: + description: CompletionTime is the time the operation finished. + format: date-time + type: string + compressedSize: + description: CompressedSize is the size in bytes the backup takes + in the storage. + format: int64 + type: integer + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + id: + description: ID identifies the operation in the `system.backups` table + of the replica that executes it. + type: string + location: + description: Location is the URL of the backup in the storage. + type: string + numFiles: + description: NumFiles is the number of files stored in the backup. + format: int64 + type: integer + phase: + description: Phase is the lifecycle phase of the operation. + enum: + - Pending + - Running + - Completed + - Failed + type: string + replica: + description: Replica is the cluster replica that executes the operation. + properties: + index: + description: Index is the index of the replica within the shard. + format: int32 + type: integer + shardID: + description: ShardID is the shard of the replica. + format: int32 + type: integer + required: + - index + - shardID + type: object + startTime: + description: StartTime is the time the operation was submitted to + ClickHouse. + format: date-time + type: string + totalSize: + description: TotalSize is the size in bytes of the data covered by + the backup, including the data stored in base backups. + format: int64 + type: integer + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: spec is immutable + rule: '!has(oldSelf.spec) || self.spec == oldSelf.spec' + served: true + storage: true + subresources: + status: {} +{{- end }} diff --git a/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml b/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml new file mode 100644 index 000000000..e886d2f9b --- /dev/null +++ b/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml @@ -0,0 +1,344 @@ +{{- if .Values.crd.enabled }} +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + {{- if .Values.crd.keep }} + "helm.sh/resource-policy": keep + {{- end }} + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhouserestores.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseRestore + listKind: ClickHouseRestoreList + plural: clickhouserestores + shortNames: + - chrestore + singular: clickhouserestore + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .spec.backupRef.name + name: Backup + type: string + - jsonPath: .status.phase + name: Phase + type: string + - jsonPath: .status.completionTime + name: Completed + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseRestore is the Schema for the `clickhouserestores` API. + It restores a backup into a ClickHouseCluster once using the ClickHouse RESTORE statement. + 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: ClickHouseRestoreSpec defines the desired state of ClickHouseRestore. + properties: + backupRef: + description: |- + BackupRef references the completed ClickHouseBackup to restore from. + Mutually exclusive with `source`, exactly one of them must be set. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to restore + into. The cluster must be in the namespace of the restore. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the restore to the listed databases and tables. + When omitted, everything except the `system` database is restored. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database that holds + the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: |- + Settings are additional settings passed to the RESTORE statement, + for example `allow_non_empty_tables` or `structure_only`. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + source: + description: |- + Source locates the backup to restore from directly in the storage. + Mutually exclusive with `backupRef`, exactly one of them must be set. + properties: + name: + description: |- + Name is the name of the backup directory in the storage. + It is the name of the ClickHouseBackup resource that created the backup. + maxLength: 253 + minLength: 1 + pattern: ^[^\s'\\]+$ + type: string + storage: + description: Storage is the storage that holds the backup. + properties: + s3: + description: S3 stores backups in an S3-compatible object + storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key that + holds the access key ID. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret key + that holds the secret access key. + properties: + key: + description: The key of the secret to select from. Must + be a valid secret key. + type: string + name: + description: The name of the secret in the cluster's + namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - name + - storage + type: object + required: + - clusterRef + type: object + x-kubernetes-validations: + - message: exactly one of backupRef or source must be set + rule: has(self.backupRef) != has(self.source) + - message: settings id, async and base_backup are managed by the operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', ''async'', + ''base_backup'']))' + status: + description: ClickHouseRestoreStatus defines the observed state of ClickHouseRestore. + properties: + completionTime: + description: CompletionTime is the time the operation finished. + format: date-time + type: string + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + id: + description: ID identifies the operation in the `system.backups` table + of the replica that executes it. + type: string + location: + description: Location is the URL of the backup in the storage. + type: string + phase: + description: Phase is the lifecycle phase of the operation. + enum: + - Pending + - Running + - Completed + - Failed + type: string + replica: + description: Replica is the cluster replica that executes the operation. + properties: + index: + description: Index is the index of the replica within the shard. + format: int32 + type: integer + shardID: + description: ShardID is the shard of the replica. + format: int32 + type: integer + required: + - index + - shardID + type: object + startTime: + description: StartTime is the time the operation was submitted to + ClickHouse. + format: date-time + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: spec is immutable + rule: '!has(oldSelf.spec) || self.spec == oldSelf.spec' + served: true + storage: true + subresources: + status: {} +{{- end }} diff --git a/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml b/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml new file mode 100644 index 000000000..d4319a909 --- /dev/null +++ b/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml @@ -0,0 +1,365 @@ +{{- if .Values.crd.enabled }} +apiVersion: apiextensions.k8s.io/v1 +kind: CustomResourceDefinition +metadata: + annotations: + {{- if .Values.crd.keep }} + "helm.sh/resource-policy": keep + {{- end }} + controller-gen.kubebuilder.io/version: v0.23.0 + name: clickhousescheduledbackups.clickhouse.com +spec: + group: clickhouse.com + names: + kind: ClickHouseScheduledBackup + listKind: ClickHouseScheduledBackupList + plural: clickhousescheduledbackups + shortNames: + - chscheduledbackup + singular: clickhousescheduledbackup + scope: Namespaced + versions: + - additionalPrinterColumns: + - jsonPath: .spec.template.spec.clusterRef.name + name: Cluster + type: string + - jsonPath: .spec.schedule + name: Schedule + type: string + - jsonPath: .spec.suspend + name: Suspend + type: boolean + - jsonPath: .status.lastScheduleTime + name: LastSchedule + type: date + - jsonPath: .status.lastSuccessfulTime + name: LastSuccessful + type: date + - jsonPath: .metadata.creationTimestamp + name: Age + type: date + name: v1alpha1 + schema: + openAPIV3Schema: + description: |- + ClickHouseScheduledBackup is the Schema for the `clickhousescheduledbackups` API. + It creates ClickHouseBackup resources on a schedule. + 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: ClickHouseScheduledBackupSpec defines the desired state of + ClickHouseScheduledBackup. + properties: + failedBackupsHistoryLimit: + default: 3 + description: FailedBackupsHistoryLimit is the number of failed ClickHouseBackup + resources to keep. + format: int32 + minimum: 0 + type: integer + fullBackupInterval: + description: |- + FullBackupInterval makes the schedule take incremental backups: every full backup is followed by + `fullBackupInterval - 1` incremental backups based on it. + When unset or 1, every backup is a full backup. + format: int32 + minimum: 1 + type: integer + schedule: + description: Schedule in the cron format, see https://en.wikipedia.org/wiki/Cron. + minLength: 1 + type: string + successfulBackupsHistoryLimit: + default: 10 + description: |- + SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. + The most recent full backup and the base backups of the kept incremental backups are always kept. + Deleting a ClickHouseBackup resource does not delete the backup data from the storage. + format: int32 + minimum: 1 + type: integer + suspend: + description: Suspend stops the creation of new backups. Backups that + are already running are not affected. + type: boolean + template: + description: Template describes the backups created by the schedule. + properties: + spec: + description: Spec of the created backups. `baseBackupRef` is managed + by the schedule and must not be set. + properties: + baseBackupRef: + description: |- + BaseBackupRef makes the backup incremental: only the data that is missing from the referenced + ClickHouseBackup is stored. The base backup must be completed and must stay in the storage + for as long as this backup is needed. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + clusterRef: + description: ClusterRef references the ClickHouseCluster to + back up. The cluster must be in the namespace of the backup. + properties: + name: + default: "" + description: |- + Name of the referent. + This field is effectively required, but due to backwards compatibility is + allowed to be empty. Instances of this type with an empty value here are + almost certainly wrong. + More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names + type: string + type: object + x-kubernetes-map-type: atomic + scope: + description: |- + Scope limits the backup to the listed databases and tables. + When omitted, everything except the `system` database is backed up. + properties: + databases: + description: Databases lists the databases to include. + items: + minLength: 1 + type: string + maxItems: 256 + type: array + x-kubernetes-list-type: set + tables: + description: Tables lists the individual tables to include. + items: + description: BackupTable identifies a table. + properties: + database: + description: Database is the name of the database + that holds the table. + minLength: 1 + type: string + table: + description: Table is the name of the table. + minLength: 1 + type: string + required: + - database + - table + type: object + maxItems: 1024 + type: array + x-kubernetes-list-type: atomic + type: object + settings: + additionalProperties: + type: string + description: Settings are additional settings passed to the + BACKUP statement. + maxProperties: 64 + type: object + x-kubernetes-validations: + - message: setting names must be valid identifiers + rule: self.all(k, k.matches('^[A-Za-z_][A-Za-z0-9_]*$')) + storage: + description: |- + Storage is the storage the backup is written to. + The backup is stored in the directory named after this resource. + properties: + s3: + description: S3 stores backups in an S3-compatible object + storage. + properties: + credentials: + description: |- + Credentials used to access the storage. + When omitted, ClickHouse uses the credentials available to the server itself, + such as an IAM role attached to the Pod or the node. + properties: + accessKeyID: + description: AccessKeyID selects the Secret key + that holds the access key ID. + properties: + key: + description: The key of the secret to select + from. Must be a valid secret key. + type: string + name: + description: The name of the secret in the + cluster's namespace to select from. + type: string + required: + - key + - name + type: object + secretAccessKey: + description: SecretAccessKey selects the Secret + key that holds the secret access key. + properties: + key: + description: The key of the secret to select + from. Must be a valid secret key. + type: string + name: + description: The name of the secret in the + cluster's namespace to select from. + type: string + required: + - key + - name + type: object + required: + - accessKeyID + - secretAccessKey + type: object + endpoint: + description: |- + Endpoint is the URL of the bucket and the prefix that holds backups, for example + `https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`. + Every backup is written to its own directory under this URL. + maxLength: 2048 + pattern: ^https?://[^\s'\\]+$ + type: string + required: + - endpoint + type: object + type: object + x-kubernetes-validations: + - message: s3 storage must be set + rule: has(self.s3) + required: + - clusterRef + - storage + type: object + x-kubernetes-validations: + - message: baseBackupRef is managed by the schedule + rule: '!has(self.baseBackupRef)' + - message: settings id, async and base_backup are managed by the + operator + rule: '!has(self.settings) || self.settings.all(k, !(k in [''id'', + ''async'', ''base_backup'']))' + required: + - spec + type: object + timeZone: + description: TimeZone is the IANA time zone name the schedule is evaluated + in. Defaults to UTC. + type: string + required: + - schedule + - template + type: object + status: + description: ClickHouseScheduledBackupStatus defines the observed state + of ClickHouseScheduledBackup. + 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 + x-kubernetes-list-map-keys: + - type + x-kubernetes-list-type: map + lastBackupName: + description: LastBackupName is the name of the most recent ClickHouseBackup + created by the schedule. + type: string + lastScheduleTime: + description: LastScheduleTime is the schedule time of the most recent + backup created by the schedule. + format: date-time + type: string + lastSuccessfulBackupName: + description: LastSuccessfulBackupName is the name of the most recent + successful ClickHouseBackup. + type: string + lastSuccessfulTime: + description: LastSuccessfulTime is the completion time of the most + recent successful backup. + format: date-time + type: string + type: object + type: object + x-kubernetes-validations: + - message: spec is required + rule: has(self.spec) + - message: name must be no more than 48 characters + rule: self.metadata.name.size() <= 48 + served: true + storage: true + subresources: + status: {} +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousebackup-admin-role.yaml b/dist/chart/templates/rbac/clickhousebackup-admin-role.yaml new file mode 100644 index 000000000..136667edb --- /dev/null +++ b/dist/chart/templates/rbac/clickhousebackup-admin-role.yaml @@ -0,0 +1,32 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousebackup-admin-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousebackup-editor-role.yaml b/dist/chart/templates/rbac/clickhousebackup-editor-role.yaml new file mode 100644 index 000000000..2de7c9c89 --- /dev/null +++ b/dist/chart/templates/rbac/clickhousebackup-editor-role.yaml @@ -0,0 +1,38 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousebackup-editor-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousebackup-viewer-role.yaml b/dist/chart/templates/rbac/clickhousebackup-viewer-role.yaml new file mode 100644 index 000000000..a22582ba0 --- /dev/null +++ b/dist/chart/templates/rbac/clickhousebackup-viewer-role.yaml @@ -0,0 +1,34 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousebackup-viewer-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousebackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhouserestore-admin-role.yaml b/dist/chart/templates/rbac/clickhouserestore-admin-role.yaml new file mode 100644 index 000000000..12ee6d295 --- /dev/null +++ b/dist/chart/templates/rbac/clickhouserestore-admin-role.yaml @@ -0,0 +1,32 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhouserestore-admin-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhouserestore-editor-role.yaml b/dist/chart/templates/rbac/clickhouserestore-editor-role.yaml new file mode 100644 index 000000000..9012ffa78 --- /dev/null +++ b/dist/chart/templates/rbac/clickhouserestore-editor-role.yaml @@ -0,0 +1,38 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhouserestore-editor-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhouserestore-viewer-role.yaml b/dist/chart/templates/rbac/clickhouserestore-viewer-role.yaml new file mode 100644 index 000000000..d444ba967 --- /dev/null +++ b/dist/chart/templates/rbac/clickhouserestore-viewer-role.yaml @@ -0,0 +1,34 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhouserestore-viewer-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhouserestores/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousescheduledbackup-admin-role.yaml b/dist/chart/templates/rbac/clickhousescheduledbackup-admin-role.yaml new file mode 100644 index 000000000..46e0197a0 --- /dev/null +++ b/dist/chart/templates/rbac/clickhousescheduledbackup-admin-role.yaml @@ -0,0 +1,32 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-admin: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousescheduledbackup-admin-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - '*' +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousescheduledbackup-editor-role.yaml b/dist/chart/templates/rbac/clickhousescheduledbackup-editor-role.yaml new file mode 100644 index 000000000..e110b5b78 --- /dev/null +++ b/dist/chart/templates/rbac/clickhousescheduledbackup-editor-role.yaml @@ -0,0 +1,38 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-edit: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousescheduledbackup-editor-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - create + - delete + - get + - list + - patch + - update + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/clickhousescheduledbackup-viewer-role.yaml b/dist/chart/templates/rbac/clickhousescheduledbackup-viewer-role.yaml new file mode 100644 index 000000000..dd64255bb --- /dev/null +++ b/dist/chart/templates/rbac/clickhousescheduledbackup-viewer-role.yaml @@ -0,0 +1,34 @@ +{{- if .Values.rbac.helpers.enabled }} +apiVersion: rbac.authorization.k8s.io/v1 +{{- if .Values.rbac.namespaced }} +kind: Role +{{- else }} +kind: ClusterRole +{{- end }} +metadata: +{{- if .Values.rbac.namespaced }} + namespace: {{ .Release.Namespace }} +{{- end }} + labels: + app.kubernetes.io/managed-by: {{ .Release.Service }} + app.kubernetes.io/name: {{ include "clickhouse-operator.name" . }} + helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }} + app.kubernetes.io/instance: {{ .Release.Name }} + rbac.authorization.k8s.io/aggregate-to-view: "true" + name: {{ include "clickhouse-operator.resourceName" (dict "suffix" "clickhousescheduledbackup-viewer-role" "context" $) }} +rules: +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups + verbs: + - get + - list + - watch +- apiGroups: + - clickhouse.com + resources: + - clickhousescheduledbackups/status + verbs: + - get +{{- end }} diff --git a/dist/chart/templates/rbac/manager-role.yaml b/dist/chart/templates/rbac/manager-role.yaml index 90f92fea8..450ed873b 100644 --- a/dist/chart/templates/rbac/manager-role.yaml +++ b/dist/chart/templates/rbac/manager-role.yaml @@ -63,7 +63,10 @@ rules: - apiGroups: - clickhouse.com resources: + - clickhousebackups - clickhouseclusters + - clickhouserestores + - clickhousescheduledbackups - keeperclusters verbs: - create @@ -76,14 +79,20 @@ rules: - apiGroups: - clickhouse.com resources: + - clickhousebackups/finalizers - clickhouseclusters/finalizers + - clickhouserestores/finalizers + - clickhousescheduledbackups/finalizers - keeperclusters/finalizers verbs: - update - apiGroups: - clickhouse.com resources: + - clickhousebackups/status - clickhouseclusters/status + - clickhouserestores/status + - clickhousescheduledbackups/status - keeperclusters/status verbs: - get diff --git a/docs/README.md b/docs/README.md index 9a993bba3..42f67887e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ Choose your preferred installation method: - **[Introduction](./guides/introduction.mdx)** - General overview of ClickHouse Operator concepts - **[Configuration Guide](./guides/configuration.mdx)** - Configure ClickHouse and Keeper clusters - **[Monitoring](./guides/monitoring.mdx)** - Monitor clickhouse-operator using Prometheus metrics +- **[Backup and restore](./guides/backup.mdx)** - Back up clusters to S3 on a schedule and restore them ## Reference diff --git a/docs/guides/backup.mdx b/docs/guides/backup.mdx new file mode 100644 index 000000000..9fa7d02c4 --- /dev/null +++ b/docs/guides/backup.mdx @@ -0,0 +1,239 @@ +--- +position: 9 +slug: /clickhouse-operator/guides/backup +title: Backup and restore +keywords: ['kubernetes', 'backup', 'restore', 's3', 'incremental', 'schedule'] +description: 'How to back up a ClickHouse cluster to S3, schedule full and incremental backups, and restore a backup.' +doc_type: 'guide' +--- + +The operator backs up and restores a `ClickHouseCluster` with the ClickHouse [`BACKUP` and `RESTORE`](https://clickhouse.com/docs/operations/backup) statements. Three Custom Resources drive them: + +| Resource | Purpose | +|---|---| +| `ClickHouseBackup` | Takes one backup of a cluster. | +| `ClickHouseScheduledBackup` | Creates `ClickHouseBackup` resources on a schedule, optionally as incremental backups. | +| `ClickHouseRestore` | Restores a backup into a cluster once. | + +The operator submits a single statement that runs `ON CLUSTER`, so ClickHouse itself coordinates the replicas and shards and writes one consistent backup. The data flows from the ClickHouse pods to the storage directly: the operator needs no access to the storage, and no sidecar or extra pod is created. + +Backups are stored in an S3-compatible object storage. + +## Taking a backup {#taking-a-backup} + +Create a `ClickHouseBackup` in the namespace of the cluster: + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackup +metadata: + name: before-upgrade +spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample + credentials: + accessKeyID: + name: backup-storage + key: access-key-id + secretAccessKey: + name: backup-storage + key: secret-access-key +``` + +The backup is written to the directory named after the resource under `endpoint`, here `https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample/before-upgrade`. The resolved URL is reported in `status.location`. + +Follow the progress with `kubectl`: + +```bash +kubectl get clickhousebackups +``` + +```text +NAME CLUSTER PHASE BASE SIZE COMPLETED AGE +before-upgrade sample Completed 1027069 12s 40s +``` + +| Phase | Meaning | +|---|---| +| `Pending` | The backup is not started yet. The `Completed` condition explains what it waits for: the cluster, a reachable replica, the credentials Secret, or the base backup. | +| `Running` | ClickHouse is creating the backup. | +| `Completed` | The backup is in the storage. `status.numFiles`, `status.totalSize` and `status.compressedSize` describe it. | +| `Failed` | The backup failed. The `Completed` condition carries the error reported by ClickHouse. | + +A `ClickHouseBackup` describes one attempt: its spec is immutable and a failed backup is not retried. Create a new resource to try again. + + +Deleting a `ClickHouseBackup` resource does not delete the backup from the storage and does not cancel a backup that is already running. Use the lifecycle rules of the bucket to expire old backups, and keep every full backup for as long as the incremental backups based on it are needed. + + +### Storage credentials {#storage-credentials} + +`spec.storage.s3.credentials` references the keys of a Secret in the namespace of the backup. The operator reads the Secret and passes the keys in the statement; ClickHouse hides them in its logs and system tables. + +When `credentials` is omitted, ClickHouse uses the credentials available to the server itself, for example an IAM role bound to the ServiceAccount of the ClickHouse pods: + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseCluster +metadata: + name: sample +spec: + podTemplate: + serviceAccountName: clickhouse-backup +--- +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackup +metadata: + name: before-upgrade +spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample +``` + +Recent ClickHouse versions refuse to use the server credentials in a statement unless the `s3_allow_server_credentials_in_user_queries` setting is enabled. The operator enables it for the backup and restore statements it submits on the servers that know the setting. + +### Choosing what to back up {#backup-scope} + +By default a backup covers everything except the `system` database. `spec.scope` limits it to the listed databases and tables: + +```yaml +spec: + scope: + databases: + - analytics + tables: + - database: default + table: events +``` + +### Backup settings {#backup-settings} + +`spec.settings` passes additional [settings](https://clickhouse.com/docs/operations/backup#command-summary) to the statement: + +```yaml +spec: + settings: + compression_method: zstd + compression_level: "3" +``` + +The `id`, `async` and `base_backup` settings are managed by the operator and cannot be set. + +## Incremental backups {#incremental-backups} + +`spec.baseBackupRef` makes a backup incremental: ClickHouse stores only the data that is missing from the referenced backup. + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackup +metadata: + name: tuesday +spec: + clusterRef: + name: sample + baseBackupRef: + name: monday + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample +``` + +The incremental backup waits in `Pending` until the base backup is completed and fails if the base backup failed. Restoring an incremental backup reads the base backup too, so the base must stay in the storage. + +## Scheduling backups {#scheduling-backups} + +`ClickHouseScheduledBackup` creates a `ClickHouseBackup` for every run of a [cron](https://en.wikipedia.org/wiki/Cron) schedule: + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseScheduledBackup +metadata: + name: nightly +spec: + schedule: "0 2 * * *" + timeZone: Europe/Amsterdam + fullBackupInterval: 7 + successfulBackupsHistoryLimit: 14 + failedBackupsHistoryLimit: 3 + template: + spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample +``` + +The created backups are named `-`, for example `nightly-20260101020000`, and are owned by the schedule. + +| Field | Behavior | +|---|---| +| `schedule` | Cron expression of the runs, evaluated in UTC unless `timeZone` is set. | +| `suspend` | Stops the creation of new backups without affecting the running ones. | +| `fullBackupInterval` | With a value of `N`, every full backup is followed by `N - 1` incremental backups based on it. When unset, every backup is full. A failed full backup is taken again on the next run. | +| `successfulBackupsHistoryLimit` | Number of completed `ClickHouseBackup` resources to keep, 10 by default. The most recent full backup and the base backups of the kept incremental backups are always kept. | +| `failedBackupsHistoryLimit` | Number of failed `ClickHouseBackup` resources to keep, 3 by default. | +| `template.spec` | Spec of the created backups. `baseBackupRef` is managed by the schedule. | + +A run is skipped while the previous backup of the schedule is not finished, and only the most recent run is started after the operator was down. `status.lastScheduleTime`, `status.lastBackupName`, `status.lastSuccessfulTime` and `status.lastSuccessfulBackupName` report the state of the schedule. + + +The history limits remove `ClickHouseBackup` resources only. The backup data stays in the storage until the lifecycle rules of the bucket remove it. + + +## Restoring a backup {#restoring-a-backup} + +Create a `ClickHouseRestore` that references a completed `ClickHouseBackup`: + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseRestore +metadata: + name: restore-before-upgrade +spec: + clusterRef: + name: sample + backupRef: + name: before-upgrade +``` + +To restore a backup that has no `ClickHouseBackup` resource in the namespace, for example into a new Kubernetes cluster, locate it in the storage with `spec.source`. `name` is the name of the `ClickHouseBackup` that created the backup: + +```yaml +spec: + clusterRef: + name: sample + source: + name: nightly-20260101020000 + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample +``` + +The restore goes through the same phases as a backup and is not retried when it fails. `spec.scope` restores a subset of the backup, and `spec.settings` passes additional [settings](https://clickhouse.com/docs/operations/backup#command-summary) to the statement. + + +ClickHouse refuses to restore a table that already contains data. Restore into an empty cluster, drop the tables first, or set `allow_non_empty_tables: "true"` in `spec.settings` to accept that the restored rows are added to the existing ones. + + +## Failures {#failures} + +| `Completed` condition reason | Meaning | +|---|---| +| `Failed` | ClickHouse rejected the statement or reported that the operation failed. The message carries the error, for example a missing bucket or a backup that already exists at the location. | +| `StateLost` | The replica that executed the operation was restarted or removed before the operation finished. ClickHouse keeps the state of an operation in memory, so the operator cannot tell how it ended. | +| `BackupFailed` | The referenced backup failed. | + +The operator emits `BackupStarted`, `BackupCompleted`, `BackupFailed`, `RestoreStarted`, `RestoreCompleted` and `RestoreFailed` events on the backup and restore resources, and `BackupScheduled`, `BackupSkipped` and `InvalidSchedule` events on the schedules. + +## Related guides {#related-guides} + +- [Storage](/products/kubernetes-operator/guides/storage) +- [Kubernetes events](/products/kubernetes-operator/guides/kubernetes-events) +- [API reference](/products/kubernetes-operator/reference/api-reference) diff --git a/docs/guides/kubernetes-events.mdx b/docs/guides/kubernetes-events.mdx index 8b6e06ca3..9c8d2b54e 100644 --- a/docs/guides/kubernetes-events.mdx +++ b/docs/guides/kubernetes-events.mdx @@ -126,6 +126,22 @@ Emitted by the version checks for `ClickHouseCluster` and `KeeperCluster`. | `VersionDiverge` | Warning | A replica's detected version differs from the version the operator detected for the cluster. Suppressed during rolling updates. | | `VersionUpgradeAvailable` | Warning | A newer version is available on the configured upgrade channel, the running version is not on that channel, or it is out of support. The operator never upgrades on its own — this event only informs. | +### Backup and restore {#backup-and-restore} + +These events are emitted on the `ClickHouseBackup`, `ClickHouseRestore` and `ClickHouseScheduledBackup` resources, see [Backup and restore](/products/kubernetes-operator/guides/backup). + +| Reason | Type | Meaning | +|---|---|---| +| `BackupStarted` | Normal | The backup statement was submitted to a replica. | +| `BackupCompleted` | Normal | The backup is written to the storage. | +| `BackupFailed` | Warning | The backup failed. The message carries the error reported by ClickHouse. | +| `RestoreStarted` | Normal | The restore statement was submitted to a replica. | +| `RestoreCompleted` | Normal | The backup is restored into the cluster. | +| `RestoreFailed` | Warning | The restore failed. The message carries the error reported by ClickHouse. | +| `BackupScheduled` | Normal | A schedule created the `ClickHouseBackup` of a run. | +| `BackupSkipped` | Warning | A schedule skipped a run because its previous backup is not finished. | +| `InvalidSchedule` | Warning | The cron expression or the time zone of a schedule is invalid. | + ### ClickHouse server warnings {#clickhouse-warnings} | Reason | Type | Meaning | diff --git a/docs/navigation.json b/docs/navigation.json index 1fbfa741b..6e3de55fc 100644 --- a/docs/navigation.json +++ b/docs/navigation.json @@ -23,7 +23,8 @@ "products/kubernetes-operator/guides/scaling", "products/kubernetes-operator/guides/tls", "products/kubernetes-operator/guides/network-policies", - "products/kubernetes-operator/guides/kubernetes-events" + "products/kubernetes-operator/guides/kubernetes-events", + "products/kubernetes-operator/guides/backup" ] }, { diff --git a/docs/overview.mdx b/docs/overview.mdx index 487215b2c..32887059f 100644 --- a/docs/overview.mdx +++ b/docs/overview.mdx @@ -21,6 +21,7 @@ The Operator handles the full lifecycle of ClickHouse clusters including scaling - **High Availability**: Fault tolerant installations for ClickHouse and Keeper clusters - **Security**: Built-in security features TLS/SSL support for secure cluster communication - **Monitoring**: Prometheus metrics integration for observability +- **Backup and Restore**: Scheduled full and incremental backups to S3 and restores using native ClickHouse backups ## Installation {#installation} @@ -38,6 +39,7 @@ Choose your preferred installation method: - **[Scaling](/products/kubernetes-operator/guides/scaling)** - Scale replicas, shards, and Keeper quorum - **[Securing with TLS](/products/kubernetes-operator/guides/tls)** - Encrypt clusters end-to-end with cert-manager - **[Network policies](/products/kubernetes-operator/guides/network-policies)** - Restrict ingress to the operator's metrics and webhook endpoints +- **[Backup and restore](/products/kubernetes-operator/guides/backup)** - Back up clusters to S3 on a schedule and restore them - **[Kubernetes events](/products/kubernetes-operator/guides/kubernetes-events)** - Reconcile, scaling, version, and ClickHouse server events on cluster objects ## Reference {#reference} diff --git a/docs/reference/api-reference.mdx b/docs/reference/api-reference.mdx index 7822f1d2c..00c5f1076 100644 --- a/docs/reference/api-reference.mdx +++ b/docs/reference/api-reference.mdx @@ -22,6 +22,92 @@ AdditionalPort declares one extra TCP port to expose on the ClickHouse Pod and t Appears in: - [ClickHouseClusterSpec](#clickhouseclusterspec) +## BackupOperationStatus {#backupoperationstatus} + +BackupOperationStatus is the observed state shared by backups and restores. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | +| `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | +| `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `location` | string | Location is the URL of the backup in the storage. | false | | +| `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | +| `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | + +Appears in: +- [ClickHouseBackupStatus](#clickhousebackupstatus) +- [ClickHouseRestoreStatus](#clickhouserestorestatus) + +## BackupPhase {#backupphase} + +BackupPhase is the lifecycle phase of a backup or a restore. + +| Field | Description | +|-------|-------------| +| `Pending` | BackupPhasePending means that the operation is not started yet.
| +| `Running` | BackupPhaseRunning means that ClickHouse is executing the operation.
| +| `Completed` | BackupPhaseCompleted means that the operation finished successfully.
| +| `Failed` | BackupPhaseFailed means that the operation failed. Failed operations are not retried.
| + +Appears in: +- [BackupOperationStatus](#backupoperationstatus) +- [ClickHouseBackupStatus](#clickhousebackupstatus) +- [ClickHouseRestoreStatus](#clickhouserestorestatus) + +## BackupReplica {#backupreplica} + +BackupReplica identifies the cluster replica that executes a backup or a restore. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `shardID` | integer | ShardID is the shard of the replica. | true | | +| `index` | integer | Index is the index of the replica within the shard. | true | | + +Appears in: +- [BackupOperationStatus](#backupoperationstatus) +- [ClickHouseBackupStatus](#clickhousebackupstatus) +- [ClickHouseRestoreStatus](#clickhouserestorestatus) + +## BackupScope {#backupscope} + +BackupScope limits a backup or a restore to a subset of the cluster data. +When no databases and no tables are listed, everything except the `system` database is included. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `databases` | string array | Databases lists the databases to include. | false | | +| `tables` | [BackupTable](#backuptable) array | Tables lists the individual tables to include. | false | | + +Appears in: +- [ClickHouseBackupSpec](#clickhousebackupspec) +- [ClickHouseRestoreSpec](#clickhouserestorespec) + +## BackupStorage {#backupstorage} + +BackupStorage selects the storage that holds backups. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `s3` | [S3BackupStorage](#s3backupstorage) | S3 stores backups in an S3-compatible object storage. | false | | + +Appears in: +- [ClickHouseBackupSpec](#clickhousebackupspec) +- [RestoreSource](#restoresource) + +## BackupTable {#backuptable} + +BackupTable identifies a table. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `database` | string | Database is the name of the database that holds the table. | true | | +| `table` | string | Table is the name of the table. | true | | + +Appears in: +- [BackupScope](#backupscope) + ## CABundleSelector {#cabundleselector} CABundleSelector selects a key holding a CA bundle from a Secret in the cluster's namespace. @@ -34,6 +120,89 @@ CABundleSelector selects a key holding a CA bundle from a Secret in the cluster' Appears in: - [ClusterTLSSpec](#clustertlsspec) +## ClickHouseBackup {#clickhousebackup} + +ClickHouseBackup is the Schema for the `clickhousebackups` API. +It runs a single backup of a ClickHouseCluster using the ClickHouse BACKUP statement. + +### API Version and Kind {#clickhousebackup-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackup +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `spec` | [ClickHouseBackupSpec](#clickhousebackupspec) | | true | | +| `status` | [ClickHouseBackupStatus](#clickhousebackupstatus) | | true | | + +Appears in: +- [ClickHouseBackupList](#clickhousebackuplist) + +## ClickHouseBackupList {#clickhousebackuplist} + +ClickHouseBackupList contains a list of ClickHouseBackup. + +### API Version and Kind {#clickhousebackuplist-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseBackupList +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `items` | [ClickHouseBackup](#clickhousebackup) array | | true | | + +## ClickHouseBackupSpec {#clickhousebackupspec} + +ClickHouseBackupSpec defines the desired state of ClickHouseBackup. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `clusterRef` | [LocalObjectReference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#localobjectreference-v1-core) | ClusterRef references the ClickHouseCluster to back up. The cluster must be in the namespace of the backup. | true | | +| `storage` | [BackupStorage](#backupstorage) | Storage is the storage the backup is written to.
The backup is stored in the directory named after this resource. | true | | +| `scope` | [BackupScope](#backupscope) | Scope limits the backup to the listed databases and tables.
When omitted, everything except the `system` database is backed up. | false | | +| `baseBackupRef` | [LocalObjectReference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#localobjectreference-v1-core) | BaseBackupRef makes the backup incremental: only the data that is missing from the referenced
ClickHouseBackup is stored. The base backup must be completed and must stay in the storage
for as long as this backup is needed. | false | | +| `settings` | object (keys:string, values:string) | Settings are additional settings passed to the BACKUP statement. | false | | + +Appears in: +- [ClickHouseBackup](#clickhousebackup) +- [ClickHouseBackupTemplate](#clickhousebackuptemplate) + +## ClickHouseBackupStatus {#clickhousebackupstatus} + +ClickHouseBackupStatus defines the observed state of ClickHouseBackup. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | +| `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | +| `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `location` | string | Location is the URL of the backup in the storage. | false | | +| `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | +| `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | +| `baseLocation` | string | BaseLocation is the URL of the base backup of an incremental backup. | false | | +| `numFiles` | integer | NumFiles is the number of files stored in the backup. | false | | +| `totalSize` | integer | TotalSize is the size in bytes of the data covered by the backup, including the data stored in base backups. | false | | +| `compressedSize` | integer | CompressedSize is the size in bytes the backup takes in the storage. | false | | + +Appears in: +- [ClickHouseBackup](#clickhousebackup) + +## ClickHouseBackupTemplate {#clickhousebackuptemplate} + +ClickHouseBackupTemplate describes the ClickHouseBackup resources created by a ClickHouseScheduledBackup. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `spec` | [ClickHouseBackupSpec](#clickhousebackupspec) | Spec of the created backups. `baseBackupRef` is managed by the schedule and must not be set. | true | | + +Appears in: +- [ClickHouseScheduledBackupSpec](#clickhousescheduledbackupspec) + ## ClickHouseCluster {#clickhousecluster} ClickHouseCluster is the Schema for the `clickhouseclusters` API. @@ -130,6 +299,140 @@ Any other ingress, including client connections and metrics scraping, requires u Appears in: - [ClickHouseClusterSpec](#clickhouseclusterspec) +## ClickHouseRestore {#clickhouserestore} + +ClickHouseRestore is the Schema for the `clickhouserestores` API. +It restores a backup into a ClickHouseCluster once using the ClickHouse RESTORE statement. + +### API Version and Kind {#clickhouserestore-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseRestore +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `spec` | [ClickHouseRestoreSpec](#clickhouserestorespec) | | true | | +| `status` | [ClickHouseRestoreStatus](#clickhouserestorestatus) | | true | | + +Appears in: +- [ClickHouseRestoreList](#clickhouserestorelist) + +## ClickHouseRestoreList {#clickhouserestorelist} + +ClickHouseRestoreList contains a list of ClickHouseRestore. + +### API Version and Kind {#clickhouserestorelist-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseRestoreList +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `items` | [ClickHouseRestore](#clickhouserestore) array | | true | | + +## ClickHouseRestoreSpec {#clickhouserestorespec} + +ClickHouseRestoreSpec defines the desired state of ClickHouseRestore. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `clusterRef` | [LocalObjectReference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#localobjectreference-v1-core) | ClusterRef references the ClickHouseCluster to restore into. The cluster must be in the namespace of the restore. | true | | +| `backupRef` | [LocalObjectReference](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#localobjectreference-v1-core) | BackupRef references the completed ClickHouseBackup to restore from.
Mutually exclusive with `source`, exactly one of them must be set. | false | | +| `source` | [RestoreSource](#restoresource) | Source locates the backup to restore from directly in the storage.
Mutually exclusive with `backupRef`, exactly one of them must be set. | false | | +| `scope` | [BackupScope](#backupscope) | Scope limits the restore to the listed databases and tables.
When omitted, everything except the `system` database is restored. | false | | +| `settings` | object (keys:string, values:string) | Settings are additional settings passed to the RESTORE statement,
for example `allow_non_empty_tables` or `structure_only`. | false | | + +Appears in: +- [ClickHouseRestore](#clickhouserestore) + +## ClickHouseRestoreStatus {#clickhouserestorestatus} + +ClickHouseRestoreStatus defines the observed state of ClickHouseRestore. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | +| `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | +| `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `location` | string | Location is the URL of the backup in the storage. | false | | +| `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | +| `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | + +Appears in: +- [ClickHouseRestore](#clickhouserestore) + +## ClickHouseScheduledBackup {#clickhousescheduledbackup} + +ClickHouseScheduledBackup is the Schema for the `clickhousescheduledbackups` API. +It creates ClickHouseBackup resources on a schedule. + +### API Version and Kind {#clickhousescheduledbackup-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseScheduledBackup +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `spec` | [ClickHouseScheduledBackupSpec](#clickhousescheduledbackupspec) | | true | | +| `status` | [ClickHouseScheduledBackupStatus](#clickhousescheduledbackupstatus) | | true | | + +Appears in: +- [ClickHouseScheduledBackupList](#clickhousescheduledbackuplist) + +## ClickHouseScheduledBackupList {#clickhousescheduledbackuplist} + +ClickHouseScheduledBackupList contains a list of ClickHouseScheduledBackup. + +### API Version and Kind {#clickhousescheduledbackuplist-api-version-and-kind} + +```yaml +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseScheduledBackupList +``` + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `items` | [ClickHouseScheduledBackup](#clickhousescheduledbackup) array | | true | | + +## ClickHouseScheduledBackupSpec {#clickhousescheduledbackupspec} + +ClickHouseScheduledBackupSpec defines the desired state of ClickHouseScheduledBackup. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `schedule` | string | Schedule in the cron format, see https://en.wikipedia.org/wiki/Cron. | true | | +| `timeZone` | string | TimeZone is the IANA time zone name the schedule is evaluated in. Defaults to UTC. | false | | +| `suspend` | boolean | Suspend stops the creation of new backups. Backups that are already running are not affected. | false | | +| `fullBackupInterval` | integer | FullBackupInterval makes the schedule take incremental backups: every full backup is followed by
`fullBackupInterval - 1` incremental backups based on it.
When unset or 1, every backup is a full backup. | false | | +| `successfulBackupsHistoryLimit` | integer | SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep.
The most recent full backup and the base backups of the kept incremental backups are always kept.
Deleting a ClickHouseBackup resource does not delete the backup data from the storage. | false | 10 | +| `failedBackupsHistoryLimit` | integer | FailedBackupsHistoryLimit is the number of failed ClickHouseBackup resources to keep. | false | 3 | +| `template` | [ClickHouseBackupTemplate](#clickhousebackuptemplate) | Template describes the backups created by the schedule. | true | | + +Appears in: +- [ClickHouseScheduledBackup](#clickhousescheduledbackup) + +## ClickHouseScheduledBackupStatus {#clickhousescheduledbackupstatus} + +ClickHouseScheduledBackupStatus defines the observed state of ClickHouseScheduledBackup. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | +| `lastScheduleTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | LastScheduleTime is the schedule time of the most recent backup created by the schedule. | false | | +| `lastBackupName` | string | LastBackupName is the name of the most recent ClickHouseBackup created by the schedule. | false | | +| `lastSuccessfulTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | LastSuccessfulTime is the completion time of the most recent successful backup. | false | | +| `lastSuccessfulBackupName` | string | LastSuccessfulBackupName is the name of the most recent successful ClickHouseBackup. | false | | + +Appears in: +- [ClickHouseScheduledBackup](#clickhousescheduledbackup) + ## ClickHouseSettings {#clickhousesettings} ClickHouseSettings defines ClickHouse server settings options. @@ -523,6 +826,43 @@ Appears in: - [ClickHouseClusterSpec](#clickhouseclusterspec) - [KeeperClusterSpec](#keeperclusterspec) +## RestoreSource {#restoresource} + +RestoreSource locates a backup that is not described by a ClickHouseBackup resource, +for example a backup taken in another Kubernetes cluster. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `storage` | [BackupStorage](#backupstorage) | Storage is the storage that holds the backup. | true | | +| `name` | string | Name is the name of the backup directory in the storage.
It is the name of the ClickHouseBackup resource that created the backup. | true | | + +Appears in: +- [ClickHouseRestoreSpec](#clickhouserestorespec) + +## S3BackupStorage {#s3backupstorage} + +S3BackupStorage describes an S3-compatible backup storage. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `endpoint` | string | Endpoint is the URL of the bucket and the prefix that holds backups, for example
`https://my-bucket.s3.eu-west-1.amazonaws.com/clickhouse/my-cluster`.
Every backup is written to its own directory under this URL. | true | | +| `credentials` | [S3Credentials](#s3credentials) | Credentials used to access the storage.
When omitted, ClickHouse uses the credentials available to the server itself,
such as an IAM role attached to the Pod or the node. | false | | + +Appears in: +- [BackupStorage](#backupstorage) + +## S3Credentials {#s3credentials} + +S3Credentials references the access key used to access an S3-compatible storage. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `accessKeyID` | [SecretKeySelector](#secretkeyselector) | AccessKeyID selects the Secret key that holds the access key ID. | true | | +| `secretAccessKey` | [SecretKeySelector](#secretkeyselector) | SecretAccessKey selects the Secret key that holds the secret access key. | true | | + +Appears in: +- [S3BackupStorage](#s3backupstorage) + ## SecretKeySelector {#secretkeyselector} SecretKeySelector selects a key of a Secret. @@ -534,6 +874,7 @@ SecretKeySelector selects a key of a Secret. Appears in: - [DefaultPasswordSelector](#defaultpasswordselector) +- [S3Credentials](#s3credentials) ## TemplateMeta {#templatemeta} diff --git a/examples/scheduled_backup_s3.yaml b/examples/scheduled_backup_s3.yaml new file mode 100644 index 000000000..148746798 --- /dev/null +++ b/examples/scheduled_backup_s3.yaml @@ -0,0 +1,43 @@ +# Nightly backups of a cluster to S3: one full backup a week followed by incremental ones. +apiVersion: v1 +kind: Secret +metadata: + name: backup-storage +stringData: + access-key-id: + secret-access-key: +--- +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseScheduledBackup +metadata: + name: nightly +spec: + schedule: "0 2 * * *" + fullBackupInterval: 7 + successfulBackupsHistoryLimit: 14 + template: + spec: + clusterRef: + name: sample + storage: + s3: + endpoint: https://my-bucket.s3.us-east-1.amazonaws.com/clickhouse/sample + # Omit credentials to use the IAM role of the ClickHouse pods. + credentials: + accessKeyID: + name: backup-storage + key: access-key-id + secretAccessKey: + name: backup-storage + key: secret-access-key +--- +# Restores the backup of a run into the cluster. +# apiVersion: clickhouse.com/v1alpha1 +# kind: ClickHouseRestore +# metadata: +# name: restore-nightly +# spec: +# clusterRef: +# name: sample +# backupRef: +# name: nightly-20260101020000 diff --git a/go.mod b/go.mod index 9ac2b4a31..e3b92091e 100644 --- a/go.mod +++ b/go.mod @@ -16,6 +16,7 @@ require ( github.com/moby/moby/api v1.56.1 github.com/onsi/ginkgo/v2 v2.34.0 github.com/onsi/gomega v1.44.0 + github.com/robfig/cron/v3 v3.0.1 github.com/sethvargo/go-envconfig v1.4.3 github.com/testcontainers/testcontainers-go v0.45.0 go.uber.org/zap v1.28.0 diff --git a/go.sum b/go.sum index e83f513e4..d129957e2 100644 --- a/go.sum +++ b/go.sum @@ -233,6 +233,8 @@ github.com/prometheus/common v0.73.1 h1:SZWh/j4AvhCdhX8jvYSnxvPxhWlC9QZkjJ+tOrEr github.com/prometheus/common v0.73.1/go.mod h1:I9aA/Ukz9s1olOobh8KtCkU7B1mQPQsB9UvQPsUQ1Dk= github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4= github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= +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/controller/clickhouse/backup_commands.go b/internal/controller/clickhouse/backup_commands.go new file mode 100644 index 000000000..280e41a8e --- /dev/null +++ b/internal/controller/clickhouse/backup_commands.go @@ -0,0 +1,275 @@ +package clickhouse + +import ( + "context" + "database/sql" + "errors" + "fmt" + "maps" + "regexp" + "slices" + "strings" + + "github.com/ClickHouse/clickhouse-go/v2" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" +) + +const ( + backupOperationStateQuery = `SELECT toString(status), error, num_files, total_size, compressed_size +FROM system.backups +WHERE id = ?` + settingExistsQuery = `SELECT count() FROM system.settings WHERE name = ?` + + // settingAllowServerCredentials lets a statement use the credentials of the server itself. + // Servers that do not know the setting allow it unconditionally. + settingAllowServerCredentials = "s3_allow_server_credentials_in_user_queries" //nolint:gosec // setting name + // settingSameCredentialsForBase makes RESTORE read the base backups with the credentials of the restored backup. + settingSameCredentialsForBase = "use_same_s3_credentials_for_base_backup" //nolint:gosec // setting name + settingBackupID = "id" + settingBaseBackup = "base_backup" + + // codeBadArguments is the ClickHouse BAD_ARGUMENTS error code. + codeBadArguments = 36 + // duplicateOperationIDMessage is the part of the BAD_ARGUMENTS message returned for an already used operation ID. + duplicateOperationIDMessage = "with the same ID" + + backupStatusCreating = "CREATING_BACKUP" + backupStatusCreated = "BACKUP_CREATED" + backupStatusRestoring = "RESTORING" + backupStatusRestored = "RESTORED" +) + +// bareSettingValue matches the setting values that are rendered without quotes. +var bareSettingValue = regexp.MustCompile(`^(-?[0-9]+(\.[0-9]+)?|true|false)$`) + +// s3Location is a backup directory in an S3-compatible storage. +type s3Location struct { + URL string + AccessKeyID string + SecretAccessKey string +} + +func (l s3Location) hasCredentials() bool { + return l.AccessKeyID != "" +} + +func (l s3Location) sql() string { + if !l.hasCredentials() { + return fmt.Sprintf("S3(%s)", quoteString(l.URL)) + } + + return fmt.Sprintf("S3(%s, %s, %s)", quoteString(l.URL), quoteString(l.AccessKeyID), quoteString(l.SecretAccessKey)) +} + +// backupStatement describes a BACKUP or a RESTORE statement executed on the whole cluster. +type backupStatement struct { + Restore bool + Scope *v1.BackupScope + Location s3Location + // Base is the base backup of an incremental backup. + Base *s3Location + // ID identifies the operation in system.backups. + ID string + Settings map[string]string + // AllowServerCredentials is set when the server requires an explicit permission to use its own credentials. + AllowServerCredentials bool +} + +// SQL renders the statement. It contains the storage credentials and must never be logged. +func (s backupStatement) SQL() string { + var sb strings.Builder + + if s.Restore { + sb.WriteString("RESTORE ") + } else { + sb.WriteString("BACKUP ") + } + + sb.WriteString(backupScopeSQL(s.Scope)) + sb.WriteString(" ON CLUSTER ") + sb.WriteString(quoteString(DefaultClusterName)) + + if s.Restore { + sb.WriteString(" FROM ") + } else { + sb.WriteString(" TO ") + } + + sb.WriteString(s.Location.sql()) + sb.WriteString(" SETTINGS ") + sb.WriteString(strings.Join(s.settingsSQL(), ", ")) + sb.WriteString(" ASYNC") + + return sb.String() +} + +// usesServerCredentials reports whether any of the statement locations is accessed without explicit credentials. +func (s backupStatement) usesServerCredentials() bool { + return !s.Location.hasCredentials() || (s.Base != nil && !s.Base.hasCredentials()) +} + +func (s backupStatement) settingsSQL() []string { + settings := map[string]string{} + + if s.AllowServerCredentials && s.usesServerCredentials() { + settings[settingAllowServerCredentials] = "1" + } + + if s.Restore && s.Location.hasCredentials() { + settings[settingSameCredentialsForBase] = "1" + } + + for name, value := range s.Settings { + if bareSettingValue.MatchString(value) { + settings[name] = value + } else { + settings[name] = quoteString(value) + } + } + + // Operator managed settings always win over the user provided ones. + delete(settings, settingBackupID) + delete(settings, settingBaseBackup) + + rendered := make([]string, 0, len(settings)+2) + rendered = append(rendered, fmt.Sprintf("%s = %s", settingBackupID, quoteString(s.ID))) + + if s.Base != nil && !s.Restore { + rendered = append(rendered, fmt.Sprintf("%s = %s", settingBaseBackup, s.Base.sql())) + } + + for _, name := range slices.Sorted(maps.Keys(settings)) { + rendered = append(rendered, fmt.Sprintf("%s = %s", name, settings[name])) + } + + return rendered +} + +// backupScopeSQL renders the list of the backup elements. An empty scope covers everything except system tables. +func backupScopeSQL(scope *v1.BackupScope) string { + if scope == nil || (len(scope.Databases) == 0 && len(scope.Tables) == 0) { + return "ALL EXCEPT DATABASES system" + } + + elements := make([]string, 0, len(scope.Databases)+len(scope.Tables)) + for _, database := range scope.Databases { + elements = append(elements, "DATABASE "+quoteIdentifier(database)) + } + + for _, table := range scope.Tables { + elements = append(elements, fmt.Sprintf("TABLE %s.%s", quoteIdentifier(table.Database), quoteIdentifier(table.Table))) + } + + return strings.Join(elements, ", ") +} + +var ( + stringEscaper = strings.NewReplacer(`\`, `\\`, `'`, `\'`) + identifierEscaper = strings.NewReplacer(`\`, `\\`, "`", "\\`") +) + +func quoteString(value string) string { + return "'" + stringEscaper.Replace(value) + "'" +} + +func quoteIdentifier(name string) string { + return "`" + identifierEscaper.Replace(name) + "`" +} + +// backupOperationState is the state of a backup or a restore reported by system.backups. +type backupOperationState struct { + Status string + Error string + NumFiles uint64 + TotalSize uint64 + CompressedSize uint64 +} + +func (s backupOperationState) running() bool { + return s.Status == backupStatusCreating || s.Status == backupStatusRestoring +} + +func (s backupOperationState) succeeded() bool { + return s.Status == backupStatusCreated || s.Status == backupStatusRestored +} + +// Ping checks that the replica accepts connections. +func (cmd *commander) Ping(ctx context.Context, id v1.ClickHouseReplicaID) error { + conn, err := cmd.getConn(id) + if err != nil { + return fmt.Errorf("failed to get connection for replica %s: %w", id, err) + } + + if err := conn.Ping(ctx); err != nil { + return fmt.Errorf("ping replica %s: %w", id, err) + } + + return nil +} + +// HasSetting reports whether the replica server knows the setting. +func (cmd *commander) HasSetting(ctx context.Context, id v1.ClickHouseReplicaID, name string) (bool, error) { + conn, err := cmd.getConn(id) + if err != nil { + return false, fmt.Errorf("failed to get connection for replica %s: %w", id, err) + } + + var count uint64 + if err := conn.QueryRow(ctx, settingExistsQuery, name).Scan(&count); err != nil { + return false, fmt.Errorf("look up setting %s on replica %s: %w", name, id, err) + } + + return count > 0, nil +} + +// StartBackupOperation submits an asynchronous BACKUP or RESTORE statement to the replica. +// A statement with an operation ID that the replica already knows is treated as submitted. +func (cmd *commander) StartBackupOperation(ctx context.Context, id v1.ClickHouseReplicaID, query string) error { + conn, err := cmd.getConn(id) + if err != nil { + return fmt.Errorf("failed to get connection for replica %s: %w", id, err) + } + + if err := conn.Exec(ctx, query); err != nil { + if isDuplicateOperationID(err) { + return nil + } + + return fmt.Errorf("submit operation to replica %s: %w", id, err) + } + + return nil +} + +// BackupOperationState reads the state of the operation from the replica that executes it. +// It returns false when the replica does not know the operation. +func (cmd *commander) BackupOperationState( + ctx context.Context, + id v1.ClickHouseReplicaID, + operationID string, +) (backupOperationState, bool, error) { + conn, err := cmd.getConn(id) + if err != nil { + return backupOperationState{}, false, fmt.Errorf("failed to get connection for replica %s: %w", id, err) + } + + var state backupOperationState + + row := conn.QueryRow(ctx, backupOperationStateQuery, operationID) + if err := row.Scan(&state.Status, &state.Error, &state.NumFiles, &state.TotalSize, &state.CompressedSize); err != nil { + if errors.Is(err, sql.ErrNoRows) { + return backupOperationState{}, false, nil + } + + return backupOperationState{}, false, fmt.Errorf("query operation %s on replica %s: %w", operationID, id, err) + } + + return state, true, nil +} + +func isDuplicateOperationID(err error) bool { + var exc *clickhouse.Exception + + return errors.As(err, &exc) && exc.Code == codeBadArguments && strings.Contains(exc.Message, duplicateOperationIDMessage) +} diff --git a/internal/controller/clickhouse/backup_commands_test.go b/internal/controller/clickhouse/backup_commands_test.go new file mode 100644 index 000000000..7e0401aad --- /dev/null +++ b/internal/controller/clickhouse/backup_commands_test.go @@ -0,0 +1,176 @@ +package clickhouse + +import ( + "errors" + "fmt" + + "github.com/ClickHouse/clickhouse-go/v2" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" +) + +var _ = Describe("backupStatement", func() { + var location, withCredentials s3Location + + BeforeEach(func() { + location = s3Location{URL: "https://bucket.s3.amazonaws.com/backups/nightly"} + withCredentials = s3Location{URL: location.URL, AccessKeyID: "key", SecretAccessKey: "secret"} + }) + + It("should back up everything except system tables by default", func() { + stmt := backupStatement{Location: withCredentials, ID: "op-1"} + + Expect(stmt.SQL()).To(Equal( + "BACKUP ALL EXCEPT DATABASES system ON CLUSTER 'default' " + + "TO S3('https://bucket.s3.amazonaws.com/backups/nightly', 'key', 'secret') " + + "SETTINGS id = 'op-1' ASYNC")) + }) + + It("should render the selected databases and tables", func() { + stmt := backupStatement{ + Location: withCredentials, + ID: "op-1", + Scope: &v1.BackupScope{ + Databases: []string{"analytics", "we`ird"}, + Tables: []v1.BackupTable{{Database: "default", Table: "events"}}, + }, + } + + Expect(stmt.SQL()).To(HavePrefix( + "BACKUP DATABASE `analytics`, DATABASE `we\\`ird`, TABLE `default`.`events` ON CLUSTER 'default' TO S3(")) + }) + + It("should treat an empty scope as the default one", func() { + stmt := backupStatement{Location: withCredentials, ID: "op-1", Scope: &v1.BackupScope{}} + + Expect(stmt.SQL()).To(HavePrefix("BACKUP ALL EXCEPT DATABASES system ON CLUSTER")) + }) + + It("should render the base backup of an incremental backup", func() { + base := s3Location{URL: "https://bucket.s3.amazonaws.com/backups/full", AccessKeyID: "key", SecretAccessKey: "secret"} + stmt := backupStatement{Location: withCredentials, Base: &base, ID: "op-1"} + + Expect(stmt.SQL()).To(ContainSubstring( + "SETTINGS id = 'op-1', base_backup = S3('https://bucket.s3.amazonaws.com/backups/full', 'key', 'secret') ASYNC")) + }) + + It("should allow server credentials only when the server requires the permission", func() { + stmt := backupStatement{Location: location, ID: "op-1"} + Expect(stmt.SQL()).To(Equal( + "BACKUP ALL EXCEPT DATABASES system ON CLUSTER 'default' " + + "TO S3('https://bucket.s3.amazonaws.com/backups/nightly') SETTINGS id = 'op-1' ASYNC")) + + stmt.AllowServerCredentials = true + Expect(stmt.SQL()).To(HaveSuffix("SETTINGS id = 'op-1', s3_allow_server_credentials_in_user_queries = 1 ASYNC")) + + stmt.Location = withCredentials + Expect(stmt.SQL()).NotTo(ContainSubstring(settingAllowServerCredentials)) + + stmt.Base = &location + Expect(stmt.SQL()).To(ContainSubstring(settingAllowServerCredentials)) + }) + + It("should render user settings in a stable order and keep the managed ones", func() { + stmt := backupStatement{ + Location: withCredentials, + ID: "op-1", + Settings: map[string]string{ + "id": "user", + "base_backup": "user", + "compression_method": "zstd", + "compression_level": "3", + "deduplicate_files": "false", + }, + } + + Expect(stmt.SQL()).To(HaveSuffix( + "SETTINGS id = 'op-1', compression_level = 3, compression_method = 'zstd', deduplicate_files = false ASYNC")) + }) + + It("should render a restore", func() { + stmt := backupStatement{ + Restore: true, + Location: withCredentials, + ID: "op-2", + Settings: map[string]string{"allow_non_empty_tables": "true"}, + } + + Expect(stmt.SQL()).To(Equal( + "RESTORE ALL EXCEPT DATABASES system ON CLUSTER 'default' " + + "FROM S3('https://bucket.s3.amazonaws.com/backups/nightly', 'key', 'secret') " + + "SETTINGS id = 'op-2', allow_non_empty_tables = true, use_same_s3_credentials_for_base_backup = 1 ASYNC")) + }) + + It("should escape string literals", func() { + stmt := backupStatement{ + Location: s3Location{URL: location.URL, AccessKeyID: "k'ey", SecretAccessKey: `s\e'cret`}, //nolint:gosec // test value + ID: "op-1", + } + + Expect(stmt.SQL()).To(ContainSubstring(`'k\'ey', 's\\e\'cret')`)) + }) +}) + +var _ = Describe("backupOperationState", func() { + DescribeTable("should classify statuses", + func(status string, running, succeeded bool) { + state := backupOperationState{Status: status} + Expect(state.running()).To(Equal(running)) + Expect(state.succeeded()).To(Equal(succeeded)) + }, + Entry("creating", "CREATING_BACKUP", true, false), + Entry("created", "BACKUP_CREATED", false, true), + Entry("backup failed", "BACKUP_FAILED", false, false), + Entry("backup cancelled", "BACKUP_CANCELLED", false, false), + Entry("restoring", "RESTORING", true, false), + Entry("restored", "RESTORED", false, true), + Entry("restore failed", "RESTORE_FAILED", false, false), + Entry("restore cancelled", "RESTORE_CANCELLED", false, false), + ) +}) + +var _ = Describe("isDuplicateOperationID", func() { + It("should recognize a repeated operation ID", func() { + err := fmt.Errorf("submit: %w", &clickhouse.Exception{ + Code: codeBadArguments, + Message: "Cannot start backup with ID 'op-1' because there is another backup with the same ID.", + }) + + Expect(isDuplicateOperationID(err)).To(BeTrue()) + }) + + It("should not match other errors", func() { + Expect(isDuplicateOperationID(&clickhouse.Exception{Code: codeBadArguments, Message: "Unknown setting"})).To(BeFalse()) + Expect(isDuplicateOperationID(&clickhouse.Exception{Code: 598, Message: "Backup already exists"})).To(BeFalse()) + Expect(isDuplicateOperationID(errors.New("connection refused"))).To(BeFalse()) + }) +}) + +var _ = Describe("backup error helpers", func() { + It("should drop the stack trace from the error", func() { + message := "Code: 499. DB::Exception: The specified bucket does not exist. (S3_ERROR), Stack trace (when copying):\n\n0. DB::Exception" + + Expect(errorSummary(message)).To(Equal("Code: 499. DB::Exception: The specified bucket does not exist. (S3_ERROR)")) + }) + + It("should limit the size of the error", func() { + message := make([]byte, 2*maxBackupMessageLength) + for i := range message { + message[i] = 'a' + } + + Expect(errorSummary(string(message))).To(HaveLen(maxBackupMessageLength + len("..."))) + }) + + It("should hide the storage credentials", func() { + stmt := backupStatement{ + Location: s3Location{URL: "u", AccessKeyID: "key", SecretAccessKey: "sec'ret"}, + Base: &s3Location{URL: "b", AccessKeyID: "key", SecretAccessKey: "base-secret"}, + } + + Expect(redactSecrets(`failed at S3('u', 'key', 'sec\'ret') and sec'ret with S3('b', 'key', 'base-secret')`, stmt)).To(Equal( + "failed at S3('u', 'key', '[HIDDEN]') and [HIDDEN] with S3('b', 'key', '[HIDDEN]')")) + }) +}) diff --git a/internal/controller/clickhouse/backup_controller.go b/internal/controller/clickhouse/backup_controller.go new file mode 100644 index 000000000..159b815f8 --- /dev/null +++ b/internal/controller/clickhouse/backup_controller.go @@ -0,0 +1,657 @@ +package clickhouse + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + "github.com/ClickHouse/clickhouse-go/v2" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/tools/events" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" + "sigs.k8s.io/controller-runtime/pkg/predicate" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + chctrl "github.com/ClickHouse/clickhouse-operator/internal/controller" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +const ( + // backupPollInterval is the interval between the checks of a running operation. + backupPollInterval = 10 * time.Second + // backupWaitInterval is the interval between the checks of the dependencies an operation waits for. + backupWaitInterval = 30 * time.Second + // maxBackupMessageLength limits the size of the error reported in the status. + maxBackupMessageLength = 2048 + + hiddenSecret = "[HIDDEN]" +) + +// backupExecutor runs backup operations on the replicas of a cluster. +type backupExecutor interface { + Ping(ctx context.Context, id v1.ClickHouseReplicaID) error + HasSetting(ctx context.Context, id v1.ClickHouseReplicaID, name string) (bool, error) + StartBackupOperation(ctx context.Context, id v1.ClickHouseReplicaID, query string) error + BackupOperationState(ctx context.Context, id v1.ClickHouseReplicaID, operationID string) (backupOperationState, bool, error) +} + +// backupExecutorFactory creates the executor for a cluster with the credentials stored in the cluster secret. +type backupExecutorFactory func(log controllerutil.Logger, cluster *v1.ClickHouseCluster, secret *corev1.Secret) backupExecutor + +// BackupController reconciles ClickHouseBackup and ClickHouseRestore objects. +// Both are one-shot operations executed by ClickHouse itself: the controller submits +// an asynchronous statement to one replica and follows it until it finishes. +type BackupController struct { + client.Client + + Logger controllerutil.Logger + Recorder events.EventRecorder + NewExecutor backupExecutorFactory +} + +// backupBlocker explains why an operation cannot be started. +type backupBlocker struct { + Reason v1.ConditionReason + Message string + // Terminal blockers fail the operation, other ones are retried. + Terminal bool +} + +// backupOperation adapts ClickHouseBackup and ClickHouseRestore to the shared reconciliation flow. +type backupOperation struct { + Object client.Object + Status *v1.BackupOperationStatus + ClusterName string + Restore bool + // Plan builds the statement. A returned blocker means that the operation cannot be started now. + Plan func(ctx context.Context) (backupStatement, *backupBlocker, error) + // Finish stores the final operation metrics in the status. + Finish func(state backupOperationState) +} + +func (o *backupOperation) startedEvent() (v1.EventReason, v1.EventAction) { + if o.Restore { + return v1.EventReasonRestoreStarted, v1.EventActionRestore + } + + return v1.EventReasonBackupStarted, v1.EventActionBackup +} + +func (o *backupOperation) completedEvent() (v1.EventReason, v1.EventAction) { + if o.Restore { + return v1.EventReasonRestoreCompleted, v1.EventActionRestore + } + + return v1.EventReasonBackupCompleted, v1.EventActionBackup +} + +func (o *backupOperation) failedEvent() (v1.EventReason, v1.EventAction) { + if o.Restore { + return v1.EventReasonRestoreFailed, v1.EventActionRestore + } + + return v1.EventReasonBackupFailed, v1.EventActionBackup +} + +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousebackups;clickhouserestores,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousebackups/status;clickhouserestores/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousebackups/finalizers;clickhouserestores/finalizers,verbs=update + +type backupReconciler struct { + *BackupController +} + +// Reconcile moves a ClickHouseBackup towards completion. +func (r backupReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + backup := &v1.ClickHouseBackup{} + if err := r.Get(ctx, req.NamespacedName, backup); err != nil { + if k8serrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + + return ctrl.Result{}, fmt.Errorf("get ClickHouseBackup %s: %w", req.String(), err) + } + + return r.reconcileOperation(ctx, r.Logger.WithContext(ctx, backup), &backupOperation{ + Object: backup, + Status: &backup.Status.BackupOperationStatus, + ClusterName: backup.Spec.ClusterRef.Name, + Plan: func(ctx context.Context) (backupStatement, *backupBlocker, error) { + return r.planBackup(ctx, backup) + }, + Finish: func(state backupOperationState) { + backup.Status.NumFiles = int64(state.NumFiles) //nolint:gosec // sizes never overflow int64 + backup.Status.TotalSize = int64(state.TotalSize) //nolint:gosec // sizes never overflow int64 + backup.Status.CompressedSize = int64(state.CompressedSize) //nolint:gosec // sizes never overflow int64 + }, + }) +} + +func (r backupReconciler) planBackup(ctx context.Context, backup *v1.ClickHouseBackup) (backupStatement, *backupBlocker, error) { + location, blocker, err := r.resolveLocation(ctx, backup.Namespace, backup.Spec.Storage, backup.Name) + if blocker != nil || err != nil { + return backupStatement{}, blocker, err + } + + stmt := backupStatement{ + Scope: backup.Spec.Scope, + Location: location, + Settings: backup.Spec.Settings, + } + + if backup.Spec.BaseBackupRef != nil { + base, blocker, err := r.resolveBackup(ctx, backup.Namespace, backup.Spec.BaseBackupRef.Name) + if blocker != nil || err != nil { + return backupStatement{}, blocker, err + } + + stmt.Base = &base + backup.Status.BaseLocation = base.URL + } + + return stmt, nil, nil +} + +type restoreReconciler struct { + *BackupController +} + +// Reconcile moves a ClickHouseRestore towards completion. +func (r restoreReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + restore := &v1.ClickHouseRestore{} + if err := r.Get(ctx, req.NamespacedName, restore); err != nil { + if k8serrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + + return ctrl.Result{}, fmt.Errorf("get ClickHouseRestore %s: %w", req.String(), err) + } + + return r.reconcileOperation(ctx, r.Logger.WithContext(ctx, restore), &backupOperation{ + Object: restore, + Status: &restore.Status.BackupOperationStatus, + ClusterName: restore.Spec.ClusterRef.Name, + Restore: true, + Plan: func(ctx context.Context) (backupStatement, *backupBlocker, error) { + return r.planRestore(ctx, restore) + }, + Finish: func(backupOperationState) {}, + }) +} + +func (r restoreReconciler) planRestore(ctx context.Context, restore *v1.ClickHouseRestore) (backupStatement, *backupBlocker, error) { + var ( + location s3Location + blocker *backupBlocker + err error + ) + + switch { + case restore.Spec.BackupRef != nil: + location, blocker, err = r.resolveBackup(ctx, restore.Namespace, restore.Spec.BackupRef.Name) + case restore.Spec.Source != nil: + location, blocker, err = r.resolveLocation(ctx, restore.Namespace, restore.Spec.Source.Storage, restore.Spec.Source.Name) + default: + blocker = &backupBlocker{ + Reason: v1.BackupConditionReasonBackupNotFound, + Message: "neither backupRef nor source is set", + Terminal: true, + } + } + + if blocker != nil || err != nil { + return backupStatement{}, blocker, err + } + + return backupStatement{ + Restore: true, + Scope: restore.Spec.Scope, + Location: location, + Settings: restore.Spec.Settings, + }, nil, nil +} + +// resolveBackup returns the location of a completed ClickHouseBackup. +func (c *BackupController) resolveBackup(ctx context.Context, namespace, name string) (s3Location, *backupBlocker, error) { + backup := &v1.ClickHouseBackup{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, backup); err != nil { + if k8serrors.IsNotFound(err) { + return s3Location{}, &backupBlocker{ + Reason: v1.BackupConditionReasonBackupNotFound, + Message: fmt.Sprintf("ClickHouseBackup %q is not found", name), + }, nil + } + + return s3Location{}, nil, fmt.Errorf("get ClickHouseBackup %s/%s: %w", namespace, name, err) + } + + switch backup.Status.Phase { + case v1.BackupPhaseCompleted: + case v1.BackupPhaseFailed: + return s3Location{}, &backupBlocker{ + Reason: v1.BackupConditionReasonBackupFailed, + Message: fmt.Sprintf("ClickHouseBackup %q failed", name), + Terminal: true, + }, nil + + case v1.BackupPhasePending, v1.BackupPhaseRunning: + fallthrough + default: + return s3Location{}, &backupBlocker{ + Reason: v1.BackupConditionReasonBackupNotCompleted, + Message: fmt.Sprintf("ClickHouseBackup %q is not completed yet", name), + }, nil + } + + location, blocker, err := c.resolveLocation(ctx, namespace, backup.Spec.Storage, backup.Name) + if blocker != nil || err != nil { + return s3Location{}, blocker, err + } + + // The backup stays where it was written even if the resource naming rules change. + location.URL = backup.Status.Location + + return location, nil, nil +} + +// resolveLocation builds the location of the named backup and loads the storage credentials. +func (c *BackupController) resolveLocation( + ctx context.Context, + namespace string, + storage v1.BackupStorage, + name string, +) (s3Location, *backupBlocker, error) { + if storage.S3 == nil { + return s3Location{}, &backupBlocker{ + Reason: v1.BackupConditionReasonCredentialsInvalid, + Message: "storage is not configured", + Terminal: true, + }, nil + } + + location := s3Location{URL: storage.S3.Location(name)} + if storage.S3.Credentials == nil { + return location, nil, nil + } + + for _, ref := range []struct { + selector v1.SecretKeySelector + target *string + }{ + {storage.S3.Credentials.AccessKeyID, &location.AccessKeyID}, + {storage.S3.Credentials.SecretAccessKey, &location.SecretAccessKey}, + } { + value, blocker, err := c.secretValue(ctx, namespace, ref.selector) + if blocker != nil || err != nil { + return s3Location{}, blocker, err + } + + *ref.target = value + } + + return location, nil, nil +} + +func (c *BackupController) secretValue( + ctx context.Context, + namespace string, + selector v1.SecretKeySelector, +) (string, *backupBlocker, error) { + secret := &corev1.Secret{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: selector.Name}, secret); err != nil { + if k8serrors.IsNotFound(err) { + return "", &backupBlocker{ + Reason: v1.BackupConditionReasonCredentialsInvalid, + Message: fmt.Sprintf("Secret %q is not found", selector.Name), + }, nil + } + + return "", nil, fmt.Errorf("get Secret %s/%s: %w", namespace, selector.Name, err) + } + + value := string(secret.Data[selector.Key]) + if value == "" { + return "", &backupBlocker{ + Reason: v1.BackupConditionReasonCredentialsInvalid, + Message: fmt.Sprintf("Secret %q has no value for key %q", selector.Name, selector.Key), + }, nil + } + + return value, nil, nil +} + +func (c *BackupController) reconcileOperation(ctx context.Context, log controllerutil.Logger, op *backupOperation) (ctrl.Result, error) { + if op.Status.Phase.Finished() || !op.Object.GetDeletionTimestamp().IsZero() { + return ctrl.Result{}, nil + } + + namespace := op.Object.GetNamespace() + started := op.Status.ID != "" + + cluster := &v1.ClickHouseCluster{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: op.ClusterName}, cluster); err != nil { + if !k8serrors.IsNotFound(err) { + return ctrl.Result{}, fmt.Errorf("get ClickHouseCluster %s/%s: %w", namespace, op.ClusterName, err) + } + + if started { + return c.fail(ctx, op, v1.BackupConditionReasonStateLost, + fmt.Sprintf("ClickHouseCluster %q was deleted while the operation was running", op.ClusterName)) + } + + return c.wait(ctx, op, v1.BackupConditionReasonClusterNotFound, + fmt.Sprintf("ClickHouseCluster %q is not found", op.ClusterName)) + } + + secret := &corev1.Secret{} + if err := c.Get(ctx, types.NamespacedName{Namespace: namespace, Name: cluster.SecretName()}, secret); err != nil { + if !k8serrors.IsNotFound(err) { + return ctrl.Result{}, fmt.Errorf("get cluster secret %s/%s: %w", namespace, cluster.SecretName(), err) + } + + if started { + log.Warn("cluster secret is not found, operation state cannot be checked") + + return ctrl.Result{RequeueAfter: backupPollInterval}, nil + } + + return c.wait(ctx, op, v1.BackupConditionReasonClusterNotReady, "cluster secret is not created yet") + } + + executor := c.NewExecutor(log, cluster, secret) + + if !started { + return c.start(ctx, log, op, cluster, executor) + } + + return c.poll(ctx, log, op, cluster, executor) +} + +// start submits the operation to the first reachable replica. +func (c *BackupController) start( + ctx context.Context, + log controllerutil.Logger, + op *backupOperation, + cluster *v1.ClickHouseCluster, + executor backupExecutor, +) (ctrl.Result, error) { + stmt, blocker, err := op.Plan(ctx) + if err != nil { + return ctrl.Result{}, err + } + + if blocker != nil { + if blocker.Terminal { + return c.fail(ctx, op, blocker.Reason, blocker.Message) + } + + return c.wait(ctx, op, blocker.Reason, blocker.Message) + } + + replica, ok := pickBackupReplica(ctx, cluster, executor) + if !ok { + return c.wait(ctx, op, v1.BackupConditionReasonClusterNotReady, "no replica of the cluster is reachable") + } + + if stmt.usesServerCredentials() { + stmt.AllowServerCredentials, err = executor.HasSetting(ctx, replica, settingAllowServerCredentials) + if err != nil { + return ctrl.Result{}, fmt.Errorf("check server credentials setting: %w", err) + } + } + + // The object UID makes the submission idempotent: a repeated statement is rejected by the replica. + stmt.ID = string(op.Object.GetUID()) + + if err := executor.StartBackupOperation(ctx, replica, stmt.SQL()); err != nil { + if exc, ok := errors.AsType[*clickhouse.Exception](err); ok { + return c.fail(ctx, op, v1.BackupConditionReasonFailed, redactSecrets(exc.Message, stmt)) + } + + return ctrl.Result{}, fmt.Errorf("start operation: %w", errors.New(redactSecrets(err.Error(), stmt))) + } + + log.Info("operation started", "operation_id", stmt.ID, "replica_id", replica, "location", stmt.Location.URL) + + now := metav1.Now() + op.Status.ID = stmt.ID + op.Status.Replica = &v1.BackupReplica{ShardID: replica.ShardID, Index: replica.Index} + op.Status.Location = stmt.Location.URL + op.Status.StartTime = &now + op.Status.Phase = v1.BackupPhaseRunning + c.setCompleted(op, metav1.ConditionFalse, v1.BackupConditionReasonInProgress, "") + + if err := c.Status().Update(ctx, op.Object); err != nil { + return ctrl.Result{}, fmt.Errorf("update status: %w", err) + } + + reason, action := op.startedEvent() + c.Recorder.Eventf(op.Object, nil, corev1.EventTypeNormal, reason, action, "Started on replica %s", replica) + + return ctrl.Result{RequeueAfter: backupPollInterval}, nil +} + +// poll follows a submitted operation until it reaches a final state. +func (c *BackupController) poll( + ctx context.Context, + log controllerutil.Logger, + op *backupOperation, + cluster *v1.ClickHouseCluster, + executor backupExecutor, +) (ctrl.Result, error) { + if op.Status.Replica == nil { + return c.fail(ctx, op, v1.BackupConditionReasonStateLost, "replica that executes the operation is unknown") + } + + replica := v1.ClickHouseReplicaID{ShardID: op.Status.Replica.ShardID, Index: op.Status.Replica.Index} + if replica.ShardID >= cluster.Shards() || replica.Index >= cluster.Replicas() { + return c.fail(ctx, op, v1.BackupConditionReasonStateLost, + fmt.Sprintf("replica %s that executed the operation was removed from the cluster", replica)) + } + + stateCtx, cancel := context.WithTimeout(ctx, chctrl.LoadReplicaStateTimeout) + defer cancel() + + state, found, err := executor.BackupOperationState(stateCtx, replica, op.Status.ID) + if err != nil { + // The replica may be restarting: the operation state is checked again once it is back. + log.Warn("failed to read operation state", "replica_id", replica, "error", err) + + return ctrl.Result{RequeueAfter: backupPollInterval}, nil + } + + switch { + case !found: + return c.fail(ctx, op, v1.BackupConditionReasonStateLost, + fmt.Sprintf("replica %s does not know the operation: the server was restarted while it was running", replica)) + case state.running(): + return ctrl.Result{RequeueAfter: backupPollInterval}, nil + case state.succeeded(): + return c.complete(ctx, log, op, state) + default: + return c.fail(ctx, op, v1.BackupConditionReasonFailed, fmt.Sprintf("%s: %s", state.Status, errorSummary(state.Error))) + } +} + +func (c *BackupController) complete( + ctx context.Context, + log controllerutil.Logger, + op *backupOperation, + state backupOperationState, +) (ctrl.Result, error) { + now := metav1.Now() + op.Status.Phase = v1.BackupPhaseCompleted + op.Status.CompletionTime = &now + op.Finish(state) + c.setCompleted(op, metav1.ConditionTrue, v1.BackupConditionReasonSucceeded, "") + + if err := c.Status().Update(ctx, op.Object); err != nil { + return ctrl.Result{}, fmt.Errorf("update status: %w", err) + } + + log.Info("operation completed", "operation_id", op.Status.ID) + + reason, action := op.completedEvent() + c.Recorder.Eventf(op.Object, nil, corev1.EventTypeNormal, reason, action, "Completed at %s", op.Status.Location) + + return ctrl.Result{}, nil +} + +// fail marks the operation as failed. Failed operations are never retried. +func (c *BackupController) fail( + ctx context.Context, + op *backupOperation, + reason v1.ConditionReason, + message string, +) (ctrl.Result, error) { + now := metav1.Now() + op.Status.Phase = v1.BackupPhaseFailed + op.Status.CompletionTime = &now + c.setCompleted(op, metav1.ConditionFalse, reason, message) + + if err := c.Status().Update(ctx, op.Object); err != nil { + return ctrl.Result{}, fmt.Errorf("update status: %w", err) + } + + eventReason, action := op.failedEvent() + c.Recorder.Eventf(op.Object, nil, corev1.EventTypeWarning, eventReason, action, "%s: %s", reason, message) + + return ctrl.Result{}, nil +} + +// wait reports why the operation is not started yet and schedules the next check. +func (c *BackupController) wait( + ctx context.Context, + op *backupOperation, + reason v1.ConditionReason, + message string, +) (ctrl.Result, error) { + current := meta.FindStatusCondition(op.Status.Conditions, v1.BackupConditionTypeCompleted) + if op.Status.Phase == v1.BackupPhasePending && current != nil && current.Reason == reason && current.Message == message { + return ctrl.Result{RequeueAfter: backupWaitInterval}, nil + } + + op.Status.Phase = v1.BackupPhasePending + c.setCompleted(op, metav1.ConditionFalse, reason, message) + + if err := c.Status().Update(ctx, op.Object); err != nil { + return ctrl.Result{}, fmt.Errorf("update status: %w", err) + } + + return ctrl.Result{RequeueAfter: backupWaitInterval}, nil +} + +func (*BackupController) setCompleted(op *backupOperation, status metav1.ConditionStatus, reason v1.ConditionReason, message string) { + chctrl.SetStatusCondition(&op.Status.Conditions, metav1.Condition{ + Type: v1.BackupConditionTypeCompleted, + Status: status, + Reason: reason, + Message: message, + ObservedGeneration: op.Object.GetGeneration(), + }) +} + +// pickBackupReplica returns the first replica that accepts connections. +// The order is stable, so a repeated submission reaches the replica that already knows the operation. +func pickBackupReplica(ctx context.Context, cluster *v1.ClickHouseCluster, executor backupExecutor) (v1.ClickHouseReplicaID, bool) { + for id := range cluster.ReplicaIDs() { + pingCtx, cancel := context.WithTimeout(ctx, chctrl.LoadReplicaStateTimeout) + err := executor.Ping(pingCtx, id) + + cancel() + + if err == nil { + return id, true + } + } + + return v1.ClickHouseReplicaID{}, false +} + +// errorSummary drops the stack trace ClickHouse appends to the stored error and limits the message size. +func errorSummary(message string) string { + if idx := strings.Index(message, ", Stack trace"); idx >= 0 { + message = message[:idx] + } + + message = strings.TrimSpace(message) + if len(message) > maxBackupMessageLength { + message = strings.ToValidUTF8(message[:maxBackupMessageLength], "") + "..." + } + + return message +} + +// redactSecrets removes the storage credentials from a message that may quote the statement. +func redactSecrets(message string, stmt backupStatement) string { + locations := []s3Location{stmt.Location} + if stmt.Base != nil { + locations = append(locations, *stmt.Base) + } + + for _, location := range locations { + if location.SecretAccessKey == "" { + continue + } + + message = strings.ReplaceAll(message, location.SecretAccessKey, hiddenSecret) + message = strings.ReplaceAll(message, stringEscaper.Replace(location.SecretAccessKey), hiddenSecret) + } + + return errorSummary(message) +} + +// setupBackupControllers registers the controllers of the backup resources. +func setupBackupControllers(mgr ctrl.Manager, deps chctrl.Dependencies, settings chctrl.Settings, cache *connCache) error { + backupController := &BackupController{ + Client: mgr.GetClient(), + Logger: deps.Logger.Named("backup"), + Recorder: mgr.GetEventRecorder("clickhouse-backup-controller"), + NewExecutor: func(log controllerutil.Logger, cluster *v1.ClickHouseCluster, secret *corev1.Secret) backupExecutor { + return newCommander(log, cluster, secret, deps.Dialer, cache) + }, + } + + options := controller.Options{MaxConcurrentReconciles: settings.MaxConcurrentReconciles} + + if err := ctrl.NewControllerManagedBy(mgr). + WithOptions(options). + For(&v1.ClickHouseBackup{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Complete(backupReconciler{backupController}); err != nil { + return fmt.Errorf("setup ClickHouseBackup controller: %w", err) + } + + if err := ctrl.NewControllerManagedBy(mgr). + WithOptions(options). + For(&v1.ClickHouseRestore{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Complete(restoreReconciler{backupController}); err != nil { + return fmt.Errorf("setup ClickHouseRestore controller: %w", err) + } + + scheduledController := &ScheduledBackupController{ + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + Logger: deps.Logger.Named("scheduled-backup"), + Recorder: mgr.GetEventRecorder("clickhouse-scheduled-backup-controller"), + Now: time.Now, + } + + if err := ctrl.NewControllerManagedBy(mgr). + WithOptions(options). + For(&v1.ClickHouseScheduledBackup{}, builder.WithPredicates(predicate.GenerationChangedPredicate{})). + Owns(&v1.ClickHouseBackup{}). + Complete(scheduledController); err != nil { + return fmt.Errorf("setup ClickHouseScheduledBackup controller: %w", err) + } + + return nil +} diff --git a/internal/controller/clickhouse/backup_controller_test.go b/internal/controller/clickhouse/backup_controller_test.go new file mode 100644 index 000000000..28aa2f243 --- /dev/null +++ b/internal/controller/clickhouse/backup_controller_test.go @@ -0,0 +1,871 @@ +package clickhouse + +import ( + "context" + "errors" + "sync" + "time" + + "github.com/ClickHouse/clickhouse-go/v2" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/events" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + "github.com/ClickHouse/clickhouse-operator/internal/controller/testutil" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +// fakeBackupExecutor records the submitted statements and reports the configured operation states. +type fakeBackupExecutor struct { + mu sync.Mutex + + unreachable bool + hasSetting bool + startErr error + stateErr error + queries []string + replicas []v1.ClickHouseReplicaID + states map[string]backupOperationState +} + +func (f *fakeBackupExecutor) Ping(context.Context, v1.ClickHouseReplicaID) error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.unreachable { + return errors.New("unreachable") + } + + return nil +} + +func (f *fakeBackupExecutor) HasSetting(context.Context, v1.ClickHouseReplicaID, string) (bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + + return f.hasSetting, nil +} + +func (f *fakeBackupExecutor) StartBackupOperation(_ context.Context, id v1.ClickHouseReplicaID, query string) error { + f.mu.Lock() + defer f.mu.Unlock() + + if f.startErr != nil { + return f.startErr + } + + f.queries = append(f.queries, query) + f.replicas = append(f.replicas, id) + + return nil +} + +func (f *fakeBackupExecutor) BackupOperationState( + _ context.Context, + _ v1.ClickHouseReplicaID, + operationID string, +) (backupOperationState, bool, error) { + f.mu.Lock() + defer f.mu.Unlock() + + if f.stateErr != nil { + return backupOperationState{}, false, f.stateErr + } + + state, ok := f.states[operationID] + + return state, ok, nil +} + +func (f *fakeBackupExecutor) setState(operationID string, state backupOperationState) { + f.mu.Lock() + defer f.mu.Unlock() + + f.states[operationID] = state +} + +func (f *fakeBackupExecutor) lastQuery() string { + f.mu.Lock() + defer f.mu.Unlock() + + if len(f.queries) == 0 { + return "" + } + + return f.queries[len(f.queries)-1] +} + +var _ = When("reconciling backup resources", Ordered, func() { + const ( + namespace = "default" + clusterName = "backup-cluster" + credentialsName = "backup-storage-access" + endpoint = "https://bucket.s3.amazonaws.com/backups" + ) + + var ( + suite testutil.TestSuit + recorder *events.FakeRecorder + executor *fakeBackupExecutor + controller *BackupController + storage v1.BackupStorage + ) + + reconcileBackup := func(ctx context.Context, backup *v1.ClickHouseBackup) ctrl.Result { + GinkgoHelper() + + result, err := backupReconciler{controller}.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(backup)}) + Expect(err).NotTo(HaveOccurred()) + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(backup), backup)).To(Succeed()) + + return result + } + + reconcileRestore := func(ctx context.Context, restore *v1.ClickHouseRestore) ctrl.Result { + GinkgoHelper() + + result, err := restoreReconciler{controller}.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(restore)}) + Expect(err).NotTo(HaveOccurred()) + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(restore), restore)).To(Succeed()) + + return result + } + + newBackup := func(ctx context.Context, name string, mutate ...func(*v1.ClickHouseBackup)) *v1.ClickHouseBackup { + GinkgoHelper() + + backup := &v1.ClickHouseBackup{ + Name: name, Namespace: namespace, + Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: clusterName}, + Storage: storage, + }, + } + for _, fn := range mutate { + fn(backup) + } + + Expect(suite.Client.Create(ctx, backup)).To(Succeed()) + + return backup + } + + completeBackup := func(ctx context.Context, backup *v1.ClickHouseBackup) { + GinkgoHelper() + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + executor.setState(backup.Status.ID, backupOperationState{Status: backupStatusCreated}) + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseCompleted)) + } + + completedCondition := func(conditions []metav1.Condition) metav1.Condition { + GinkgoHelper() + + cond := meta.FindStatusCondition(conditions, v1.BackupConditionTypeCompleted) + Expect(cond).NotTo(BeNil()) + + return *cond + } + + BeforeAll(func(ctx context.Context) { + suite = testutil.SetupEnvironment(v1.AddToScheme) + + cluster := &v1.ClickHouseCluster{ + Name: clusterName, Namespace: namespace, + Spec: v1.ClickHouseClusterSpec{ + Replicas: new(int32(2)), + Shards: new(int32(1)), + KeeperClusterRef: &v1.KeeperClusterReference{Name: "keeper"}, + }, + } + Expect(suite.Client.Create(ctx, cluster)).To(Succeed()) + + Expect(suite.Client.Create(ctx, &corev1.Secret{ + Name: cluster.SecretName(), Namespace: namespace, + Data: map[string][]byte{SecretKeyManagementPassword: []byte("password")}, + })).To(Succeed()) + + Expect(suite.Client.Create(ctx, &corev1.Secret{ + Name: credentialsName, Namespace: namespace, + Data: map[string][]byte{"id": []byte("access-key"), "secret": []byte("secret-key")}, + })).To(Succeed()) + + storage = v1.BackupStorage{S3: &v1.S3BackupStorage{ + Endpoint: endpoint, + Credentials: &v1.S3Credentials{ + AccessKeyID: v1.SecretKeySelector{Name: credentialsName, Key: "id"}, + SecretAccessKey: v1.SecretKeySelector{Name: credentialsName, Key: "secret"}, + }, + }} + }) + + AfterAll(func() { + By("tearing down the test environment") + + Expect(suite.TestEnv.Stop()).To(Succeed()) + }) + + BeforeEach(func() { + recorder = events.NewFakeRecorder(64) + executor = &fakeBackupExecutor{states: map[string]backupOperationState{}} + controller = &BackupController{ + Client: suite.Client, + Logger: suite.Log.Named("backup"), + Recorder: recorder, + NewExecutor: func(controllerutil.Logger, *v1.ClickHouseCluster, *corev1.Secret) backupExecutor { + return executor + }, + } + }) + + Describe("ClickHouseBackup", func() { + It("should run a backup to completion", func(ctx context.Context) { + backup := newBackup(ctx, "full") + + By("submitting the statement to the first replica") + + result := reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupPollInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(backup.Status.ID).To(Equal(string(backup.UID))) + Expect(backup.Status.Replica).To(Equal(&v1.BackupReplica{ShardID: 0, Index: 0})) + Expect(backup.Status.Location).To(Equal(endpoint + "/full")) + Expect(backup.Status.StartTime).NotTo(BeNil()) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonInProgress)) + Expect(executor.lastQuery()).To(Equal( + "BACKUP ALL EXCEPT DATABASES system ON CLUSTER 'default' " + + "TO S3('https://bucket.s3.amazonaws.com/backups/full', 'access-key', 'secret-key') " + + "SETTINGS id = '" + string(backup.UID) + "' ASYNC")) + + By("waiting while the backup is created") + + executor.setState(backup.Status.ID, backupOperationState{Status: backupStatusCreating}) + result = reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupPollInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + By("recording the result") + + executor.setState(backup.Status.ID, backupOperationState{ + Status: backupStatusCreated, NumFiles: 12, TotalSize: 2048, CompressedSize: 1024, + }) + result = reconcileBackup(ctx, backup) + Expect(result.IsZero()).To(BeTrue()) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseCompleted)) + Expect(backup.Status.CompletionTime).NotTo(BeNil()) + Expect(backup.Status.NumFiles).To(BeEquivalentTo(12)) + Expect(backup.Status.TotalSize).To(BeEquivalentTo(2048)) + Expect(backup.Status.CompressedSize).To(BeEquivalentTo(1024)) + Expect(completedCondition(backup.Status.Conditions).Status).To(Equal(metav1.ConditionTrue)) + testutil.AssertEvents(recorder.Events, map[string]int{ + v1.EventReasonBackupStarted: 1, + v1.EventReasonBackupCompleted: 1, + }) + + By("leaving the finished backup untouched") + + executor.setState(backup.Status.ID, backupOperationState{Status: "BACKUP_FAILED"}) + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseCompleted)) + Expect(executor.queries).To(HaveLen(1)) + }) + + It("should wait for the cluster", func(ctx context.Context) { + backup := newBackup(ctx, "no-cluster", func(b *v1.ClickHouseBackup) { + b.Spec.ClusterRef.Name = "missing" + }) + + result := reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupWaitInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonClusterNotFound)) + Expect(executor.queries).To(BeEmpty()) + }) + + It("should wait for a reachable replica", func(ctx context.Context) { + backup := newBackup(ctx, "unreachable") + executor.unreachable = true + + result := reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupWaitInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonClusterNotReady)) + + executor.unreachable = false + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + }) + + It("should wait for the storage credentials", func(ctx context.Context) { + backup := newBackup(ctx, "no-credentials", func(b *v1.ClickHouseBackup) { + b.Spec.Storage.S3 = b.Spec.Storage.S3.DeepCopy() + b.Spec.Storage.S3.Credentials.SecretAccessKey.Key = "missing" + }) + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonCredentialsInvalid)) + Expect(executor.queries).To(BeEmpty()) + }) + + It("should use the server credentials when none are configured", func(ctx context.Context) { + executor.hasSetting = true + backup := newBackup(ctx, "server-credentials", func(b *v1.ClickHouseBackup) { + b.Spec.Storage = v1.BackupStorage{S3: &v1.S3BackupStorage{Endpoint: endpoint + "/"}} + b.Spec.Scope = &v1.BackupScope{Databases: []string{"analytics"}} + b.Spec.Settings = map[string]string{"compression_method": "zstd"} + }) + + reconcileBackup(ctx, backup) + Expect(executor.lastQuery()).To(Equal( + "BACKUP DATABASE `analytics` ON CLUSTER 'default' " + + "TO S3('https://bucket.s3.amazonaws.com/backups/server-credentials') " + + "SETTINGS id = '" + string(backup.UID) + "', compression_method = 'zstd', " + + "s3_allow_server_credentials_in_user_queries = 1 ASYNC")) + }) + + It("should fail when ClickHouse reports a failure", func(ctx context.Context) { + backup := newBackup(ctx, "failed") + reconcileBackup(ctx, backup) + + executor.setState(backup.Status.ID, backupOperationState{ + Status: "BACKUP_FAILED", + Error: "Code: 499. DB::Exception: The specified bucket does not exist. (S3_ERROR), Stack trace (when copying):\n0. DB", + }) + result := reconcileBackup(ctx, backup) + Expect(result.IsZero()).To(BeTrue()) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + + cond := completedCondition(backup.Status.Conditions) + Expect(cond.Reason).To(Equal(v1.BackupConditionReasonFailed)) + Expect(cond.Message).To(Equal( + "BACKUP_FAILED: Code: 499. DB::Exception: The specified bucket does not exist. (S3_ERROR)")) + testutil.AssertEvents(recorder.Events, map[string]int{ + v1.EventReasonBackupStarted: 1, + v1.EventReasonBackupFailed: 1, + }) + }) + + It("should fail when the replica forgets the operation", func(ctx context.Context) { + backup := newBackup(ctx, "state-lost") + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonStateLost)) + }) + + It("should keep polling while the replica is unreachable", func(ctx context.Context) { + backup := newBackup(ctx, "replica-restart") + reconcileBackup(ctx, backup) + + executor.stateErr = errors.New("connection refused") + result := reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupPollInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + }) + + It("should fail when the cluster is deleted while the backup is running", func(ctx context.Context) { + cluster := &v1.ClickHouseCluster{ + Name: "short-lived", Namespace: namespace, + Spec: v1.ClickHouseClusterSpec{ + Replicas: new(int32(1)), + KeeperClusterRef: &v1.KeeperClusterReference{Name: "keeper"}, + }, + } + Expect(suite.Client.Create(ctx, cluster)).To(Succeed()) + Expect(suite.Client.Create(ctx, &corev1.Secret{ + Name: cluster.SecretName(), Namespace: namespace, + Data: map[string][]byte{SecretKeyManagementPassword: []byte("password")}, + })).To(Succeed()) + + backup := newBackup(ctx, "orphaned", func(b *v1.ClickHouseBackup) { + b.Spec.ClusterRef.Name = cluster.Name + }) + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + Expect(suite.Client.Delete(ctx, cluster)).To(Succeed()) + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + Expect(completedCondition(backup.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonStateLost)) + }) + + It("should fail without leaking credentials when the statement is rejected", func(ctx context.Context) { + backup := newBackup(ctx, "rejected") + executor.startErr = &clickhouse.Exception{ + Code: 598, + Message: "Backup S3('https://bucket.s3.amazonaws.com/backups/rejected', 'access-key', 'secret-key') already exists", + } + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + Expect(backup.Status.ID).To(BeEmpty()) + + cond := completedCondition(backup.Status.Conditions) + Expect(cond.Reason).To(Equal(v1.BackupConditionReasonFailed)) + Expect(cond.Message).To(ContainSubstring("already exists")) + Expect(cond.Message).NotTo(ContainSubstring("secret-key")) + }) + + It("should take an incremental backup once the base is completed", func(ctx context.Context) { + base := newBackup(ctx, "base") + incremental := newBackup(ctx, "incremental", func(b *v1.ClickHouseBackup) { + b.Spec.BaseBackupRef = &corev1.LocalObjectReference{Name: base.Name} + }) + + By("waiting for the base backup") + + reconcileBackup(ctx, incremental) + Expect(incremental.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(completedCondition(incremental.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonBackupNotCompleted)) + + completeBackup(ctx, base) + + By("referencing the base backup location") + + reconcileBackup(ctx, incremental) + Expect(incremental.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(incremental.Status.BaseLocation).To(Equal(endpoint + "/base")) + Expect(executor.lastQuery()).To(ContainSubstring( + "base_backup = S3('https://bucket.s3.amazonaws.com/backups/base', 'access-key', 'secret-key')")) + }) + + It("should fail an incremental backup whose base failed", func(ctx context.Context) { + base := newBackup(ctx, "failed-base") + reconcileBackup(ctx, base) + executor.setState(base.Status.ID, backupOperationState{Status: "BACKUP_FAILED", Error: "boom"}) + reconcileBackup(ctx, base) + + incremental := newBackup(ctx, "orphan-incremental", func(b *v1.ClickHouseBackup) { + b.Spec.BaseBackupRef = &corev1.LocalObjectReference{Name: base.Name} + }) + reconcileBackup(ctx, incremental) + Expect(incremental.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + Expect(completedCondition(incremental.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonBackupFailed)) + }) + + It("should reject invalid specs", func(ctx context.Context) { + By("changing the spec of a created backup") + + backup := newBackup(ctx, "immutable") + backup.Spec.ClusterRef.Name = "other" + Expect(suite.Client.Update(ctx, backup)).To(MatchError(ContainSubstring("spec is immutable"))) + + By("setting a managed setting") + + managed := &v1.ClickHouseBackup{ + Name: "managed-setting", Namespace: namespace, + Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: clusterName}, + Storage: storage, + Settings: map[string]string{"base_backup": "S3('x')"}, + }, + } + Expect(suite.Client.Create(ctx, managed)).To(MatchError(ContainSubstring("managed by the operator"))) + + By("using an invalid setting name") + + managed.Spec.Settings = map[string]string{"a = 1, b": "1"} + Expect(suite.Client.Create(ctx, managed)).To(MatchError(ContainSubstring("valid identifiers"))) + + By("omitting the storage type") + + managed.Spec.Settings = nil + managed.Spec.Storage = v1.BackupStorage{} + Expect(suite.Client.Create(ctx, managed)).To(MatchError(ContainSubstring("s3 storage must be set"))) + }) + }) + + Describe("ClickHouseRestore", func() { + newRestore := func(ctx context.Context, name string, mutate func(*v1.ClickHouseRestore)) *v1.ClickHouseRestore { + GinkgoHelper() + + restore := &v1.ClickHouseRestore{ + Name: name, Namespace: namespace, + Spec: v1.ClickHouseRestoreSpec{ClusterRef: corev1.LocalObjectReference{Name: clusterName}}, + } + mutate(restore) + Expect(suite.Client.Create(ctx, restore)).To(Succeed()) + + return restore + } + + It("should restore a completed backup", func(ctx context.Context) { + backup := newBackup(ctx, "to-restore") + restore := newRestore(ctx, "from-backup", func(r *v1.ClickHouseRestore) { + r.Spec.BackupRef = &corev1.LocalObjectReference{Name: backup.Name} + r.Spec.Settings = map[string]string{"allow_non_empty_tables": "true"} + }) + + By("waiting for the backup") + + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(completedCondition(restore.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonBackupNotCompleted)) + + completeBackup(ctx, backup) + testutil.AssertEvents(recorder.Events, map[string]int{ + v1.EventReasonBackupStarted: 1, + v1.EventReasonBackupCompleted: 1, + }) + + By("submitting the statement") + + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(restore.Status.Location).To(Equal(endpoint + "/to-restore")) + Expect(executor.lastQuery()).To(Equal( + "RESTORE ALL EXCEPT DATABASES system ON CLUSTER 'default' " + + "FROM S3('https://bucket.s3.amazonaws.com/backups/to-restore', 'access-key', 'secret-key') " + + "SETTINGS id = '" + string(restore.UID) + "', allow_non_empty_tables = true, " + + "use_same_s3_credentials_for_base_backup = 1 ASYNC")) + + By("recording the result") + + executor.setState(restore.Status.ID, backupOperationState{Status: backupStatusRestoring}) + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + executor.setState(restore.Status.ID, backupOperationState{Status: backupStatusRestored}) + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseCompleted)) + testutil.AssertEvents(recorder.Events, map[string]int{ + v1.EventReasonRestoreStarted: 1, + v1.EventReasonRestoreCompleted: 1, + }) + }) + + It("should restore a backup located in the storage", func(ctx context.Context) { + restore := newRestore(ctx, "from-source", func(r *v1.ClickHouseRestore) { + r.Spec.Source = &v1.RestoreSource{Storage: storage, Name: "other-cluster-backup"} + r.Spec.Scope = &v1.BackupScope{Tables: []v1.BackupTable{{Database: "default", Table: "events"}}} + }) + + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(executor.lastQuery()).To(HavePrefix( + "RESTORE TABLE `default`.`events` ON CLUSTER 'default' " + + "FROM S3('https://bucket.s3.amazonaws.com/backups/other-cluster-backup', 'access-key', 'secret-key')")) + + executor.setState(restore.Status.ID, backupOperationState{Status: "RESTORE_FAILED", Error: "table is not empty"}) + reconcileRestore(ctx, restore) + Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + Expect(completedCondition(restore.Status.Conditions).Message).To(Equal("RESTORE_FAILED: table is not empty")) + }) + + It("should require exactly one backup source", func(ctx context.Context) { + restore := &v1.ClickHouseRestore{ + Name: "no-source", Namespace: namespace, + Spec: v1.ClickHouseRestoreSpec{ClusterRef: corev1.LocalObjectReference{Name: clusterName}}, + } + Expect(suite.Client.Create(ctx, restore)).To(MatchError(ContainSubstring("exactly one of backupRef or source"))) + + restore.Spec.BackupRef = &corev1.LocalObjectReference{Name: "backup"} + restore.Spec.Source = &v1.RestoreSource{Storage: storage, Name: "backup"} + Expect(suite.Client.Create(ctx, restore)).To(MatchError(ContainSubstring("exactly one of backupRef or source"))) + }) + }) + + Describe("ClickHouseScheduledBackup", func() { + var ( + scheduler *ScheduledBackupController + now time.Time + ) + + reconcileScheduled := func(ctx context.Context, scheduled *v1.ClickHouseScheduledBackup) ctrl.Result { + GinkgoHelper() + + result, err := scheduler.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(scheduled)}) + Expect(err).NotTo(HaveOccurred()) + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(scheduled), scheduled)).To(Succeed()) + + return result + } + + newScheduled := func( + ctx context.Context, + name string, + mutate ...func(*v1.ClickHouseScheduledBackup), + ) *v1.ClickHouseScheduledBackup { + GinkgoHelper() + + scheduled := &v1.ClickHouseScheduledBackup{ + Name: name, Namespace: namespace, + Spec: v1.ClickHouseScheduledBackupSpec{ + Schedule: "0 * * * *", + Template: v1.ClickHouseBackupTemplate{Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: clusterName}, + Storage: storage, + }}, + }, + } + for _, fn := range mutate { + fn(scheduled) + } + + Expect(suite.Client.Create(ctx, scheduled)).To(Succeed()) + + // Start from the beginning of the hour after the creation to make the schedule deterministic. + now = scheduled.CreationTimestamp.Truncate(time.Hour).Add(time.Hour) + + return scheduled + } + + ownedBackups := func(ctx context.Context, scheduled *v1.ClickHouseScheduledBackup) []v1.ClickHouseBackup { + GinkgoHelper() + + backups, err := scheduler.ownedBackups(ctx, scheduled) + Expect(err).NotTo(HaveOccurred()) + + return backups + } + + // runBackup lets the schedule create the backup of the next hour and finishes it. + runBackup := func(ctx context.Context, scheduled *v1.ClickHouseScheduledBackup, succeed bool) *v1.ClickHouseBackup { + GinkgoHelper() + + reconcileScheduled(ctx, scheduled) + + backup := &v1.ClickHouseBackup{} + Expect(suite.Client.Get(ctx, types.NamespacedName{ + Namespace: namespace, + Name: scheduled.Status.LastBackupName, + }, backup)).To(Succeed()) + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + + status := backupStatusCreated + if !succeed { + status = "BACKUP_FAILED" + } + + executor.setState(backup.Status.ID, backupOperationState{Status: status}) + reconcileBackup(ctx, backup) + + now = now.Add(time.Hour) + + return backup + } + + BeforeEach(func() { + scheduler = &ScheduledBackupController{ + Client: suite.Client, + Scheme: clientgoscheme.Scheme, + Logger: suite.Log.Named("scheduled-backup"), + Recorder: recorder, + Now: func() time.Time { return now }, + } + }) + + It("should create backups on schedule", func(ctx context.Context) { + scheduled := newScheduled(ctx, "hourly") + + By("waiting for the first run") + + now = scheduled.CreationTimestamp.Time + result := reconcileScheduled(ctx, scheduled) + Expect(result.RequeueAfter).To(BeNumerically(">", 0)) + Expect(result.RequeueAfter).To(BeNumerically("<=", time.Hour)) + Expect(ownedBackups(ctx, scheduled)).To(BeEmpty()) + Expect(meta.IsStatusConditionTrue(scheduled.Status.Conditions, v1.ScheduledBackupConditionTypeScheduled)).To(BeTrue()) + + By("creating the backup of the due run") + + now = scheduled.CreationTimestamp.Truncate(time.Hour).Add(time.Hour + time.Minute) + due := now.Truncate(time.Hour) + result = reconcileScheduled(ctx, scheduled) + Expect(result.RequeueAfter).To(Equal(59 * time.Minute)) + Expect(scheduled.Status.LastScheduleTime.Time).To(BeTemporally("==", due)) + Expect(scheduled.Status.LastBackupName).To(Equal("hourly-" + due.UTC().Format(scheduledBackupNameTimeLayout))) + + backups := ownedBackups(ctx, scheduled) + Expect(backups).To(HaveLen(1)) + Expect(backups[0].Name).To(Equal(scheduled.Status.LastBackupName)) + Expect(backups[0].Spec.ClusterRef.Name).To(Equal(clusterName)) + Expect(backups[0].Spec.BaseBackupRef).To(BeNil()) + Expect(metav1.IsControlledBy(&backups[0], scheduled)).To(BeTrue()) + + By("not creating the same run twice") + + reconcileScheduled(ctx, scheduled) + Expect(ownedBackups(ctx, scheduled)).To(HaveLen(1)) + + By("skipping a run while the previous backup is not finished") + + now = now.Add(time.Hour) + + reconcileScheduled(ctx, scheduled) + Expect(ownedBackups(ctx, scheduled)).To(HaveLen(1)) + Expect(scheduled.Status.LastScheduleTime.Time).To(BeTemporally("==", due.Add(time.Hour))) + + By("recording the last successful backup") + + completeBackup(ctx, &backups[0]) + reconcileScheduled(ctx, scheduled) + Expect(scheduled.Status.LastSuccessfulBackupName).To(Equal(backups[0].Name)) + Expect(scheduled.Status.LastSuccessfulTime).NotTo(BeNil()) + }) + + It("should only run the most recent missed run", func(ctx context.Context) { + scheduled := newScheduled(ctx, "missed") + + now = now.Add(5*time.Hour + time.Minute) + + reconcileScheduled(ctx, scheduled) + Expect(ownedBackups(ctx, scheduled)).To(HaveLen(1)) + Expect(scheduled.Status.LastScheduleTime.Time).To(BeTemporally("==", now.Truncate(time.Hour))) + }) + + It("should not create backups while suspended", func(ctx context.Context) { + scheduled := newScheduled(ctx, "suspended", func(s *v1.ClickHouseScheduledBackup) { + s.Spec.Suspend = new(true) + }) + + result := reconcileScheduled(ctx, scheduled) + Expect(result.IsZero()).To(BeTrue()) + Expect(ownedBackups(ctx, scheduled)).To(BeEmpty()) + + cond := meta.FindStatusCondition(scheduled.Status.Conditions, v1.ScheduledBackupConditionTypeScheduled) + Expect(cond).NotTo(BeNil()) + Expect(cond.Reason).To(Equal(v1.ScheduledBackupConditionReasonSuspended)) + }) + + It("should report an invalid schedule", func(ctx context.Context) { + scheduled := newScheduled(ctx, "invalid", func(s *v1.ClickHouseScheduledBackup) { + s.Spec.Schedule = "every day" + }) + + result := reconcileScheduled(ctx, scheduled) + Expect(result.IsZero()).To(BeTrue()) + + cond := meta.FindStatusCondition(scheduled.Status.Conditions, v1.ScheduledBackupConditionTypeScheduled) + Expect(cond).NotTo(BeNil()) + Expect(cond.Reason).To(Equal(v1.ScheduledBackupConditionReasonInvalidSchedule)) + testutil.AssertEvents(recorder.Events, map[string]int{v1.EventReasonInvalidSchedule: 1}) + }) + + It("should alternate full and incremental backups", func(ctx context.Context) { + scheduled := newScheduled(ctx, "incremental", func(s *v1.ClickHouseScheduledBackup) { + s.Spec.FullBackupInterval = new(int32(3)) + }) + + first := runBackup(ctx, scheduled, true) + Expect(first.Spec.BaseBackupRef).To(BeNil()) + + for range 2 { + incremental := runBackup(ctx, scheduled, true) + Expect(incremental.Spec.BaseBackupRef).To(Equal(&corev1.LocalObjectReference{Name: first.Name})) + } + + By("retrying a failed full backup") + + failed := runBackup(ctx, scheduled, false) + Expect(failed.Spec.BaseBackupRef).To(BeNil()) + Expect(failed.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + + second := runBackup(ctx, scheduled, true) + Expect(second.Spec.BaseBackupRef).To(BeNil()) + + incremental := runBackup(ctx, scheduled, true) + Expect(incremental.Spec.BaseBackupRef).To(Equal(&corev1.LocalObjectReference{Name: second.Name})) + }) + + It("should prune the backups that exceed the history limits", func(ctx context.Context) { + scheduled := newScheduled(ctx, "pruned", func(s *v1.ClickHouseScheduledBackup) { + s.Spec.FullBackupInterval = new(int32(3)) + s.Spec.SuccessfulBackupsHistoryLimit = new(int32(2)) + s.Spec.FailedBackupsHistoryLimit = new(int32(1)) + }) + + names := func() []string { + GinkgoHelper() + + backups := ownedBackups(ctx, scheduled) + + result := make([]string, 0, len(backups)) + for _, backup := range backups { + result = append(result, backup.Name) + } + + return result + } + + full := runBackup(ctx, scheduled, true) + incremental1 := runBackup(ctx, scheduled, true) + incremental2 := runBackup(ctx, scheduled, true) + + By("keeping the base of the kept incremental backups") + + reconcileScheduled(ctx, scheduled) + Expect(names()).To(ContainElements(full.Name, incremental1.Name, incremental2.Name)) + Expect(names()).To(HaveLen(4)) + + By("keeping a limited number of failed backups") + + nextFull := &v1.ClickHouseBackup{} + Expect(suite.Client.Get(ctx, types.NamespacedName{ + Namespace: namespace, Name: scheduled.Status.LastBackupName, + }, nextFull)).To(Succeed()) + reconcileBackup(ctx, nextFull) + executor.setState(nextFull.Status.ID, backupOperationState{Status: "BACKUP_FAILED"}) + reconcileBackup(ctx, nextFull) + + now = now.Add(time.Hour) + + failed := runBackup(ctx, scheduled, false) + reconcileScheduled(ctx, scheduled) + Expect(names()).NotTo(ContainElement(nextFull.Name)) + Expect(names()).To(ContainElement(failed.Name)) + + By("dropping the old chain once a newer one fills the history") + + Expect(suite.Client.Get(ctx, types.NamespacedName{ + Namespace: namespace, Name: scheduled.Status.LastBackupName, + }, nextFull)).To(Succeed()) + completeBackup(ctx, nextFull) + + now = now.Add(time.Hour) + + newIncremental := runBackup(ctx, scheduled, true) + Expect(newIncremental.Spec.BaseBackupRef).To(Equal(&corev1.LocalObjectReference{Name: nextFull.Name})) + + reconcileScheduled(ctx, scheduled) + Expect(names()).NotTo(ContainElements(full.Name, incremental1.Name, incremental2.Name)) + Expect(names()).To(ContainElements(nextFull.Name, newIncremental.Name)) + }) + + It("should reject invalid specs", func(ctx context.Context) { + scheduled := &v1.ClickHouseScheduledBackup{ + Name: "with-base", Namespace: namespace, + Spec: v1.ClickHouseScheduledBackupSpec{ + Schedule: "0 * * * *", + Template: v1.ClickHouseBackupTemplate{Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: clusterName}, + Storage: storage, + BaseBackupRef: &corev1.LocalObjectReference{Name: "base"}, + }}, + }, + } + Expect(suite.Client.Create(ctx, scheduled)).To(MatchError(ContainSubstring("baseBackupRef is managed by the schedule"))) + + scheduled.Spec.Template.Spec.BaseBackupRef = nil + scheduled.Name = "a-name-that-leaves-no-room-for-the-timestamp-suffix" + Expect(suite.Client.Create(ctx, scheduled)).To(MatchError(ContainSubstring("no more than 48 characters"))) + }) + }) +}) diff --git a/internal/controller/clickhouse/commands_test.go b/internal/controller/clickhouse/commands_test.go index 4d09a58b8..4436f403d 100644 --- a/internal/controller/clickhouse/commands_test.go +++ b/internal/controller/clickhouse/commands_test.go @@ -40,6 +40,7 @@ const ( var ( keeperImage = "clickhouse/clickhouse-keeper:" + supported.Latest.Version() clickhouseImage = "clickhouse/clickhouse-server:" + supported.Latest.Version() + s3Image = "adobe/s3mock:5.2.3" ) func generateKeeperConfig() *strings.Reader { @@ -421,6 +422,155 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { } }) + Describe("backup operations", Ordered, func() { + const ( + s3Hostname = "test-s3" + s3Port = "9090/tcp" + s3Bucket = "backups" + s3Endpoint = "http://test-s3:9090/backups" + s3MissingBucket = "http://test-s3:9090/missing-bucket" + ) + + // The zero value is the first replica of the first shard. + var id0 v1.ClickHouseReplicaID + + location := func(name string) s3Location { + return s3Location{URL: s3Endpoint + "/" + name, AccessKeyID: "test", SecretAccessKey: "test"} + } + + waitFinished := func(ctx context.Context, operationID string) backupOperationState { + GinkgoHelper() + + var state backupOperationState + + Eventually(func(g Gomega) { + var ( + found bool + err error + ) + + state, found, err = cmd.BackupOperationState(ctx, id0, operationID) + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(found).To(BeTrue()) + g.Expect(state.running()).To(BeFalse()) + }, "2m", "200ms").Should(Succeed()) + + return state + } + + BeforeAll(func(ctx context.Context) { + By("starting S3 storage") + + ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ + Image: s3Image, + ConfigModifier: func(c *container.Config) { + c.Hostname = s3Hostname + }, + Env: map[string]string{"COM_ADOBE_TESTING_S3MOCK_STORE_INITIAL_BUCKETS": s3Bucket}, + Networks: []string{testNetwork.Name}, + ExposedPorts: []string{s3Port}, + WaitingFor: wait.ForListeningPort(s3Port), + Started: true, + }) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(func(ctx context.Context) { + By("terminating S3 storage") + + _ = ctr.Terminate(ctx, testcontainers.StopTimeout(time.Second)) + }) + }) + + It("should back up and restore a replicated table", func(ctx context.Context) { + conn, err := cmd.getConn(id0) + Expect(err).NotTo(HaveOccurred()) + + scope := &v1.BackupScope{Tables: []v1.BackupTable{{Database: "default", Table: "backup_src"}}} + + Expect(conn.Exec(ctx, `CREATE TABLE default.backup_src (id UInt64) ENGINE=ReplicatedMergeTree ORDER BY id`)).To(Succeed()) + Expect(conn.Exec(ctx, `INSERT INTO default.backup_src SELECT number FROM numbers(1000)`)).To(Succeed()) + + By("taking a full backup") + + full := backupStatement{Scope: scope, Location: location("full"), ID: "backup-full"} + Expect(cmd.StartBackupOperation(ctx, id0, full.SQL())).To(Succeed()) + + By("accepting a repeated submission of the same operation") + + Expect(cmd.StartBackupOperation(ctx, id0, full.SQL())).To(Succeed()) + + state := waitFinished(ctx, full.ID) + Expect(state.succeeded()).To(BeTrue(), "status %s: %s", state.Status, state.Error) + Expect(state.NumFiles).To(BeNumerically(">", 0)) + Expect(state.CompressedSize).To(BeNumerically(">", 0)) + + By("taking an incremental backup") + + Expect(conn.Exec(ctx, `INSERT INTO default.backup_src SELECT number + 1000 FROM numbers(500)`)).To(Succeed()) + + base := location("full") + incremental := backupStatement{Scope: scope, Location: location("incremental"), Base: &base, ID: "backup-incremental"} + Expect(cmd.StartBackupOperation(ctx, id0, incremental.SQL())).To(Succeed()) + + incrementalState := waitFinished(ctx, incremental.ID) + Expect(incrementalState.succeeded()).To(BeTrue(), "status %s: %s", incrementalState.Status, incrementalState.Error) + + By("restoring the dropped table from the incremental backup") + + Expect(conn.Exec(ctx, `DROP TABLE default.backup_src SYNC`)).To(Succeed()) + + restore := backupStatement{Restore: true, Scope: scope, Location: location("incremental"), ID: "restore-incremental"} + Expect(cmd.StartBackupOperation(ctx, id0, restore.SQL())).To(Succeed()) + + restoreState := waitFinished(ctx, restore.ID) + Expect(restoreState.succeeded()).To(BeTrue(), "status %s: %s", restoreState.Status, restoreState.Error) + + for id := range cmd.cluster.ReplicaIDs() { + replicaConn, err := cmd.getConn(id) + Expect(err).NotTo(HaveOccurred()) + + Eventually(func(g Gomega) { + var count uint64 + g.Expect(replicaConn.QueryRow(ctx, `SELECT count() FROM default.backup_src`).Scan(&count)).To(Succeed()) + g.Expect(count).To(Equal(uint64(1500))) + }, "1m", "200ms").Should(Succeed()) + } + + Expect(conn.Exec(ctx, `DROP TABLE default.backup_src SYNC`)).To(Succeed()) + }) + + It("should report a failed operation", func(ctx context.Context) { + failed := backupStatement{ + Scope: &v1.BackupScope{Databases: []string{"default"}}, + Location: s3Location{URL: s3MissingBucket + "/full", AccessKeyID: "test", SecretAccessKey: "test"}, + ID: "backup-failed", + } + Expect(cmd.StartBackupOperation(ctx, id0, failed.SQL())).To(Succeed()) + + state := waitFinished(ctx, failed.ID) + Expect(state.succeeded()).To(BeFalse()) + Expect(state.Status).To(Equal("BACKUP_FAILED")) + Expect(errorSummary(state.Error)).To(ContainSubstring("bucket")) + }) + + It("should not find an unknown operation", func(ctx context.Context) { + _, found, err := cmd.BackupOperationState(ctx, id0, "unknown") + Expect(err).NotTo(HaveOccurred()) + Expect(found).To(BeFalse()) + }) + + It("should detect the settings known to the server", func(ctx context.Context) { + Expect(cmd.Ping(ctx, id0)).To(Succeed()) + + known, err := cmd.HasSetting(ctx, id0, "max_threads") + Expect(err).NotTo(HaveOccurred()) + Expect(known).To(BeTrue()) + + known, err = cmd.HasSetting(ctx, id0, "no_such_setting") + Expect(err).NotTo(HaveOccurred()) + Expect(known).To(BeFalse()) + }) + }) + It("should evict a single replica connection from the cache", func(_ context.Context) { id := v1.ClickHouseReplicaID{ShardID: 0, Index: 0} diff --git a/internal/controller/clickhouse/controller.go b/internal/controller/clickhouse/controller.go index f072a8e32..d2dd53612 100644 --- a/internal/controller/clickhouse/controller.go +++ b/internal/controller/clickhouse/controller.go @@ -249,7 +249,7 @@ func SetupWithManager(mgr ctrl.Manager, deps chctrl.Dependencies, settings chctr return fmt.Errorf("close cached ClickHouse connections: %w", err) } - return nil + return setupBackupControllers(mgr, deps, settings, clickhouseController.connCache) } func (cc *ClusterController) clickHouseClustersForKeeper(ctx context.Context, obj client.Object) []reconcile.Request { diff --git a/internal/controller/clickhouse/scheduledbackup_controller.go b/internal/controller/clickhouse/scheduledbackup_controller.go new file mode 100644 index 000000000..d353c440b --- /dev/null +++ b/internal/controller/clickhouse/scheduledbackup_controller.go @@ -0,0 +1,401 @@ +package clickhouse + +import ( + "cmp" + "context" + "fmt" + "slices" + "time" + + gcmp "github.com/google/go-cmp/cmp" + "github.com/robfig/cron/v3" + corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/tools/events" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + chctrl "github.com/ClickHouse/clickhouse-operator/internal/controller" + util "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +const ( + // scheduledBackupNameTimeLayout is the suffix added to the schedule name to name the created backups. + scheduledBackupNameTimeLayout = "20060102150405" + // maxMissedScheduleWindow bounds how far back missed runs are looked for. + maxMissedScheduleWindow = 7 * 24 * time.Hour +) + +// ScheduledBackupController reconciles ClickHouseScheduledBackup objects. +// It creates ClickHouseBackup resources on a schedule and prunes the old ones. +type ScheduledBackupController struct { + client.Client + + Scheme *runtime.Scheme + Logger util.Logger + Recorder events.EventRecorder + // Now returns the current time, replaceable in tests. + Now func() time.Time +} + +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousescheduledbackups,verbs=get;list;watch;create;update;patch;delete +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousescheduledbackups/status,verbs=get;update;patch +// +kubebuilder:rbac:groups=clickhouse.com,resources=clickhousescheduledbackups/finalizers,verbs=update + +// Reconcile creates the due backup of the schedule and removes the backups that exceed the history limits. +func (c *ScheduledBackupController) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { + scheduled := &v1.ClickHouseScheduledBackup{} + if err := c.Get(ctx, req.NamespacedName, scheduled); err != nil { + if k8serrors.IsNotFound(err) { + return ctrl.Result{}, nil + } + + return ctrl.Result{}, fmt.Errorf("get ClickHouseScheduledBackup %s: %w", req.String(), err) + } + + if !scheduled.DeletionTimestamp.IsZero() { + return ctrl.Result{}, nil + } + + log := c.Logger.WithContext(ctx, scheduled) + status := scheduled.Status.DeepCopy() + + backups, err := c.ownedBackups(ctx, scheduled) + if err != nil { + return ctrl.Result{}, err + } + + backups, err = c.prune(ctx, log, scheduled, backups) + if err != nil { + return ctrl.Result{}, err + } + + recordLastSuccessful(scheduled, backups) + + result, err := c.schedule(ctx, log, scheduled, backups) + if err != nil { + return ctrl.Result{}, err + } + + if gcmp.Equal(status, &scheduled.Status) { + return result, nil + } + + if err := c.Status().Update(ctx, scheduled); err != nil { + return ctrl.Result{}, fmt.Errorf("update status: %w", err) + } + + return result, nil +} + +// schedule creates the backup of the most recent missed run and returns when the next run is due. +func (c *ScheduledBackupController) schedule( + ctx context.Context, + log util.Logger, + scheduled *v1.ClickHouseScheduledBackup, + backups []v1.ClickHouseBackup, +) (ctrl.Result, error) { + schedule, err := parseBackupSchedule(scheduled.Spec) + if err != nil { + if c.setScheduled(scheduled, metav1.ConditionFalse, v1.ScheduledBackupConditionReasonInvalidSchedule, err.Error()) { + c.Recorder.Eventf(scheduled, nil, corev1.EventTypeWarning, v1.EventReasonInvalidSchedule, v1.EventActionScheduling, + "Invalid schedule: %s", err.Error()) + } + + return ctrl.Result{}, nil + } + + if scheduled.Spec.Suspend != nil && *scheduled.Spec.Suspend { + c.setScheduled(scheduled, metav1.ConditionFalse, v1.ScheduledBackupConditionReasonSuspended, "") + + return ctrl.Result{}, nil + } + + c.setScheduled(scheduled, metav1.ConditionTrue, v1.ScheduledBackupConditionReasonActive, "") + + now := c.Now() + + last := scheduled.CreationTimestamp.Time + if scheduled.Status.LastScheduleTime != nil { + last = scheduled.Status.LastScheduleTime.Time + } + + due, next := missedBackupSchedule(schedule, last, now) + if due.IsZero() { + return ctrl.Result{RequeueAfter: next.Sub(now)}, nil + } + + scheduled.Status.LastScheduleTime = &metav1.Time{Time: due} + + if active := activeBackup(backups); active != "" { + log.Info("skipping scheduled backup, previous backup is not finished", "backup", active) + c.Recorder.Eventf(scheduled, nil, corev1.EventTypeWarning, v1.EventReasonBackupSkipped, v1.EventActionScheduling, + "Skipped the run of %s: backup %s is not finished", due.UTC().Format(time.RFC3339), active) + + return ctrl.Result{RequeueAfter: next.Sub(now)}, nil + } + + backup, err := c.newBackup(scheduled, backups, due) + if err != nil { + return ctrl.Result{}, err + } + + if err := c.Create(ctx, backup); err != nil && !k8serrors.IsAlreadyExists(err) { + return ctrl.Result{}, fmt.Errorf("create ClickHouseBackup %s: %w", backup.Name, err) + } + + log.Info("created scheduled backup", "backup", backup.Name, "incremental", backup.IsIncremental()) + c.Recorder.Eventf(scheduled, backup, corev1.EventTypeNormal, v1.EventReasonBackupScheduled, v1.EventActionScheduling, + "Created backup %s", backup.Name) + + scheduled.Status.LastBackupName = backup.Name + + return ctrl.Result{RequeueAfter: next.Sub(now)}, nil +} + +func (c *ScheduledBackupController) newBackup( + scheduled *v1.ClickHouseScheduledBackup, + backups []v1.ClickHouseBackup, + due time.Time, +) (*v1.ClickHouseBackup, error) { + backup := &v1.ClickHouseBackup{ + Name: fmt.Sprintf("%s-%s", scheduled.Name, due.UTC().Format(scheduledBackupNameTimeLayout)), + Namespace: scheduled.Namespace, + Labels: map[string]string{util.LabelScheduledBackup: scheduled.Name}, + Spec: *scheduled.Spec.Template.Spec.DeepCopy(), + } + + if base := incrementalBase(backups, scheduled.Spec.FullBackupInterval); base != "" { + backup.Spec.BaseBackupRef = &corev1.LocalObjectReference{Name: base} + } + + if err := controllerutil.SetControllerReference(scheduled, backup, c.Scheme); err != nil { + return nil, fmt.Errorf("set owner of ClickHouseBackup %s: %w", backup.Name, err) + } + + return backup, nil +} + +// ownedBackups lists the backups created by the schedule, ordered from the oldest to the newest. +func (c *ScheduledBackupController) ownedBackups( + ctx context.Context, + scheduled *v1.ClickHouseScheduledBackup, +) ([]v1.ClickHouseBackup, error) { + var list v1.ClickHouseBackupList + if err := c.List(ctx, &list, client.InNamespace(scheduled.Namespace), + client.MatchingLabels{util.LabelScheduledBackup: scheduled.Name}); err != nil { + return nil, fmt.Errorf("list ClickHouseBackups of %s: %w", scheduled.Name, err) + } + + backups := slices.DeleteFunc(list.Items, func(backup v1.ClickHouseBackup) bool { + return !metav1.IsControlledBy(&backup, scheduled) || !backup.DeletionTimestamp.IsZero() + }) + + slices.SortFunc(backups, func(a, b v1.ClickHouseBackup) int { + return cmp.Or(a.CreationTimestamp.Compare(b.CreationTimestamp.Time), cmp.Compare(a.Name, b.Name)) + }) + + return backups, nil +} + +// prune deletes the backup resources that exceed the history limits and returns the remaining ones. +func (c *ScheduledBackupController) prune( + ctx context.Context, + log util.Logger, + scheduled *v1.ClickHouseScheduledBackup, + backups []v1.ClickHouseBackup, +) ([]v1.ClickHouseBackup, error) { + expired := expiredBackups(backups, scheduled.Spec.SuccessfulBackupsHistoryLimit, scheduled.Spec.FailedBackupsHistoryLimit) + if len(expired) == 0 { + return backups, nil + } + + for i := range backups { + if _, ok := expired[backups[i].Name]; !ok { + continue + } + + log.Info("deleting backup resource that exceeds the history limit", "backup", backups[i].Name) + + if err := c.Delete(ctx, &backups[i]); err != nil && !k8serrors.IsNotFound(err) { + return nil, fmt.Errorf("delete ClickHouseBackup %s: %w", backups[i].Name, err) + } + } + + return slices.DeleteFunc(backups, func(backup v1.ClickHouseBackup) bool { + _, ok := expired[backup.Name] + return ok + }), nil +} + +// setScheduled sets the Scheduled condition and reports whether its status changed. +func (*ScheduledBackupController) setScheduled( + scheduled *v1.ClickHouseScheduledBackup, + status metav1.ConditionStatus, + reason v1.ConditionReason, + message string, +) bool { + return chctrl.SetStatusCondition(&scheduled.Status.Conditions, metav1.Condition{ + Type: v1.ScheduledBackupConditionTypeScheduled, + Status: status, + Reason: reason, + Message: message, + ObservedGeneration: scheduled.Generation, + }) +} + +//nolint:ireturn // the cron parser returns the interface +func parseBackupSchedule(spec v1.ClickHouseScheduledBackupSpec) (cron.Schedule, error) { + expression := spec.Schedule + if spec.TimeZone != nil && *spec.TimeZone != "" { + expression = fmt.Sprintf("CRON_TZ=%s %s", *spec.TimeZone, spec.Schedule) + } + + schedule, err := cron.ParseStandard(expression) + if err != nil { + return nil, fmt.Errorf("parse schedule %q: %w", spec.Schedule, err) + } + + return schedule, nil +} + +// missedBackupSchedule returns the most recent run between last and now, or zero time if there is none, +// and the first run after now. +func missedBackupSchedule(schedule cron.Schedule, last, now time.Time) (due, next time.Time) { + if earliest := now.Add(-maxMissedScheduleWindow); last.Before(earliest) { + last = earliest + } + + next = schedule.Next(last) + for !next.After(now) { + due = next + next = schedule.Next(next) + } + + return due, next +} + +// activeBackup returns the name of a backup that is not finished yet. +func activeBackup(backups []v1.ClickHouseBackup) string { + for i := range backups { + if !backups[i].Status.Phase.Finished() { + return backups[i].Name + } + } + + return "" +} + +// incrementalBase returns the name of the full backup the next backup is based on, +// or an empty string if the next backup is a full one. +func incrementalBase(backups []v1.ClickHouseBackup, interval *int32) string { + if interval == nil || *interval <= 1 { + return "" + } + + incrementals := int32(0) + + for i := len(backups) - 1; i >= 0; i-- { + backup := &backups[i] + + if backup.IsIncremental() { + incrementals++ + continue + } + + if backup.Status.Phase != v1.BackupPhaseCompleted { + continue + } + + if incrementals >= *interval-1 { + return "" + } + + return backup.Name + } + + return "" +} + +// expiredBackups selects the finished backups that exceed the history limits. +// The most recent full backup and the base backups of the kept backups are never selected. +func expiredBackups(backups []v1.ClickHouseBackup, successfulLimit, failedLimit *int32) map[string]struct{} { + var completed, failed []*v1.ClickHouseBackup + + protected := map[string]struct{}{} + + for i := range backups { + backup := &backups[i] + + switch backup.Status.Phase { + case v1.BackupPhaseCompleted: + completed = append(completed, backup) + case v1.BackupPhaseFailed: + failed = append(failed, backup) + case v1.BackupPhasePending, v1.BackupPhaseRunning: + fallthrough + default: + protectBase(protected, backup) + } + } + + expired := map[string]struct{}{} + + if failedLimit != nil && len(failed) > int(*failedLimit) { + for _, backup := range failed[:len(failed)-int(*failedLimit)] { + expired[backup.Name] = struct{}{} + } + } + + if successfulLimit == nil || len(completed) <= int(*successfulLimit) { + return expired + } + + kept := completed[len(completed)-int(*successfulLimit):] + for _, backup := range kept { + protectBase(protected, backup) + } + + for _, c := range slices.Backward(completed) { + if !c.IsIncremental() { + protected[c.Name] = struct{}{} + break + } + } + + for _, backup := range completed[:len(completed)-int(*successfulLimit)] { + if _, ok := protected[backup.Name]; !ok { + expired[backup.Name] = struct{}{} + } + } + + return expired +} + +func protectBase(protected map[string]struct{}, backup *v1.ClickHouseBackup) { + if backup.IsIncremental() { + protected[backup.Spec.BaseBackupRef.Name] = struct{}{} + } +} + +// recordLastSuccessful stores the most recent completed backup in the schedule status. +func recordLastSuccessful(scheduled *v1.ClickHouseScheduledBackup, backups []v1.ClickHouseBackup) { + for i := len(backups) - 1; i >= 0; i-- { + backup := &backups[i] + if backup.Status.Phase != v1.BackupPhaseCompleted || backup.Status.CompletionTime == nil { + continue + } + + last := scheduled.Status.LastSuccessfulTime + if last == nil || last.Before(backup.Status.CompletionTime) { + scheduled.Status.LastSuccessfulTime = backup.Status.CompletionTime + scheduled.Status.LastSuccessfulBackupName = backup.Name + } + + return + } +} diff --git a/internal/controllerutil/labels.go b/internal/controllerutil/labels.go index 623dbdfe6..ad49dfc85 100644 --- a/internal/controllerutil/labels.go +++ b/internal/controllerutil/labels.go @@ -20,6 +20,7 @@ const ( LabelClickHouseShardID = "clickhouse.com/shard-id" LabelClickHouseReplicaID = "clickhouse.com/replica-id" LabelDiskName = "clickhouse.com/disk" + LabelScheduledBackup = "clickhouse.com/scheduled-backup" ) const ( diff --git a/test/e2e/backup_e2e_test.go b/test/e2e/backup_e2e_test.go new file mode 100644 index 000000000..9f12126a3 --- /dev/null +++ b/test/e2e/backup_e2e_test.go @@ -0,0 +1,229 @@ +package e2e + +import ( + "context" + "fmt" + "math/rand/v2" + "time" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/util/intstr" + "sigs.k8s.io/controller-runtime/pkg/client" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" + "github.com/ClickHouse/clickhouse-operator/test/testutil" +) + +const ( + s3Image = "adobe/s3mock:5.2.3" + s3Name = "s3" + s3Port = 9090 + s3Bucket = "backups" +) + +var _ = Describe("Backup controller", Label("clickhouse", "backup"), func() { + var ( + ns string + cr v1.ClickHouseCluster + storage v1.BackupStorage + ) + + waitBackup := func(ctx context.Context, backup *v1.ClickHouseBackup) { + GinkgoHelper() + + Eventually(func(g Gomega) { + g.Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(backup), backup)).To(Succeed()) + g.Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseCompleted), "conditions: %v", backup.Status.Conditions) + }, 3*time.Minute).WithPolling(pollingInterval).Should(Succeed()) + } + + BeforeEach(func(ctx context.Context) { + ns = testutil.EnsureTestNamespace(ctx, env) + + By("starting S3 storage") + + labels := map[string]string{controllerutil.LabelAppKey: s3Name} + Expect(k8sClient.Create(ctx, &corev1.Pod{ + Namespace: ns, Name: s3Name, Labels: labels, + Spec: corev1.PodSpec{Containers: []corev1.Container{{ + Name: s3Name, + Image: s3Image, + Env: []corev1.EnvVar{{Name: "COM_ADOBE_TESTING_S3MOCK_STORE_INITIAL_BUCKETS", Value: s3Bucket}}, + Ports: []corev1.ContainerPort{{ContainerPort: s3Port}}, + ReadinessProbe: &corev1.Probe{ + TCPSocket: &corev1.TCPSocketAction{Port: intstr.FromInt32(s3Port)}}, + }}}, + })).To(Succeed()) + Expect(k8sClient.Create(ctx, &corev1.Service{ + Namespace: ns, Name: s3Name, + Spec: corev1.ServiceSpec{ + Selector: labels, + Ports: []corev1.ServicePort{{Port: s3Port, TargetPort: intstr.FromInt32(s3Port)}}, + }, + })).To(Succeed()) + + Expect(k8sClient.Create(ctx, &corev1.Secret{ + Namespace: ns, Name: s3Name, + StringData: map[string]string{"access-key-id": "test", "secret-access-key": "test"}, + })).To(Succeed()) + + storage = v1.BackupStorage{S3: &v1.S3BackupStorage{ + Endpoint: fmt.Sprintf("http://%s.%s.svc:%d/%s", s3Name, ns, s3Port, s3Bucket), + Credentials: &v1.S3Credentials{ + AccessKeyID: v1.SecretKeySelector{Name: s3Name, Key: "access-key-id"}, + SecretAccessKey: v1.SecretKeySelector{Name: s3Name, Key: "secret-access-key"}, + }, + }} + + By("creating the cluster") + + name := fmt.Sprintf("backup-%d", rand.Uint32()) //nolint:gosec + keeper := testutil.NewKeeperCluster(ns, name).WithStorage(defaultStorage).Cluster() + Expect(k8sClient.Create(ctx, &keeper)).To(Succeed()) + DeferCleanup(func(ctx context.Context) { + Expect(k8sClient.Delete(ctx, &keeper)).To(Succeed()) + }) + env.WaitKeeperUpdatedAndReady(ctx, &keeper, 2*time.Minute) + + cr = testutil.NewClickHouseCluster(ns, name). + WithReplicas(2). + WithStorage(defaultStorage). + WithKeeper(keeper.Name). + Cluster() + Expect(k8sClient.Create(ctx, &cr)).To(Succeed()) + DeferCleanup(func(ctx context.Context) { + Expect(k8sClient.Delete(ctx, &cr)).To(Succeed()) + }) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 3*time.Minute) + }) + + It("should back up, restore and schedule backups of a cluster", func(ctx context.Context) { + chClient, err := testutil.NewClickHouseClient(ctx, podDialer, &cr) + Expect(err).NotTo(HaveOccurred()) + DeferCleanup(chClient.Close) + + Expect(chClient.Exec(ctx, + "CREATE TABLE default.backup_test (id UInt64) ENGINE=ReplicatedMergeTree ORDER BY id")).To(Succeed()) + Expect(chClient.Exec(ctx, "INSERT INTO default.backup_test SELECT number FROM numbers(1000)")).To(Succeed()) + + By("taking a full backup") + + full := &v1.ClickHouseBackup{ + Namespace: ns, Name: "full", + Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: cr.Name}, + Storage: storage, + }, + } + Expect(k8sClient.Create(ctx, full)).To(Succeed()) + waitBackup(ctx, full) + Expect(full.Status.Location).To(Equal(storage.S3.Endpoint + "/full")) + Expect(full.Status.NumFiles).To(BeNumerically(">", 0)) + + By("taking an incremental backup") + + Expect(chClient.Exec(ctx, "INSERT INTO default.backup_test SELECT number + 1000 FROM numbers(500)")).To(Succeed()) + + incremental := &v1.ClickHouseBackup{ + Namespace: ns, Name: "incremental", + Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: cr.Name}, + Storage: storage, + BaseBackupRef: &corev1.LocalObjectReference{Name: full.Name}, + }, + } + Expect(k8sClient.Create(ctx, incremental)).To(Succeed()) + waitBackup(ctx, incremental) + Expect(incremental.Status.BaseLocation).To(Equal(full.Status.Location)) + + By("restoring the dropped table") + + Expect(chClient.Exec(ctx, "DROP TABLE default.backup_test SYNC")).To(Succeed()) + + restore := &v1.ClickHouseRestore{ + Namespace: ns, Name: "restore", + Spec: v1.ClickHouseRestoreSpec{ + ClusterRef: corev1.LocalObjectReference{Name: cr.Name}, + BackupRef: &corev1.LocalObjectReference{Name: incremental.Name}, + }, + } + Expect(k8sClient.Create(ctx, restore)).To(Succeed()) + Eventually(func(g Gomega) { + g.Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(restore), restore)).To(Succeed()) + g.Expect(restore.Status.Phase).To(Equal(v1.BackupPhaseCompleted), "conditions: %v", restore.Status.Conditions) + }, 3*time.Minute).WithPolling(pollingInterval).Should(Succeed()) + + for id := range cr.ReplicaIDs() { + Eventually(func(g Gomega) { + var count uint64 + g.Expect(chClient.QueryRowReplica(ctx, id, "SELECT count() FROM default.backup_test", &count)).To(Succeed()) + g.Expect(count).To(BeEquivalentTo(1500)) + }, time.Minute).WithPolling(pollingInterval).Should(Succeed()) + } + + By("reporting a backup that cannot be written") + + failed := &v1.ClickHouseBackup{ + Namespace: ns, Name: "missing-bucket", + Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: cr.Name}, + Storage: v1.BackupStorage{S3: &v1.S3BackupStorage{ + Endpoint: fmt.Sprintf("http://%s.%s.svc:%d/missing-bucket", s3Name, ns, s3Port), + Credentials: storage.S3.Credentials, + }}, + }, + } + Expect(k8sClient.Create(ctx, failed)).To(Succeed()) + Eventually(func(g Gomega) { + g.Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(failed), failed)).To(Succeed()) + g.Expect(failed.Status.Phase).To(Equal(v1.BackupPhaseFailed)) + }, 2*time.Minute).WithPolling(pollingInterval).Should(Succeed()) + + By("creating backups on schedule") + + scheduled := &v1.ClickHouseScheduledBackup{ + Namespace: ns, Name: "minutely", + Spec: v1.ClickHouseScheduledBackupSpec{ + Schedule: "* * * * *", + FullBackupInterval: new(int32(2)), + Template: v1.ClickHouseBackupTemplate{Spec: v1.ClickHouseBackupSpec{ + ClusterRef: corev1.LocalObjectReference{Name: cr.Name}, + Storage: storage, + }}, + }, + } + Expect(k8sClient.Create(ctx, scheduled)).To(Succeed()) + DeferCleanup(func(ctx context.Context) { + Expect(k8sClient.Delete(ctx, scheduled)).To(Succeed()) + }) + + Eventually(func(g Gomega) { + var backups v1.ClickHouseBackupList + g.Expect(k8sClient.List(ctx, &backups, client.InNamespace(ns), + client.MatchingLabels{controllerutil.LabelScheduledBackup: scheduled.Name})).To(Succeed()) + + var completedFull, completedIncremental int + + for _, backup := range backups.Items { + if backup.Status.Phase != v1.BackupPhaseCompleted { + continue + } + + if backup.IsIncremental() { + completedIncremental++ + } else { + completedFull++ + } + } + + g.Expect(completedFull).To(BeNumerically(">=", 1)) + g.Expect(completedIncremental).To(BeNumerically(">=", 1)) + + g.Expect(k8sClient.Get(ctx, client.ObjectKeyFromObject(scheduled), scheduled)).To(Succeed()) + g.Expect(scheduled.Status.LastSuccessfulBackupName).NotTo(BeEmpty()) + }, 4*time.Minute).WithPolling(pollingInterval).Should(Succeed()) + }) +}) From 227ac33195c358814a66fe1f7f88e87be6c114ab Mon Sep 17 00:00:00 2001 From: Tal Efraim Date: Tue, 1 Dec 2026 22:49:10 +0200 Subject: [PATCH 2/3] fix: retry backup status update conflicts, follow the constants and logging conventions --- .../clickhouse/backup_controller.go | 22 ++++++++++++------- .../clickhouse/backup_controller_test.go | 16 ++++++++++++++ internal/controller/clickhouse/constants.go | 9 ++++++++ .../clickhouse/scheduledbackup_controller.go | 16 +++++--------- 4 files changed, 45 insertions(+), 18 deletions(-) diff --git a/internal/controller/clickhouse/backup_controller.go b/internal/controller/clickhouse/backup_controller.go index 7b9396f6d..2c6ff862a 100644 --- a/internal/controller/clickhouse/backup_controller.go +++ b/internal/controller/clickhouse/backup_controller.go @@ -28,10 +28,6 @@ import ( ) const ( - // backupPollInterval is the interval between the checks of a running operation. - backupPollInterval = 10 * time.Second - // backupWaitInterval is the interval between the checks of the dependencies an operation waits for. - backupWaitInterval = 30 * time.Second // maxBackupMessageLength limits the size of the error reported in the status. maxBackupMessageLength = 2048 @@ -433,7 +429,7 @@ func (c *BackupController) start( c.setCompleted(op, metav1.ConditionFalse, v1.BackupConditionReasonInProgress, "") if err := c.Status().Update(ctx, op.Object); err != nil { - return ctrl.Result{}, fmt.Errorf("update status: %w", err) + return statusUpdateResult(err) } reason, action := op.startedEvent() @@ -497,7 +493,7 @@ func (c *BackupController) complete( c.setCompleted(op, metav1.ConditionTrue, v1.BackupConditionReasonSucceeded, "") if err := c.Status().Update(ctx, op.Object); err != nil { - return ctrl.Result{}, fmt.Errorf("update status: %w", err) + return statusUpdateResult(err) } log.Info("operation completed", "operation_id", op.Status.ID) @@ -521,7 +517,7 @@ func (c *BackupController) fail( c.setCompleted(op, metav1.ConditionFalse, reason, message) if err := c.Status().Update(ctx, op.Object); err != nil { - return ctrl.Result{}, fmt.Errorf("update status: %w", err) + return statusUpdateResult(err) } eventReason, action := op.failedEvent() @@ -546,7 +542,7 @@ func (c *BackupController) wait( c.setCompleted(op, metav1.ConditionFalse, reason, message) if err := c.Status().Update(ctx, op.Object); err != nil { - return ctrl.Result{}, fmt.Errorf("update status: %w", err) + return statusUpdateResult(err) } return ctrl.Result{RequeueAfter: backupWaitInterval}, nil @@ -612,6 +608,16 @@ func redactSecrets(message string, stmt backupStatement) string { return errorSummary(message) } +// statusUpdateResult maps a failed status update to a reconcile result. A conflict is not an error: +// the object changed since it was read, so the reconcile runs again on the fresh one. +func statusUpdateResult(err error) (ctrl.Result, error) { + if k8serrors.IsConflict(err) { + return ctrl.Result{RequeueAfter: statusConflictRequeueInterval}, nil + } + + return ctrl.Result{}, fmt.Errorf("update status: %w", err) +} + // replicaPodAddress resolves replicas by Pod IP, as the cluster controller does: cluster DNS serves // stale records for a while after a Pod restart. func replicaPodAddress(ctx context.Context, reader client.Reader, cluster *v1.ClickHouseCluster) replicaResolver { diff --git a/internal/controller/clickhouse/backup_controller_test.go b/internal/controller/clickhouse/backup_controller_test.go index bc406be8c..8bc0b5346 100644 --- a/internal/controller/clickhouse/backup_controller_test.go +++ b/internal/controller/clickhouse/backup_controller_test.go @@ -10,8 +10,10 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/events" @@ -868,4 +870,18 @@ var _ = When("reconciling backup resources", Ordered, func() { Expect(suite.Client.Create(ctx, scheduled)).To(MatchError(ContainSubstring("no more than 48 characters"))) }) }) + + Describe("status update", func() { + It("should retry a conflict instead of reporting an error", func() { + resource := schema.GroupResource{Group: v1.GroupVersion.Group, Resource: "clickhousebackups"} + conflict := k8serrors.NewConflict(resource, "backup", errors.New("the object has been modified")) + + result, err := statusUpdateResult(conflict) + Expect(err).NotTo(HaveOccurred()) + Expect(result.RequeueAfter).To(Equal(statusConflictRequeueInterval)) + + _, err = statusUpdateResult(errors.New("unavailable")) + Expect(err).To(MatchError(ContainSubstring("update status: unavailable"))) + }) + }) }) diff --git a/internal/controller/clickhouse/constants.go b/internal/controller/clickhouse/constants.go index 128006423..8237deff6 100644 --- a/internal/controller/clickhouse/constants.go +++ b/internal/controller/clickhouse/constants.go @@ -96,6 +96,15 @@ const ( // terminationGracePeriod covers the query drain, the merge_tree unique parts wait from base.yaml.tmpl and the table shutdown. terminationGracePeriod = 90 * time.Second + + // backupPollInterval is the interval between the checks of a running backup or restore. + backupPollInterval = 10 * time.Second + // backupWaitInterval is the interval between the checks of the dependencies a backup or restore waits for. + backupWaitInterval = 30 * time.Second + // statusConflictRequeueInterval is the delay before a backup resource whose status update conflicted is reconciled again. + statusConflictRequeueInterval = time.Second + // maxMissedScheduleWindow bounds how far back missed scheduled backup runs are looked for. + maxMissedScheduleWindow = 7 * 24 * time.Hour ) type secretSpec struct { diff --git a/internal/controller/clickhouse/scheduledbackup_controller.go b/internal/controller/clickhouse/scheduledbackup_controller.go index d353c440b..44684815f 100644 --- a/internal/controller/clickhouse/scheduledbackup_controller.go +++ b/internal/controller/clickhouse/scheduledbackup_controller.go @@ -23,12 +23,8 @@ import ( util "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" ) -const ( - // scheduledBackupNameTimeLayout is the suffix added to the schedule name to name the created backups. - scheduledBackupNameTimeLayout = "20060102150405" - // maxMissedScheduleWindow bounds how far back missed runs are looked for. - maxMissedScheduleWindow = 7 * 24 * time.Hour -) +// scheduledBackupNameTimeLayout is the suffix added to the schedule name to name the created backups. +const scheduledBackupNameTimeLayout = "20060102150405" // ScheduledBackupController reconciles ClickHouseScheduledBackup objects. // It creates ClickHouseBackup resources on a schedule and prunes the old ones. @@ -86,7 +82,7 @@ func (c *ScheduledBackupController) Reconcile(ctx context.Context, req ctrl.Requ } if err := c.Status().Update(ctx, scheduled); err != nil { - return ctrl.Result{}, fmt.Errorf("update status: %w", err) + return statusUpdateResult(err) } return result, nil @@ -132,7 +128,7 @@ func (c *ScheduledBackupController) schedule( scheduled.Status.LastScheduleTime = &metav1.Time{Time: due} if active := activeBackup(backups); active != "" { - log.Info("skipping scheduled backup, previous backup is not finished", "backup", active) + log.Info("skipping scheduled backup, previous backup is not finished", "clickhousebackup", active) c.Recorder.Eventf(scheduled, nil, corev1.EventTypeWarning, v1.EventReasonBackupSkipped, v1.EventActionScheduling, "Skipped the run of %s: backup %s is not finished", due.UTC().Format(time.RFC3339), active) @@ -148,7 +144,7 @@ func (c *ScheduledBackupController) schedule( return ctrl.Result{}, fmt.Errorf("create ClickHouseBackup %s: %w", backup.Name, err) } - log.Info("created scheduled backup", "backup", backup.Name, "incremental", backup.IsIncremental()) + log.Info("created scheduled backup", "clickhousebackup", backup.Name, "incremental", backup.IsIncremental()) c.Recorder.Eventf(scheduled, backup, corev1.EventTypeNormal, v1.EventReasonBackupScheduled, v1.EventActionScheduling, "Created backup %s", backup.Name) @@ -219,7 +215,7 @@ func (c *ScheduledBackupController) prune( continue } - log.Info("deleting backup resource that exceeds the history limit", "backup", backups[i].Name) + log.Info("deleting backup resource that exceeds the history limit", "clickhousebackup", backups[i].Name) if err := c.Delete(ctx, &backups[i]); err != nil && !k8serrors.IsNotFound(err) { return nil, fmt.Errorf("delete ClickHouseBackup %s: %w", backups[i].Name, err) From 8a794c8fd6ea1843d3ffc7e9bef496d49f881ca8 Mon Sep 17 00:00:00 2001 From: Tal Efraim Date: Tue, 1 Dec 2026 23:14:40 +0200 Subject: [PATCH 3/3] fix: keep the current backup chain when pruning, default schedules to UTC, record the replica before submitting --- api/v1alpha1/clickhousebackup_types.go | 3 +- .../clickhousescheduledbackup_types.go | 3 +- .../clickhouse.com_clickhousebackups.yaml | 4 +- .../clickhouse.com_clickhouserestores.yaml | 4 +- ...khouse.com_clickhousescheduledbackups.yaml | 3 +- .../crd/clickhousebackups.clickhouse.com.yaml | 4 +- .../clickhouserestores.clickhouse.com.yaml | 4 +- ...khousescheduledbackups.clickhouse.com.yaml | 3 +- docs/guides/backup.mdx | 2 +- docs/reference/api-reference.mdx | 8 +- .../clickhouse/backup_controller.go | 52 ++++++++++--- .../clickhouse/backup_controller_test.go | 76 +++++++++++++++++++ .../clickhouse/scheduledbackup_controller.go | 57 ++++++++------ 13 files changed, 177 insertions(+), 46 deletions(-) diff --git a/api/v1alpha1/clickhousebackup_types.go b/api/v1alpha1/clickhousebackup_types.go index 8d05ca267..c571f0176 100644 --- a/api/v1alpha1/clickhousebackup_types.go +++ b/api/v1alpha1/clickhousebackup_types.go @@ -116,7 +116,8 @@ type BackupOperationStatus struct { // +optional ID string `json:"id,omitempty"` - // Replica is the cluster replica that executes the operation. + // Replica is the cluster replica chosen to execute the operation. It is recorded before the operation + // is submitted. // +optional Replica *BackupReplica `json:"replica,omitempty"` diff --git a/api/v1alpha1/clickhousescheduledbackup_types.go b/api/v1alpha1/clickhousescheduledbackup_types.go index 95ca6c5b6..79970631a 100644 --- a/api/v1alpha1/clickhousescheduledbackup_types.go +++ b/api/v1alpha1/clickhousescheduledbackup_types.go @@ -33,7 +33,8 @@ type ClickHouseScheduledBackupSpec struct { FullBackupInterval *int32 `json:"fullBackupInterval,omitempty"` // SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. - // The most recent full backup and the base backups of the kept incremental backups are always kept. + // The most recent full backup, the incremental backups based on it and the base backups of the kept + // incremental backups are always kept. // Deleting a ClickHouseBackup resource does not delete the backup data from the storage. // +optional // +kubebuilder:default:=10 diff --git a/config/crd/bases/clickhouse.com_clickhousebackups.yaml b/config/crd/bases/clickhouse.com_clickhousebackups.yaml index d66d36ca6..e0096aa81 100644 --- a/config/crd/bases/clickhouse.com_clickhousebackups.yaml +++ b/config/crd/bases/clickhouse.com_clickhousebackups.yaml @@ -307,7 +307,9 @@ spec: - Failed type: string replica: - description: Replica is the cluster replica that executes the operation. + description: |- + Replica is the cluster replica chosen to execute the operation. It is recorded before the operation + is submitted. properties: index: description: Index is the index of the replica within the shard. diff --git a/config/crd/bases/clickhouse.com_clickhouserestores.yaml b/config/crd/bases/clickhouse.com_clickhouserestores.yaml index 4dcddf073..4ced91518 100644 --- a/config/crd/bases/clickhouse.com_clickhouserestores.yaml +++ b/config/crd/bases/clickhouse.com_clickhouserestores.yaml @@ -308,7 +308,9 @@ spec: - Failed type: string replica: - description: Replica is the cluster replica that executes the operation. + description: |- + Replica is the cluster replica chosen to execute the operation. It is recorded before the operation + is submitted. properties: index: description: Index is the index of the replica within the shard. diff --git a/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml b/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml index a69b8fa3f..449f6eafe 100644 --- a/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml +++ b/config/crd/bases/clickhouse.com_clickhousescheduledbackups.yaml @@ -86,7 +86,8 @@ spec: default: 10 description: |- SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. - The most recent full backup and the base backups of the kept incremental backups are always kept. + The most recent full backup, the incremental backups based on it and the base backups of the kept + incremental backups are always kept. Deleting a ClickHouseBackup resource does not delete the backup data from the storage. format: int32 minimum: 1 diff --git a/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml b/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml index 871bd5164..d4856958f 100644 --- a/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhousebackups.clickhouse.com.yaml @@ -310,7 +310,9 @@ spec: - Failed type: string replica: - description: Replica is the cluster replica that executes the operation. + description: |- + Replica is the cluster replica chosen to execute the operation. It is recorded before the operation + is submitted. properties: index: description: Index is the index of the replica within the shard. diff --git a/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml b/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml index e886d2f9b..8bba42f5c 100644 --- a/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhouserestores.clickhouse.com.yaml @@ -311,7 +311,9 @@ spec: - Failed type: string replica: - description: Replica is the cluster replica that executes the operation. + description: |- + Replica is the cluster replica chosen to execute the operation. It is recorded before the operation + is submitted. properties: index: description: Index is the index of the replica within the shard. diff --git a/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml b/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml index d4319a909..180b2cc0d 100644 --- a/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhousescheduledbackups.clickhouse.com.yaml @@ -89,7 +89,8 @@ spec: default: 10 description: |- SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep. - The most recent full backup and the base backups of the kept incremental backups are always kept. + The most recent full backup, the incremental backups based on it and the base backups of the kept + incremental backups are always kept. Deleting a ClickHouseBackup resource does not delete the backup data from the storage. format: int32 minimum: 1 diff --git a/docs/guides/backup.mdx b/docs/guides/backup.mdx index 9fa7d02c4..0a0071ebe 100644 --- a/docs/guides/backup.mdx +++ b/docs/guides/backup.mdx @@ -177,7 +177,7 @@ The created backups are named `-`, for example `nightly | `schedule` | Cron expression of the runs, evaluated in UTC unless `timeZone` is set. | | `suspend` | Stops the creation of new backups without affecting the running ones. | | `fullBackupInterval` | With a value of `N`, every full backup is followed by `N - 1` incremental backups based on it. When unset, every backup is full. A failed full backup is taken again on the next run. | -| `successfulBackupsHistoryLimit` | Number of completed `ClickHouseBackup` resources to keep, 10 by default. The most recent full backup and the base backups of the kept incremental backups are always kept. | +| `successfulBackupsHistoryLimit` | Number of completed `ClickHouseBackup` resources to keep, 10 by default. The most recent full backup, the incremental backups based on it and the base backups of the kept incremental backups are always kept. | | `failedBackupsHistoryLimit` | Number of failed `ClickHouseBackup` resources to keep, 3 by default. | | `template.spec` | Spec of the created backups. `baseBackupRef` is managed by the schedule. | diff --git a/docs/reference/api-reference.mdx b/docs/reference/api-reference.mdx index a09e5bedd..27a70913f 100644 --- a/docs/reference/api-reference.mdx +++ b/docs/reference/api-reference.mdx @@ -31,7 +31,7 @@ BackupOperationStatus is the observed state shared by backups and restores. | `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | | `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | | `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | -| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica chosen to execute the operation. It is recorded before the operation
is submitted. | false | | | `location` | string | Location is the URL of the backup in the storage. | false | | | `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | | `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | @@ -180,7 +180,7 @@ ClickHouseBackupStatus defines the observed state of ClickHouseBackup. | `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | | `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | | `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | -| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica chosen to execute the operation. It is recorded before the operation
is submitted. | false | | | `location` | string | Location is the URL of the backup in the storage. | false | | | `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | | `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | @@ -359,7 +359,7 @@ ClickHouseRestoreStatus defines the observed state of ClickHouseRestore. | `conditions` | [Condition](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#condition-v1-meta) array | | false | | | `phase` | [BackupPhase](#backupphase) | Phase is the lifecycle phase of the operation. | false | | | `id` | string | ID identifies the operation in the `system.backups` table of the replica that executes it. | false | | -| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica that executes the operation. | false | | +| `replica` | [BackupReplica](#backupreplica) | Replica is the cluster replica chosen to execute the operation. It is recorded before the operation
is submitted. | false | | | `location` | string | Location is the URL of the backup in the storage. | false | | | `startTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | StartTime is the time the operation was submitted to ClickHouse. | false | | | `completionTime` | [Time](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#time-v1-meta) | CompletionTime is the time the operation finished. | false | | @@ -412,7 +412,7 @@ ClickHouseScheduledBackupSpec defines the desired state of ClickHouseScheduledBa | `timeZone` | string | TimeZone is the IANA time zone name the schedule is evaluated in. Defaults to UTC. | false | | | `suspend` | boolean | Suspend stops the creation of new backups. Backups that are already running are not affected. | false | | | `fullBackupInterval` | integer | FullBackupInterval makes the schedule take incremental backups: every full backup is followed by
`fullBackupInterval - 1` incremental backups based on it.
When unset or 1, every backup is a full backup. | false | | -| `successfulBackupsHistoryLimit` | integer | SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep.
The most recent full backup and the base backups of the kept incremental backups are always kept.
Deleting a ClickHouseBackup resource does not delete the backup data from the storage. | false | 10 | +| `successfulBackupsHistoryLimit` | integer | SuccessfulBackupsHistoryLimit is the number of completed ClickHouseBackup resources to keep.
The most recent full backup, the incremental backups based on it and the base backups of the kept
incremental backups are always kept.
Deleting a ClickHouseBackup resource does not delete the backup data from the storage. | false | 10 | | `failedBackupsHistoryLimit` | integer | FailedBackupsHistoryLimit is the number of failed ClickHouseBackup resources to keep. | false | 3 | | `template` | [ClickHouseBackupTemplate](#clickhousebackuptemplate) | Template describes the backups created by the schedule. | true | | diff --git a/internal/controller/clickhouse/backup_controller.go b/internal/controller/clickhouse/backup_controller.go index 2c6ff862a..030335438 100644 --- a/internal/controller/clickhouse/backup_controller.go +++ b/internal/controller/clickhouse/backup_controller.go @@ -374,7 +374,7 @@ func (c *BackupController) reconcileOperation(ctx context.Context, log controlle return c.poll(ctx, log, op, cluster, executor) } -// start submits the operation to the first reachable replica. +// start submits the operation to the first reachable replica, or to the replica an earlier attempt chose. func (c *BackupController) start( ctx context.Context, log controllerutil.Logger, @@ -395,9 +395,24 @@ func (c *BackupController) start( return c.wait(ctx, op, blocker.Reason, blocker.Message) } - replica, ok := pickBackupReplica(ctx, cluster, executor) - if !ok { - return c.wait(ctx, op, v1.BackupConditionReasonClusterNotReady, "no replica of the cluster is reachable") + replica, ok := assignedBackupReplica(op, cluster) + if ok { + if !backupReplicaReachable(ctx, executor, replica) { + return c.wait(ctx, op, v1.BackupConditionReasonClusterNotReady, + fmt.Sprintf("replica %s chosen for the operation is not reachable", replica)) + } + } else { + replica, ok = pickBackupReplica(ctx, cluster, executor) + if !ok { + return c.wait(ctx, op, v1.BackupConditionReasonClusterNotReady, "no replica of the cluster is reachable") + } + + // Recorded before the statement is submitted: a retry has to reach the same replica, the only one + // that knows whether the operation was already accepted. + op.Status.Replica = &v1.BackupReplica{ShardID: replica.ShardID, Index: replica.Index} + if err := c.Status().Update(ctx, op.Object); err != nil { + return statusUpdateResult(err) + } } if stmt.usesServerCredentials() { @@ -558,16 +573,24 @@ func (*BackupController) setCompleted(op *backupOperation, status metav1.Conditi }) } +// assignedBackupReplica returns the replica an earlier attempt recorded, unless it left the cluster. +func assignedBackupReplica(op *backupOperation, cluster *v1.ClickHouseCluster) (v1.ClickHouseReplicaID, bool) { + if op.Status.Replica == nil { + return v1.ClickHouseReplicaID{}, false + } + + id := v1.ClickHouseReplicaID{ShardID: op.Status.Replica.ShardID, Index: op.Status.Replica.Index} + if id.ShardID >= cluster.Shards() || id.Index >= cluster.Replicas() { + return v1.ClickHouseReplicaID{}, false + } + + return id, true +} + // pickBackupReplica returns the first replica that accepts connections. -// The order is stable, so a repeated submission reaches the replica that already knows the operation. func pickBackupReplica(ctx context.Context, cluster *v1.ClickHouseCluster, executor backupExecutor) (v1.ClickHouseReplicaID, bool) { for id := range cluster.ReplicaIDs() { - pingCtx, cancel := context.WithTimeout(ctx, chctrl.LoadReplicaStateTimeout) - err := executor.Ping(pingCtx, id) - - cancel() - - if err == nil { + if backupReplicaReachable(ctx, executor, id) { return id, true } } @@ -575,6 +598,13 @@ func pickBackupReplica(ctx context.Context, cluster *v1.ClickHouseCluster, execu return v1.ClickHouseReplicaID{}, false } +func backupReplicaReachable(ctx context.Context, executor backupExecutor, id v1.ClickHouseReplicaID) bool { + ctx, cancel := context.WithTimeout(ctx, chctrl.LoadReplicaStateTimeout) + defer cancel() + + return executor.Ping(ctx, id) == nil +} + // errorSummary drops the stack trace ClickHouse appends to the stored error and limits the message size. func errorSummary(message string) string { if idx := strings.Index(message, ", Stack trace"); idx >= 0 { diff --git a/internal/controller/clickhouse/backup_controller_test.go b/internal/controller/clickhouse/backup_controller_test.go index 8bc0b5346..f884af683 100644 --- a/internal/controller/clickhouse/backup_controller_test.go +++ b/internal/controller/clickhouse/backup_controller_test.go @@ -460,6 +460,47 @@ var _ = When("reconciling backup resources", Ordered, func() { Expect(completedCondition(incremental.Status.Conditions).Reason).To(Equal(v1.BackupConditionReasonBackupFailed)) }) + It("should record the replica before submitting the backup", func(ctx context.Context) { + backup := newBackup(ctx, "recorded") + executor.startErr = errors.New("connection lost") + + _, err := backupReconciler{controller}.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKeyFromObject(backup)}) + Expect(err).To(MatchError(ContainSubstring("connection lost"))) + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(backup), backup)).To(Succeed()) + Expect(backup.Status.Replica).To(Equal(&v1.BackupReplica{ShardID: 0, Index: 0})) + Expect(backup.Status.ID).To(BeEmpty()) + + executor.startErr = nil + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(executor.replicas).To(Equal([]v1.ClickHouseReplicaID{{ShardID: 0, Index: 0}})) + }) + + It("should submit a retried backup to the replica chosen first", func(ctx context.Context) { + backup := newBackup(ctx, "assigned") + backup.Status.Replica = &v1.BackupReplica{ShardID: 0, Index: 1} + Expect(suite.Client.Status().Update(ctx, backup)).To(Succeed()) + + By("waiting while the chosen replica is unreachable") + + executor.unreachable = true + + result := reconcileBackup(ctx, backup) + Expect(result.RequeueAfter).To(Equal(backupWaitInterval)) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhasePending)) + Expect(executor.queries).To(BeEmpty()) + + By("submitting to it once it is back") + + executor.unreachable = false + + reconcileBackup(ctx, backup) + Expect(backup.Status.Phase).To(Equal(v1.BackupPhaseRunning)) + Expect(backup.Status.Replica).To(Equal(&v1.BackupReplica{ShardID: 0, Index: 1})) + Expect(executor.replicas).To(Equal([]v1.ClickHouseReplicaID{{ShardID: 0, Index: 1}})) + }) + It("should reject invalid specs", func(ctx context.Context) { By("changing the spec of a created backup") @@ -851,6 +892,41 @@ var _ = When("reconciling backup resources", Ordered, func() { Expect(names()).To(ContainElements(nextFull.Name, newIncremental.Name)) }) + It("should take the next full backup when the history is shorter than the chain", func(ctx context.Context) { + scheduled := newScheduled(ctx, "short-history", func(s *v1.ClickHouseScheduledBackup) { + s.Spec.FullBackupInterval = new(int32(4)) + s.Spec.SuccessfulBackupsHistoryLimit = new(int32(1)) + }) + + full := runBackup(ctx, scheduled, true) + + for range 3 { + incremental := runBackup(ctx, scheduled, true) + Expect(incremental.Spec.BaseBackupRef).To(Equal(&corev1.LocalObjectReference{Name: full.Name})) + } + + next := runBackup(ctx, scheduled, true) + Expect(next.Spec.BaseBackupRef).To(BeNil()) + + By("dropping the previous chain") + + reconcileScheduled(ctx, scheduled) + + for _, backup := range ownedBackups(ctx, scheduled) { + Expect(backup.Name).NotTo(Equal(full.Name)) + Expect(backup.Spec.BaseBackupRef).NotTo(Equal(&corev1.LocalObjectReference{Name: full.Name})) + } + }) + + It("should evaluate the schedule in UTC unless a time zone is set", func() { + // Midnight in a zone five hours ahead of UTC, as an operator process running there would see it. + at := time.Date(2026, time.January, 1, 0, 0, 0, 0, time.FixedZone("east", 5*60*60)) + + schedule, err := parseBackupSchedule(v1.ClickHouseScheduledBackupSpec{Schedule: "0 2 * * *"}) + Expect(err).NotTo(HaveOccurred()) + Expect(schedule.Next(at).UTC()).To(Equal(time.Date(2026, time.January, 1, 2, 0, 0, 0, time.UTC))) + }) + It("should reject invalid specs", func(ctx context.Context) { scheduled := &v1.ClickHouseScheduledBackup{ Name: "with-base", Namespace: namespace, diff --git a/internal/controller/clickhouse/scheduledbackup_controller.go b/internal/controller/clickhouse/scheduledbackup_controller.go index 44684815f..f44782883 100644 --- a/internal/controller/clickhouse/scheduledbackup_controller.go +++ b/internal/controller/clickhouse/scheduledbackup_controller.go @@ -246,12 +246,13 @@ func (*ScheduledBackupController) setScheduled( //nolint:ireturn // the cron parser returns the interface func parseBackupSchedule(spec v1.ClickHouseScheduledBackupSpec) (cron.Schedule, error) { - expression := spec.Schedule + // The location is always explicit: without it the parser follows the time zone of the operator process. + timeZone := "UTC" if spec.TimeZone != nil && *spec.TimeZone != "" { - expression = fmt.Sprintf("CRON_TZ=%s %s", *spec.TimeZone, spec.Schedule) + timeZone = *spec.TimeZone } - schedule, err := cron.ParseStandard(expression) + schedule, err := cron.ParseStandard(fmt.Sprintf("CRON_TZ=%s %s", timeZone, spec.Schedule)) if err != nil { return nil, fmt.Errorf("parse schedule %q: %w", spec.Schedule, err) } @@ -318,7 +319,8 @@ func incrementalBase(backups []v1.ClickHouseBackup, interval *int32) string { } // expiredBackups selects the finished backups that exceed the history limits. -// The most recent full backup and the base backups of the kept backups are never selected. +// The most recent full backup, the incremental backups based on it and the base backups of the kept +// backups are never selected. func expiredBackups(backups []v1.ClickHouseBackup, successfulLimit, failedLimit *int32) map[string]struct{} { var completed, failed []*v1.ClickHouseBackup @@ -339,36 +341,47 @@ func expiredBackups(backups []v1.ClickHouseBackup, successfulLimit, failedLimit } } - expired := map[string]struct{}{} + // The chain of the most recent full backup is kept whole: incrementalBase counts its incremental + // backups to decide when the next full backup is due. + for _, full := range slices.Backward(completed) { + if full.IsIncremental() { + continue + } - if failedLimit != nil && len(failed) > int(*failedLimit) { - for _, backup := range failed[:len(failed)-int(*failedLimit)] { - expired[backup.Name] = struct{}{} + protected[full.Name] = struct{}{} + + for i := range backups { + if backups[i].IsIncremental() && backups[i].Spec.BaseBackupRef.Name == full.Name { + protected[backups[i].Name] = struct{}{} + } } - } - if successfulLimit == nil || len(completed) <= int(*successfulLimit) { - return expired + break } - kept := completed[len(completed)-int(*successfulLimit):] - for _, backup := range kept { - protectBase(protected, backup) + if successfulLimit != nil && len(completed) > int(*successfulLimit) { + for _, backup := range completed[len(completed)-int(*successfulLimit):] { + protectBase(protected, backup) + } } - for _, c := range slices.Backward(completed) { - if !c.IsIncremental() { - protected[c.Name] = struct{}{} - break + expired := map[string]struct{}{} + + expire := func(finished []*v1.ClickHouseBackup, limit *int32) { + if limit == nil || len(finished) <= int(*limit) { + return } - } - for _, backup := range completed[:len(completed)-int(*successfulLimit)] { - if _, ok := protected[backup.Name]; !ok { - expired[backup.Name] = struct{}{} + for _, backup := range finished[:len(finished)-int(*limit)] { + if _, ok := protected[backup.Name]; !ok { + expired[backup.Name] = struct{}{} + } } } + expire(failed, failedLimit) + expire(completed, successfulLimit) + return expired }