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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -98,6 +98,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
Expand All @@ -114,6 +115,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
Expand Down
24 changes: 24 additions & 0 deletions PROJECT
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,28 @@ resources:
kind: ClickHouseCluster
path: github.com/ClickHouse/clickhouse-operator/api/v1alpha2
version: v1alpha2
- 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"
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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:
Expand Down
222 changes: 222 additions & 0 deletions api/v1alpha1/clickhousebackup_types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
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 chosen to execute the operation. It is recorded before the operation
// is submitted.
// +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"`
}
87 changes: 87 additions & 0 deletions api/v1alpha1/clickhouserestore_types.go
Original file line number Diff line number Diff line change
@@ -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"`
}
Loading