From 3048c437b070dd1e814cdfd126ffefd616e60872 Mon Sep 17 00:00:00 2001 From: Vasiliy Koshkin <61789920+melancholictheory@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:00:04 +0300 Subject: [PATCH 1/4] feat: support multi-cluster Keeper and ClickHouse deployments Add replicaIDOffset and externalPeers to KeeperCluster, and shardIDOffset, replicaIDOffset, and externalReplicas to ClickHouseCluster so a single logical Keeper ensemble and ClickHouse cluster can span multiple Kubernetes clusters or regions. Fixes #144 --- api/v1alpha1/clickhousecluster_types.go | 121 ++++++++++- api/v1alpha1/keepercluster_types.go | 86 +++++++- api/v1alpha1/types_test.go | 68 ++++++ api/v1alpha1/zz_generated.deepcopy.go | 40 ++++ .../clickhouse.com_clickhouseclusters.yaml | 89 ++++++++ .../bases/clickhouse.com_keeperclusters.yaml | 91 +++++++- dist/chart-cluster/values.yaml | 32 ++- .../clickhouseclusters.clickhouse.com.yaml | 89 ++++++++ .../crd/keeperclusters.clickhouse.com.yaml | 91 +++++++- docs/guides/configuration.mdx | 140 +++++++++++++ docs/reference/api-reference.mdx | 48 ++++- internal/controller/clickhouse/commands.go | 142 +++++++++++-- .../controller/clickhouse/commands_test.go | 31 ++- internal/controller/clickhouse/config.go | 125 ++++++++--- internal/controller/clickhouse/config_test.go | 117 +++++++++++ internal/controller/clickhouse/schemasync.go | 2 +- internal/controller/clickhouse/sync.go | 31 ++- internal/controller/clickhouse/templates.go | 7 +- .../clickhouse/templates/cluster.yaml.tmpl | 12 +- internal/controller/keeper/constants.go | 6 +- internal/controller/keeper/controller.go | 6 +- internal/controller/keeper/sync.go | 107 ++++++++-- internal/controller/keeper/sync_test.go | 197 ++++++++++++++++++ internal/controller/keeper/templates.go | 26 ++- internal/validation_constants.go | 5 + .../v1alpha1/clickhousecluster_webhook.go | 73 +++++++ .../clickhousecluster_webhook_test.go | 90 ++++++++ .../webhook/v1alpha1/keepercluster_webhook.go | 81 ++++++- .../v1alpha1/keepercluster_webhook_test.go | 119 +++++++++++ 29 files changed, 1962 insertions(+), 110 deletions(-) diff --git a/api/v1alpha1/clickhousecluster_types.go b/api/v1alpha1/clickhousecluster_types.go index 0bf998af4..417b12c07 100644 --- a/api/v1alpha1/clickhousecluster_types.go +++ b/api/v1alpha1/clickhousecluster_types.go @@ -36,6 +36,7 @@ func (s *ClickHouseNetworkPolicySpec) Enabled() bool { // ClickHouseClusterSpec defines the desired state of ClickHouseCluster. // +kubebuilder:validation:XValidation:rule="has(self.keeperClusterRef) != has(self.externalKeeper)",message="exactly one of keeperClusterRef or externalKeeper must be set" +// +kubebuilder:validation:XValidation:rule="!has(self.externalReplicas) || self.externalReplicas.all(r, r.shard < (has(self.shardIDOffset) ? self.shardIDOffset : 0) || r.shard >= (has(self.shardIDOffset) ? self.shardIDOffset : 0) + (has(self.shards) ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))",message="externalReplicas must not collide with locally managed shard and replica IDs" type ClickHouseClusterSpec struct { // Number of replicas in the single shard. // +optional @@ -50,6 +51,33 @@ type ClickHouseClusterSpec struct { // +kubebuilder:validation:Minimum=0 Shards *int32 `json:"shards"` + // ShardIDOffset is the starting shard index for locally managed shards. + // Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters. + // Defaults to 0. Cannot be changed after cluster creation. + // +optional + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + ShardIDOffset int32 `json:"shardIDOffset,omitempty"` + + // ReplicaIDOffset is the starting replica index within each shard for locally managed replicas. + // Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards + // (for example 0, 10, 20 to leave room for independent scaling in each cluster). + // Defaults to 0. Cannot be changed after cluster creation. + // +optional + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + ReplicaIDOffset int32 `json:"replicaIDOffset,omitempty"` + + // ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster + // (for example, by another clickhouse-operator instance in a different cluster or region). + // The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + // without creating Kubernetes workloads for them. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=256 + // +kubebuilder:validation:XValidation:rule="self.all(r, self.exists_one(m, m.shard == r.shard && m.replica == r.replica))",message="externalReplicas must not repeat the same shard and replica" + ExternalReplicas []ExternalClickHouseReplica `json:"externalReplicas,omitempty"` + // Reference to the KeeperCluster that is used for ClickHouse coordination. // When namespace is omitted, the ClickHouseCluster namespace is used. // Mutually exclusive with `externalKeeper`, exactly one of them must be set. @@ -406,6 +434,51 @@ type ExternalKeeperNode struct { Port int32 `json:"port,omitempty"` } +// ExternalReplicaTLSPolicy controls how remote_servers connects to an external ClickHouse replica. +// +kubebuilder:validation:Enum=Enabled;Disabled +type ExternalReplicaTLSPolicy string + +const ( + // ExternalReplicaTLSEnabled makes remote_servers connect to the external replica over TLS. + ExternalReplicaTLSEnabled ExternalReplicaTLSPolicy = "Enabled" + // ExternalReplicaTLSDisabled is the default policy: connections are made in plain text. + ExternalReplicaTLSDisabled ExternalReplicaTLSPolicy = "Disabled" +) + +// ExternalClickHouseReplica addresses a single ClickHouse replica managed outside this Kubernetes cluster. +type ExternalClickHouseReplica struct { + // Shard is the shard index this external replica belongs to. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + Shard int32 `json:"shard"` + + // Replica is the replica index within the shard. + // Must not collide with any locally managed replica in the same shard. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + Replica int32 `json:"replica"` + + // Host is the DNS name or IP address of the external ClickHouse replica reachable from this cluster. + // IPv6 addresses must be enclosed in square brackets. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Host string `json:"host"` + + // Port is the native TCP port used for remote_servers communication. + // Defaults to 9001 (the operator internal management TCP port). + // +optional + // +kubebuilder:default:=9001 + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + Port int32 `json:"port,omitempty"` + + // TLS controls whether remote_servers connects to this external replica over TLS. + // Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. + // +optional + // +kubebuilder:default:=Disabled + TLS ExternalReplicaTLSPolicy `json:"tls,omitempty"` +} + // ClickHouseCluster is the Schema for the `clickhouseclusters` API. // +kubebuilder:object:root=true // +kubebuilder:subresource:status @@ -540,11 +613,33 @@ func (v *ClickHouseCluster) Replicas() int32 { return *v.Spec.Replicas } -// ReplicaIDs returns sequence of ClickHouseReplicaID for every replica in the ClickHouseCluster. +// ShardIDs returns sequence of locally managed shard IDs in the ClickHouseCluster. +func (v *ClickHouseCluster) ShardIDs() iter.Seq[int32] { + return func(yield func(int32) bool) { + for i := range v.Shards() { + if !yield(v.Spec.ShardIDOffset + i) { + return + } + } + } +} + +// ReplicaIndexes returns sequence of locally managed replica indexes within each shard. +func (v *ClickHouseCluster) ReplicaIndexes() iter.Seq[int32] { + return func(yield func(int32) bool) { + for i := range v.Replicas() { + if !yield(v.Spec.ReplicaIDOffset + i) { + return + } + } + } +} + +// ReplicaIDs returns sequence of ClickHouseReplicaID for every locally managed replica in the ClickHouseCluster. func (v *ClickHouseCluster) ReplicaIDs() iter.Seq[ClickHouseReplicaID] { return func(yield func(ClickHouseReplicaID) bool) { - for shard := range v.Shards() { - for index := range v.Replicas() { + for shard := range v.ShardIDs() { + for index := range v.ReplicaIndexes() { if !yield(ClickHouseReplicaID{ShardID: shard, Index: index}) { return } @@ -553,9 +648,25 @@ func (v *ClickHouseCluster) ReplicaIDs() iter.Seq[ClickHouseReplicaID] { } } -// ReplicaObsolete reports whether the replica is outside the desired shard and replica counts and is due for removal. +// ShardObsolete reports whether the shard ID is outside the desired local shard range. +func (v *ClickHouseCluster) ShardObsolete(shardID int32) bool { + return shardID < v.Spec.ShardIDOffset || shardID >= v.Spec.ShardIDOffset+v.Shards() +} + +// ReplicaObsolete reports whether the replica is outside the desired local shard and replica ranges and is due for removal. func (v *ClickHouseCluster) ReplicaObsolete(id ClickHouseReplicaID) bool { - return id.ShardID >= v.Shards() || id.Index >= v.Replicas() + return v.ShardObsolete(id.ShardID) || id.Index < v.Spec.ReplicaIDOffset || id.Index >= v.Spec.ReplicaIDOffset+v.Replicas() +} + +// IsExternalReplica reports whether the replica ID matches a configured external replica. +func (v *ClickHouseCluster) IsExternalReplica(id ClickHouseReplicaID) bool { + for _, ext := range v.Spec.ExternalReplicas { + if ext.Shard == id.ShardID && ext.Replica == id.Index { + return true + } + } + + return false } // HeadlessServiceName returns name of the headless service for the ClickHouseCluster. diff --git a/api/v1alpha1/keepercluster_types.go b/api/v1alpha1/keepercluster_types.go index 3a1576a2e..ad339d3f1 100644 --- a/api/v1alpha1/keepercluster_types.go +++ b/api/v1alpha1/keepercluster_types.go @@ -2,6 +2,7 @@ package v1alpha1 import ( "fmt" + "iter" "strconv" corev1 "k8s.io/api/core/v1" @@ -33,14 +34,38 @@ func (s *KeeperNetworkPolicySpec) Enabled() bool { } // KeeperClusterSpec defines the desired state of KeeperCluster. +// +kubebuilder:validation:XValidation:rule="(has(self.externalPeers) && size(self.externalPeers) > 0) || !has(self.replicas) || self.replicas == 0 || self.replicas % 2 == 1",message="replicas must be odd (or 0) unless externalPeers is configured" +// +kubebuilder:validation:XValidation:rule="!has(self.externalPeers) || (has(self.replicas) ? self.replicas : 3) + size(self.externalPeers) <= 15",message="total Keeper ensemble size (replicas + externalPeers) must not exceed 15" +// +kubebuilder:validation:XValidation:rule="!has(self.externalPeers) || self.externalPeers.all(p, p.id < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))",message="externalPeers must not collide with locally managed replica IDs" type KeeperClusterSpec struct { - // Number of replicas in the cluster + // Number of locally managed replicas in the cluster. + // Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, + // as long as replicas + len(externalPeers) <= 15. // +optional // +kubebuilder:default:=3 - // +kubebuilder:validation:Enum=0;1;3;5;7;9;11;13;15 + // +kubebuilder:validation:Enum=0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15 // +operator-sdk:csv:customresourcedefinitions:type=spec,displayName="Replica count" Replicas *int32 `json:"replicas"` + // ReplicaIDOffset is the starting Raft server ID for locally managed replicas. + // Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble + // (for example 0, 10, 20 to leave room for independent scaling in each cluster). + // Defaults to 0. Cannot be changed after cluster creation. + // +optional + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + ReplicaIDOffset int32 `json:"replicaIDOffset,omitempty"` + + // ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster + // (for example, by another clickhouse-operator instance in a different cluster or region). + // The operator includes them in raft_configuration without creating Kubernetes workloads for them. + // +optional + // +listType=atomic + // +kubebuilder:validation:MaxItems=14 + // +kubebuilder:validation:XValidation:rule="self.all(p, self.exists_one(q, q.id == p.id))",message="externalPeers must not repeat the same id" + // +kubebuilder:validation:XValidation:rule="self.all(p, self.exists_one(q, q.host.lowerAscii() == p.host.lowerAscii() && q.port == p.port))",message="externalPeers must not repeat the same host and port" + ExternalPeers []ExternalKeeperPeer `json:"externalPeers,omitempty"` + // Parameters passed to the Keeper pod spec. // +optional PodTemplate PodTemplateSpec `json:"podTemplate,omitempty"` @@ -139,6 +164,37 @@ func (s *KeeperClusterSpec) WithDefaults() { } } +// ExternalKeeperPeer addresses a single Raft peer of a Keeper ensemble managed outside this Kubernetes cluster. +type ExternalKeeperPeer struct { + // ID is the unique Raft server ID of the external peer. + // Must not collide with any locally managed replica ID or another external peer ID. + // +kubebuilder:validation:Minimum=0 + // +kubebuilder:validation:Maximum=10000 + ID int32 `json:"id"` + + // Host is the DNS name or IP address of the external peer reachable from this cluster. + // IPv6 addresses must be enclosed in square brackets. + // +kubebuilder:validation:MinLength=1 + // +kubebuilder:validation:MaxLength=253 + Host string `json:"host"` + + // Port is the Raft inter-server communication port of the external peer. + // Defaults to 9234. + // +optional + // +kubebuilder:default:=9234 + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + Port int32 `json:"port,omitempty"` + + // ClientPort is the Keeper client port of the external peer, used when a ClickHouseCluster + // references this KeeperCluster via keeperClusterRef. + // When omitted, defaults to 2181 (or 2281 when TLS is enabled on this KeeperCluster). + // +optional + // +kubebuilder:validation:Minimum=1 + // +kubebuilder:validation:Maximum=65535 + ClientPort int32 `json:"clientPort,omitempty"` +} + // KeeperSettings defines ClickHouse Keeper server configuration. type KeeperSettings struct { // Configuration of ClickHouse Keeper server logging. @@ -324,15 +380,37 @@ func (v *KeeperCluster) StatefulSetNameByReplicaID(replicaID KeeperReplicaID) st return v.SpecificResourceName(fmt.Sprintf("%d", replicaID)) } +// ReplicaIDs returns sequence of KeeperReplicaID for every locally managed replica in the KeeperCluster. +func (v *KeeperCluster) ReplicaIDs() iter.Seq[KeeperReplicaID] { + return func(yield func(KeeperReplicaID) bool) { + for i := range v.Replicas() { + if !yield(KeeperReplicaID(v.Spec.ReplicaIDOffset + i)) { + return + } + } + } +} + +// IsExternalPeer reports whether the given Raft server ID belongs to a configured external peer. +func (v *KeeperCluster) IsExternalPeer(id KeeperReplicaID) bool { + for _, peer := range v.Spec.ExternalPeers { + if KeeperReplicaID(peer.ID) == id { + return true + } + } + + return false +} + // HostnameByID returns domain name for the specific replica to access within Kubernetes cluster. func (v *KeeperCluster) HostnameByID(id KeeperReplicaID) string { return formatPodHostname(v.StatefulSetNameByReplicaID(id), v.HeadlessServiceName(), v.Namespace, v.Spec.ClusterDomain) } -// Hostnames returns list of domain names for all replicas to access within Kubernetes cluster. +// Hostnames returns list of domain names for all locally managed replicas to access within Kubernetes cluster. func (v *KeeperCluster) Hostnames() []string { hostnames := make([]string, 0, v.Replicas()) - for id := range KeeperReplicaID(v.Replicas()) { + for id := range v.ReplicaIDs() { hostnames = append(hostnames, v.HostnameByID(id)) } diff --git a/api/v1alpha1/types_test.go b/api/v1alpha1/types_test.go index 7b1b172bf..976564a33 100644 --- a/api/v1alpha1/types_test.go +++ b/api/v1alpha1/types_test.go @@ -1,6 +1,7 @@ package v1alpha1 import ( + "slices" "testing" . "github.com/onsi/ginkgo/v2" @@ -52,6 +53,31 @@ var _ = Describe("KeeperCluster", func() { Expect(hostname).To(Equal("test-keeper-2-0.test-keeper-headless.test-ns.svc.internal.corp.example.com")) }) }) + + Describe("ReplicaIDs and ExternalPeers", func() { + It("should apply replicaIDOffset to ReplicaIDs and Hostnames", func() { + keeper := &KeeperCluster{ + Name: "test", + Namespace: "test-ns", + Spec: KeeperClusterSpec{ + Replicas: new(int32(2)), + ReplicaIDOffset: 10, + ClusterDomain: "k8s.dc2", + ExternalPeers: []ExternalKeeperPeer{ + {ID: 0, Host: "test-keeper-0-0.test-keeper-headless.test-ns.svc.k8s.dc1"}, + }, + }, + } + + Expect(slices.Collect(keeper.ReplicaIDs())).To(Equal([]KeeperReplicaID{10, 11})) + Expect(keeper.Hostnames()).To(Equal([]string{ + "test-keeper-10-0.test-keeper-headless.test-ns.svc.k8s.dc2", + "test-keeper-11-0.test-keeper-headless.test-ns.svc.k8s.dc2", + })) + Expect(keeper.IsExternalPeer(0)).To(BeTrue()) + Expect(keeper.IsExternalPeer(10)).To(BeFalse()) + }) + }) }) var _ = Describe("ClickHouseCluster", func() { @@ -182,4 +208,46 @@ var _ = Describe("ClickHouseCluster", func() { Expect(res).To(HaveSuffix(suffix), res) }) }) + + Describe("Multi-cluster offsets and ExternalReplicas", func() { + It("should compute ShardIDs, ReplicaIndexes, ReplicaIDs, and obsolescence with offsets", func() { + cluster := &ClickHouseCluster{ + Name: "test", + Namespace: "test-ns", + Spec: ClickHouseClusterSpec{ + Shards: new(int32(2)), + Replicas: new(int32(2)), + ShardIDOffset: 1, + ReplicaIDOffset: 10, + ExternalReplicas: []ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "ch-dc1-0-0"}, + {Shard: 1, Replica: 0, Host: "ch-dc1-1-0"}, + }, + }, + } + + Expect(slices.Collect(cluster.ShardIDs())).To(Equal([]int32{1, 2})) + Expect(slices.Collect(cluster.ReplicaIndexes())).To(Equal([]int32{10, 11})) + Expect(slices.Collect(cluster.ReplicaIDs())).To(Equal([]ClickHouseReplicaID{ + {ShardID: 1, Index: 10}, + {ShardID: 1, Index: 11}, + {ShardID: 2, Index: 10}, + {ShardID: 2, Index: 11}, + })) + + Expect(cluster.ShardObsolete(0)).To(BeTrue()) + Expect(cluster.ShardObsolete(1)).To(BeFalse()) + Expect(cluster.ShardObsolete(2)).To(BeFalse()) + Expect(cluster.ShardObsolete(3)).To(BeTrue()) + + Expect(cluster.ReplicaObsolete(ClickHouseReplicaID{ShardID: 1, Index: 10})).To(BeFalse()) + Expect(cluster.ReplicaObsolete(ClickHouseReplicaID{ShardID: 1, Index: 9})).To(BeTrue()) + Expect(cluster.ReplicaObsolete(ClickHouseReplicaID{ShardID: 1, Index: 12})).To(BeTrue()) + Expect(cluster.ReplicaObsolete(ClickHouseReplicaID{ShardID: 0, Index: 10})).To(BeTrue()) + + Expect(cluster.IsExternalReplica(ClickHouseReplicaID{ShardID: 0, Index: 0})).To(BeTrue()) + Expect(cluster.IsExternalReplica(ClickHouseReplicaID{ShardID: 1, Index: 0})).To(BeTrue()) + Expect(cluster.IsExternalReplica(ClickHouseReplicaID{ShardID: 1, Index: 10})).To(BeFalse()) + }) + }) }) diff --git a/api/v1alpha1/zz_generated.deepcopy.go b/api/v1alpha1/zz_generated.deepcopy.go index 78e3f4754..28cf439f7 100644 --- a/api/v1alpha1/zz_generated.deepcopy.go +++ b/api/v1alpha1/zz_generated.deepcopy.go @@ -130,6 +130,11 @@ func (in *ClickHouseClusterSpec) DeepCopyInto(out *ClickHouseClusterSpec) { *out = new(int32) **out = **in } + if in.ExternalReplicas != nil { + in, out := &in.ExternalReplicas, &out.ExternalReplicas + *out = make([]ExternalClickHouseReplica, len(*in)) + copy(*out, *in) + } if in.KeeperClusterRef != nil { in, out := &in.KeeperClusterRef, &out.KeeperClusterRef *out = new(KeeperClusterReference) @@ -439,6 +444,21 @@ func (in *EncryptionSettings) DeepCopy() *EncryptionSettings { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalClickHouseReplica) DeepCopyInto(out *ExternalClickHouseReplica) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalClickHouseReplica. +func (in *ExternalClickHouseReplica) DeepCopy() *ExternalClickHouseReplica { + if in == nil { + return nil + } + out := new(ExternalClickHouseReplica) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExternalKeeperNode) DeepCopyInto(out *ExternalKeeperNode) { *out = *in @@ -454,6 +474,21 @@ func (in *ExternalKeeperNode) DeepCopy() *ExternalKeeperNode { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ExternalKeeperPeer) DeepCopyInto(out *ExternalKeeperPeer) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalKeeperPeer. +func (in *ExternalKeeperPeer) DeepCopy() *ExternalKeeperPeer { + if in == nil { + return nil + } + out := new(ExternalKeeperPeer) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExternalKeeperSpec) DeepCopyInto(out *ExternalKeeperSpec) { *out = *in @@ -586,6 +621,11 @@ func (in *KeeperClusterSpec) DeepCopyInto(out *KeeperClusterSpec) { *out = new(int32) **out = **in } + if in.ExternalPeers != nil { + in, out := &in.ExternalPeers, &out.ExternalPeers + *out = make([]ExternalKeeperPeer, len(*in)) + copy(*out, *in) + } in.PodTemplate.DeepCopyInto(&out.PodTemplate) in.ContainerTemplate.DeepCopyInto(&out.ContainerTemplate) if in.DataVolumeClaimSpec != nil { diff --git a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml index 8053101cb..46d37faa1 100644 --- a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml +++ b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml @@ -1036,6 +1036,68 @@ spec: required: - nodes type: object + externalReplicas: + description: |- + ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster + (for example, by another clickhouse-operator instance in a different cluster or region). + The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + without creating Kubernetes workloads for them. + items: + description: ExternalClickHouseReplica addresses a single ClickHouse + replica managed outside this Kubernetes cluster. + properties: + host: + description: |- + Host is the DNS name or IP address of the external ClickHouse replica reachable from this cluster. + IPv6 addresses must be enclosed in square brackets. + maxLength: 253 + minLength: 1 + type: string + port: + default: 9001 + description: |- + Port is the native TCP port used for remote_servers communication. + Defaults to 9001 (the operator internal management TCP port). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + replica: + description: |- + Replica is the replica index within the shard. + Must not collide with any locally managed replica in the same shard. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + shard: + description: Shard is the shard index this external replica + belongs to. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + tls: + default: Disabled + description: |- + TLS controls whether remote_servers connects to this external replica over TLS. + Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. + enum: + - Enabled + - Disabled + type: string + required: + - host + - replica + - shard + type: object + maxItems: 256 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: externalReplicas must not repeat the same shard and replica + rule: self.all(r, self.exists_one(m, m.shard == r.shard && m.replica + == r.replica)) externalSecret: description: |- ExternalSecret is an optional reference to an externally-managed Secret containing cluster secrets. @@ -3485,6 +3547,16 @@ spec: x-kubernetes-validations: - message: topologyMinDomains requires topologyZoneKey rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' + replicaIDOffset: + description: |- + ReplicaIDOffset is the starting replica index within each shard for locally managed replicas. + Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards + (for example 0, 10, 20 to leave room for independent scaling in each cluster). + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer replicas: default: 3 description: Number of replicas in the single shard. @@ -3682,6 +3754,15 @@ spec: x-kubernetes-validations: - message: encryption cannot be disabled after it has been enabled rule: '!has(oldSelf.encryption) || has(self.encryption)' + shardIDOffset: + description: |- + ShardIDOffset is the starting shard index for locally managed shards. + Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters. + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer shards: default: 1 description: Number of shards in the cluster. @@ -3996,6 +4077,14 @@ spec: x-kubernetes-validations: - message: exactly one of keeperClusterRef or externalKeeper must be set rule: has(self.keeperClusterRef) != has(self.externalKeeper) + - message: externalReplicas must not collide with locally managed shard + and replica IDs + rule: '!has(self.externalReplicas) || self.externalReplicas.all(r, r.shard + < (has(self.shardIDOffset) ? self.shardIDOffset : 0) || r.shard >= + (has(self.shardIDOffset) ? self.shardIDOffset : 0) + (has(self.shards) + ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset + : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset + : 0) + (has(self.replicas) ? self.replicas : 3))' status: description: ClickHouseClusterStatus defines the observed state of ClickHouseCluster. properties: diff --git a/config/crd/bases/clickhouse.com_keeperclusters.yaml b/config/crd/bases/clickhouse.com_keeperclusters.yaml index 03a72b21f..8f82a4c70 100644 --- a/config/crd/bases/clickhouse.com_keeperclusters.yaml +++ b/config/crd/bases/clickhouse.com_keeperclusters.yaml @@ -821,6 +821,61 @@ spec: volumeName: type: string type: object + externalPeers: + description: |- + ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster + (for example, by another clickhouse-operator instance in a different cluster or region). + The operator includes them in raft_configuration without creating Kubernetes workloads for them. + items: + description: ExternalKeeperPeer addresses a single Raft peer of + a Keeper ensemble managed outside this Kubernetes cluster. + properties: + clientPort: + description: |- + ClientPort is the Keeper client port of the external peer, used when a ClickHouseCluster + references this KeeperCluster via keeperClusterRef. + When omitted, defaults to 2181 (or 2281 when TLS is enabled on this KeeperCluster). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + host: + description: |- + Host is the DNS name or IP address of the external peer reachable from this cluster. + IPv6 addresses must be enclosed in square brackets. + maxLength: 253 + minLength: 1 + type: string + id: + description: |- + ID is the unique Raft server ID of the external peer. + Must not collide with any locally managed replica ID or another external peer ID. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + port: + default: 9234 + description: |- + Port is the Raft inter-server communication port of the external peer. + Defaults to 9234. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - host + - id + type: object + maxItems: 14 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: externalPeers must not repeat the same id + rule: self.all(p, self.exists_one(q, q.id == p.id)) + - message: externalPeers must not repeat the same host and port + rule: self.all(p, self.exists_one(q, q.host.lowerAscii() == p.host.lowerAscii() + && q.port == p.port)) labels: additionalProperties: type: string @@ -3187,18 +3242,38 @@ spec: x-kubernetes-validations: - message: topologyMinDomains requires topologyZoneKey rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' + replicaIDOffset: + description: |- + ReplicaIDOffset is the starting Raft server ID for locally managed replicas. + Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble + (for example 0, 10, 20 to leave room for independent scaling in each cluster). + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer replicas: default: 3 - description: Number of replicas in the cluster + description: |- + Number of locally managed replicas in the cluster. + Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, + as long as replicas + len(externalPeers) <= 15. enum: - 0 - 1 + - 2 - 3 + - 4 - 5 + - 6 - 7 + - 8 - 9 + - 10 - 11 + - 12 - 13 + - 14 - 15 format: int32 type: integer @@ -3602,6 +3677,20 @@ spec: type: object type: object type: object + x-kubernetes-validations: + - message: replicas must be odd (or 0) unless externalPeers is configured + rule: (has(self.externalPeers) && size(self.externalPeers) > 0) || !has(self.replicas) + || self.replicas == 0 || self.replicas % 2 == 1 + - message: total Keeper ensemble size (replicas + externalPeers) must + not exceed 15 + rule: '!has(self.externalPeers) || (has(self.replicas) ? self.replicas + : 3) + size(self.externalPeers) <= 15' + - message: externalPeers must not collide with locally managed replica + IDs + rule: '!has(self.externalPeers) || self.externalPeers.all(p, p.id < + (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= + (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) + ? self.replicas : 3))' status: description: KeeperClusterStatus defines the observed state of KeeperCluster. properties: diff --git a/dist/chart-cluster/values.yaml b/dist/chart-cluster/values.yaml index c0fabbb83..6e3c0a3c4 100644 --- a/dist/chart-cluster/values.yaml +++ b/dist/chart-cluster/values.yaml @@ -76,6 +76,12 @@ clickhouse: # Mutually exclusive with `keeperClusterRef`, exactly one of them must be set. # externalKeeper: {} + # ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster + # (for example, by another clickhouse-operator instance in a different cluster or region). + # The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + # without creating Kubernetes workloads for them. + # externalReplicas: [] + # ExternalSecret is an optional reference to an externally-managed Secret containing cluster secrets. # The secret must reside in the same namespace as the cluster. # externalSecret: {} @@ -105,12 +111,23 @@ clickhouse: # Parameters passed to the ClickHouse pod spec. # podTemplate: {} + # ReplicaIDOffset is the starting replica index within each shard for locally managed replicas. + # Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards + # (for example 0, 10, 20 to leave room for independent scaling in each cluster). + # Defaults to 0. Cannot be changed after cluster creation. + # replicaIDOffset: 0 + # Number of replicas in the single shard. replicas: 3 # Configuration parameters for ClickHouse server. settings: {} + # ShardIDOffset is the starting shard index for locally managed shards. + # Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters. + # Defaults to 0. Cannot be changed after cluster creation. + # shardIDOffset: 0 + # Number of shards in the cluster. shards: 1 @@ -157,6 +174,11 @@ keeper: # Specification of persistent storage for ClickHouse Keeper data. # dataVolumeClaimSpec: {} + # ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster + # (for example, by another clickhouse-operator instance in a different cluster or region). + # The operator includes them in raft_configuration without creating Kubernetes workloads for them. + # externalPeers: [] + # Additional labels that are added to resources. # labels: {} @@ -171,7 +193,15 @@ keeper: # Parameters passed to the Keeper pod spec. # podTemplate: {} - # Number of replicas in the cluster + # ReplicaIDOffset is the starting Raft server ID for locally managed replicas. + # Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble + # (for example 0, 10, 20 to leave room for independent scaling in each cluster). + # Defaults to 0. Cannot be changed after cluster creation. + # replicaIDOffset: 0 + + # Number of locally managed replicas in the cluster. + # Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, + # as long as replicas + len(externalPeers) <= 15. replicas: 3 # Configuration parameters for ClickHouse Keeper server. diff --git a/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml b/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml index dc6f6fc8c..da9b1c6d7 100644 --- a/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml @@ -1039,6 +1039,68 @@ spec: required: - nodes type: object + externalReplicas: + description: |- + ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster + (for example, by another clickhouse-operator instance in a different cluster or region). + The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + without creating Kubernetes workloads for them. + items: + description: ExternalClickHouseReplica addresses a single ClickHouse + replica managed outside this Kubernetes cluster. + properties: + host: + description: |- + Host is the DNS name or IP address of the external ClickHouse replica reachable from this cluster. + IPv6 addresses must be enclosed in square brackets. + maxLength: 253 + minLength: 1 + type: string + port: + default: 9001 + description: |- + Port is the native TCP port used for remote_servers communication. + Defaults to 9001 (the operator internal management TCP port). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + replica: + description: |- + Replica is the replica index within the shard. + Must not collide with any locally managed replica in the same shard. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + shard: + description: Shard is the shard index this external replica + belongs to. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + tls: + default: Disabled + description: |- + TLS controls whether remote_servers connects to this external replica over TLS. + Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. + enum: + - Enabled + - Disabled + type: string + required: + - host + - replica + - shard + type: object + maxItems: 256 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: externalReplicas must not repeat the same shard and replica + rule: self.all(r, self.exists_one(m, m.shard == r.shard && m.replica + == r.replica)) externalSecret: description: |- ExternalSecret is an optional reference to an externally-managed Secret containing cluster secrets. @@ -3488,6 +3550,16 @@ spec: x-kubernetes-validations: - message: topologyMinDomains requires topologyZoneKey rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' + replicaIDOffset: + description: |- + ReplicaIDOffset is the starting replica index within each shard for locally managed replicas. + Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards + (for example 0, 10, 20 to leave room for independent scaling in each cluster). + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer replicas: default: 3 description: Number of replicas in the single shard. @@ -3685,6 +3757,15 @@ spec: x-kubernetes-validations: - message: encryption cannot be disabled after it has been enabled rule: '!has(oldSelf.encryption) || has(self.encryption)' + shardIDOffset: + description: |- + ShardIDOffset is the starting shard index for locally managed shards. + Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters. + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer shards: default: 1 description: Number of shards in the cluster. @@ -3999,6 +4080,14 @@ spec: x-kubernetes-validations: - message: exactly one of keeperClusterRef or externalKeeper must be set rule: has(self.keeperClusterRef) != has(self.externalKeeper) + - message: externalReplicas must not collide with locally managed shard + and replica IDs + rule: '!has(self.externalReplicas) || self.externalReplicas.all(r, r.shard + < (has(self.shardIDOffset) ? self.shardIDOffset : 0) || r.shard >= + (has(self.shardIDOffset) ? self.shardIDOffset : 0) + (has(self.shards) + ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset + : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset + : 0) + (has(self.replicas) ? self.replicas : 3))' status: description: ClickHouseClusterStatus defines the observed state of ClickHouseCluster. properties: diff --git a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml index 9b369e4da..1c3d34c9b 100644 --- a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml @@ -824,6 +824,61 @@ spec: volumeName: type: string type: object + externalPeers: + description: |- + ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster + (for example, by another clickhouse-operator instance in a different cluster or region). + The operator includes them in raft_configuration without creating Kubernetes workloads for them. + items: + description: ExternalKeeperPeer addresses a single Raft peer of + a Keeper ensemble managed outside this Kubernetes cluster. + properties: + clientPort: + description: |- + ClientPort is the Keeper client port of the external peer, used when a ClickHouseCluster + references this KeeperCluster via keeperClusterRef. + When omitted, defaults to 2181 (or 2281 when TLS is enabled on this KeeperCluster). + format: int32 + maximum: 65535 + minimum: 1 + type: integer + host: + description: |- + Host is the DNS name or IP address of the external peer reachable from this cluster. + IPv6 addresses must be enclosed in square brackets. + maxLength: 253 + minLength: 1 + type: string + id: + description: |- + ID is the unique Raft server ID of the external peer. + Must not collide with any locally managed replica ID or another external peer ID. + format: int32 + maximum: 10000 + minimum: 0 + type: integer + port: + default: 9234 + description: |- + Port is the Raft inter-server communication port of the external peer. + Defaults to 9234. + format: int32 + maximum: 65535 + minimum: 1 + type: integer + required: + - host + - id + type: object + maxItems: 14 + type: array + x-kubernetes-list-type: atomic + x-kubernetes-validations: + - message: externalPeers must not repeat the same id + rule: self.all(p, self.exists_one(q, q.id == p.id)) + - message: externalPeers must not repeat the same host and port + rule: self.all(p, self.exists_one(q, q.host.lowerAscii() == p.host.lowerAscii() + && q.port == p.port)) labels: additionalProperties: type: string @@ -3190,18 +3245,38 @@ spec: x-kubernetes-validations: - message: topologyMinDomains requires topologyZoneKey rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' + replicaIDOffset: + description: |- + ReplicaIDOffset is the starting Raft server ID for locally managed replicas. + Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble + (for example 0, 10, 20 to leave room for independent scaling in each cluster). + Defaults to 0. Cannot be changed after cluster creation. + format: int32 + maximum: 10000 + minimum: 0 + type: integer replicas: default: 3 - description: Number of replicas in the cluster + description: |- + Number of locally managed replicas in the cluster. + Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, + as long as replicas + len(externalPeers) <= 15. enum: - 0 - 1 + - 2 - 3 + - 4 - 5 + - 6 - 7 + - 8 - 9 + - 10 - 11 + - 12 - 13 + - 14 - 15 format: int32 type: integer @@ -3605,6 +3680,20 @@ spec: type: object type: object type: object + x-kubernetes-validations: + - message: replicas must be odd (or 0) unless externalPeers is configured + rule: (has(self.externalPeers) && size(self.externalPeers) > 0) || !has(self.replicas) + || self.replicas == 0 || self.replicas % 2 == 1 + - message: total Keeper ensemble size (replicas + externalPeers) must + not exceed 15 + rule: '!has(self.externalPeers) || (has(self.replicas) ? self.replicas + : 3) + size(self.externalPeers) <= 15' + - message: externalPeers must not collide with locally managed replica + IDs + rule: '!has(self.externalPeers) || self.externalPeers.all(p, p.id < + (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= + (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) + ? self.replicas : 3))' status: description: KeeperClusterStatus defines the observed state of KeeperCluster. properties: diff --git a/docs/guides/configuration.mdx b/docs/guides/configuration.mdx index e3f64e5e1..79603f241 100644 --- a/docs/guides/configuration.mdx +++ b/docs/guides/configuration.mdx @@ -1203,6 +1203,146 @@ spec: name: default-password ``` +## Multi-cluster and multi-region deployments {#multi-cluster} + +You can span a single logical `KeeperCluster` Raft ensemble and `ClickHouseCluster` across multiple +Kubernetes clusters or regions, with an operator instance running in each cluster. Each operator +manages only its local Kubernetes resources while configuring Keeper and ClickHouse to communicate +with remote peers. + +### Prerequisites {#multi-cluster-prerequisites} + +- **Cross-cluster connectivity and DNS**: Pods in each Kubernetes cluster must be able to reach the + headless Service DNS names (or custom hostnames/IPs) of remote Keeper and ClickHouse pods (for + example via Cilium ClusterMesh, Submariner, or CoreDNS forwarding over a mesh/VPN). +- **Per-cluster `clusterDomain`**: Set `spec.clusterDomain` on each cluster's CR to the DNS suffix + remote clusters use to reach its local pods (for example `k8s-cluster.dc1` and `k8s-cluster.dc2`). +- **Shared ClickHouse credentials**: Use [`spec.externalSecret`](#external-secret) with identical + `interserver-password`, `cluster-secret`, `keeper-identity`, and `named-collections-key` values in + every Kubernetes cluster so cross-cluster replication and `remote_servers` authentication succeed. + +### Multi-cluster KeeperCluster {#multi-cluster-keeper} + +Use `spec.replicaIDOffset` and `spec.externalPeers` to assign each Kubernetes cluster a distinct +range of Raft server IDs and list the Raft peers hosted in other clusters. Leave room between offsets +(for example `0`, `10`, `20`) if you plan to scale individual clusters independently. + +When `externalPeers` is configured, `spec.replicas` may be even (for example `2` local replicas plus +`3` external peers for a 5-node Raft ensemble), as long as the total ensemble size does not exceed +`15`. An odd total ensemble size is recommended for Raft fault tolerance. + +```yaml +# Cluster DC1 (local Raft server IDs 0, 1) +apiVersion: clickhouse.com/v1alpha1 +kind: KeeperCluster +metadata: + name: my-keeper +spec: + replicas: 2 + replicaIDOffset: 0 + clusterDomain: k8s-cluster.dc1 + externalPeers: + - id: 10 + host: my-keeper-keeper-10-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc2 + port: 9234 + - id: 11 + host: my-keeper-keeper-11-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc2 + port: 9234 + - id: 20 + host: my-keeper-keeper-20-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc3 + port: 9234 +``` + +```yaml +# Cluster DC2 (local Raft server IDs 10, 11) +apiVersion: clickhouse.com/v1alpha1 +kind: KeeperCluster +metadata: + name: my-keeper +spec: + replicas: 2 + replicaIDOffset: 10 + clusterDomain: k8s-cluster.dc2 + externalPeers: + - id: 0 + host: my-keeper-keeper-0-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc1 + - id: 1 + host: my-keeper-keeper-1-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc1 + - id: 20 + host: my-keeper-keeper-20-0.my-keeper-keeper-headless.default.svc.k8s-cluster.dc3 +``` + +When a `ClickHouseCluster` references a multi-cluster `KeeperCluster` via `keeperClusterRef`, the +operator writes both the local Keeper replicas and `externalPeers` into ClickHouse's `` +configuration (using `clientPort`, defaulting to `2181` or `2281` when TLS is enabled). + +### Multi-cluster ClickHouseCluster {#multi-cluster-clickhouse} + +Use `spec.shardIDOffset`, `spec.replicaIDOffset`, and `spec.externalReplicas` to distribute shards +or replicas of a single ClickHouse cluster across Kubernetes clusters: + +- Set `replicaIDOffset` to place replicas of the same shard in different clusters (active-active HA + and datacenter failover). +- Set `shardIDOffset` to place different shards in different clusters. +- List every remote replica in `externalReplicas` with its `(shard, replica)` coordinates and + reachable `host` (typically the remote replica's internal headless Service + `-clickhouse-internal--..svc.` on port `9001`). + +The operator merges local and external replicas into `remote_servers.default`, preserves external +replicas' metadata during Keeper cleanup, and discovers existing `Replicated` databases from remote +peers when new replicas join. + +```yaml +# Cluster DC1 (shard 0, local replica 0) +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseCluster +metadata: + name: my-clickhouse +spec: + shards: 1 + replicas: 1 + replicaIDOffset: 0 + clusterDomain: k8s-cluster.dc1 + keeperClusterRef: + name: my-keeper + externalSecret: + name: my-clickhouse-shared-secret + externalReplicas: + - shard: 0 + replica: 10 + host: my-clickhouse-clickhouse-internal-0-10.default.svc.k8s-cluster.dc2 + port: 9001 +``` + +```yaml +# Cluster DC2 (shard 0, local replica 10) +apiVersion: clickhouse.com/v1alpha1 +kind: ClickHouseCluster +metadata: + name: my-clickhouse +spec: + shards: 1 + replicas: 1 + replicaIDOffset: 10 + clusterDomain: k8s-cluster.dc2 + keeperClusterRef: + name: my-keeper + externalSecret: + name: my-clickhouse-shared-secret + externalReplicas: + - shard: 0 + replica: 0 + host: my-clickhouse-clickhouse-internal-0-0.default.svc.k8s-cluster.dc1 + port: 9001 +``` + + +`replicaIDOffset` (on both CRDs) and `shardIDOffset` (on `ClickHouseCluster`) are immutable after +cluster creation. If `networkPolicy.policy` is `Enabled`, add user-defined `NetworkPolicy` rules +allowing cross-cluster traffic on Keeper Raft (`9234`), Keeper client (`2181`/`2281`), and ClickHouse +interserver (`9009`) and management (`9001`) ports. + + ## Periodic resync {#periodic-resync} Besides reacting to Kubernetes events, the operator re-reconciles every cluster on a fixed interval. This keeps status conditions fresh for state that no watch can observe — ClickHouse replica health, Keeper quorum — and retries remediation such as stuck-pod cleanup. diff --git a/docs/reference/api-reference.mdx b/docs/reference/api-reference.mdx index 6a77691ca..1db3970ce 100644 --- a/docs/reference/api-reference.mdx +++ b/docs/reference/api-reference.mdx @@ -76,6 +76,9 @@ ClickHouseClusterSpec defines the desired state of ClickHouseCluster. |-------|------|-------------|----------|---------| | `replicas` | integer | Number of replicas in the single shard. | false | 3 | | `shards` | integer | Number of shards in the cluster. | false | 1 | +| `shardIDOffset` | integer | ShardIDOffset is the starting shard index for locally managed shards.
Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters.
Defaults to 0. Cannot be changed after cluster creation. | false | | +| `replicaIDOffset` | integer | ReplicaIDOffset is the starting replica index within each shard for locally managed replicas.
Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards
(for example 0, 10, 20 to leave room for independent scaling in each cluster).
Defaults to 0. Cannot be changed after cluster creation. | false | | +| `externalReplicas` | [ExternalClickHouseReplica](#externalclickhousereplica) array | ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in remote_servers and preserves their Keeper metadata during cleanup
without creating Kubernetes workloads for them. | false | | | `keeperClusterRef` | [KeeperClusterReference](#keeperclusterreference) | Reference to the KeeperCluster that is used for ClickHouse coordination.
When namespace is omitted, the ClickHouseCluster namespace is used.
Mutually exclusive with `externalKeeper`, exactly one of them must be set. | false | | | `externalKeeper` | [ExternalKeeperSpec](#externalkeeperspec) | Keeper ensemble that is not managed by this operator, used for ClickHouse coordination.
The operator does not own the lifecycle of these servers and only points ClickHouse at them.
Mutually exclusive with `keeperClusterRef`, exactly one of them must be set. | false | | | `podTemplate` | [PodTemplateSpec](#podtemplatespec) | Parameters passed to the ClickHouse pod spec. | false | | @@ -237,6 +240,21 @@ Encryption cannot be disabled once enabled. Appears in: - [ClickHouseSettings](#clickhousesettings) +## ExternalClickHouseReplica {#externalclickhousereplica} + +ExternalClickHouseReplica addresses a single ClickHouse replica managed outside this Kubernetes cluster. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `shard` | integer | Shard is the shard index this external replica belongs to. | true | | +| `replica` | integer | Replica is the replica index within the shard.
Must not collide with any locally managed replica in the same shard. | true | | +| `host` | string | Host is the DNS name or IP address of the external ClickHouse replica reachable from this cluster.
IPv6 addresses must be enclosed in square brackets. | true | | +| `port` | integer | Port is the native TCP port used for remote_servers communication.
Defaults to 9001 (the operator internal management TCP port). | false | 9001 | +| `tls` | [ExternalReplicaTLSPolicy](#externalreplicatlspolicy) | TLS controls whether remote_servers connects to this external replica over TLS.
Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. | false | Disabled | + +Appears in: +- [ClickHouseClusterSpec](#clickhouseclusterspec) + ## ExternalKeeperNode {#externalkeepernode} ExternalKeeperNode addresses a single server of an external Keeper ensemble. @@ -249,6 +267,20 @@ ExternalKeeperNode addresses a single server of an external Keeper ensemble. Appears in: - [ExternalKeeperSpec](#externalkeeperspec) +## ExternalKeeperPeer {#externalkeeperpeer} + +ExternalKeeperPeer addresses a single Raft peer of a Keeper ensemble managed outside this Kubernetes cluster. + +| Field | Type | Description | Required | Default | +|-------|------|-------------|----------|---------| +| `id` | integer | ID is the unique Raft server ID of the external peer.
Must not collide with any locally managed replica ID or another external peer ID. | true | | +| `host` | string | Host is the DNS name or IP address of the external peer reachable from this cluster.
IPv6 addresses must be enclosed in square brackets. | true | | +| `port` | integer | Port is the Raft inter-server communication port of the external peer.
Defaults to 9234. | false | 9234 | +| `clientPort` | integer | ClientPort is the Keeper client port of the external peer, used when a ClickHouseCluster
references this KeeperCluster via keeperClusterRef.
When omitted, defaults to 2181 (or 2281 when TLS is enabled on this KeeperCluster). | false | | + +Appears in: +- [KeeperClusterSpec](#keeperclusterspec) + ## ExternalKeeperSpec {#externalkeeperspec} ExternalKeeperSpec describes a Keeper ensemble managed outside of this operator. @@ -273,6 +305,18 @@ ExternalKeeperTLSPolicy controls how ClickHouse connects to an external Keeper e Appears in: - [ExternalKeeperSpec](#externalkeeperspec) +## ExternalReplicaTLSPolicy {#externalreplicatlspolicy} + +ExternalReplicaTLSPolicy controls how remote_servers connects to an external ClickHouse replica. + +| Field | Description | +|-------|-------------| +| `Enabled` | ExternalReplicaTLSEnabled makes remote_servers connect to the external replica over TLS.
| +| `Disabled` | ExternalReplicaTLSDisabled is the default policy: connections are made in plain text.
| + +Appears in: +- [ExternalClickHouseReplica](#externalclickhousereplica) + ## ExternalSecret {#externalsecret} ExternalSecret is a reference to a Secret in the same namespace. @@ -361,7 +405,9 @@ KeeperClusterSpec defines the desired state of KeeperCluster. | Field | Type | Description | Required | Default | |-------|------|-------------|----------|---------| -| `replicas` | integer | Number of replicas in the cluster | false | 3 | +| `replicas` | integer | Number of locally managed replicas in the cluster.
Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set,
as long as replicas + len(externalPeers) <= 15. | false | 3 | +| `replicaIDOffset` | integer | ReplicaIDOffset is the starting Raft server ID for locally managed replicas.
Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble
(for example 0, 10, 20 to leave room for independent scaling in each cluster).
Defaults to 0. Cannot be changed after cluster creation. | false | | +| `externalPeers` | [ExternalKeeperPeer](#externalkeeperpeer) array | ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in raft_configuration without creating Kubernetes workloads for them. | false | | | `podTemplate` | [PodTemplateSpec](#podtemplatespec) | Parameters passed to the Keeper pod spec. | false | | | `containerTemplate` | [ContainerTemplateSpec](#containertemplatespec) | Parameters passed to the Keeper container spec. | false | | | `dataVolumeClaimSpec` | [PersistentVolumeClaimSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#persistentvolumeclaimspec-v1-core) | Specification of persistent storage for ClickHouse Keeper data. | false | | diff --git a/internal/controller/clickhouse/commands.go b/internal/controller/clickhouse/commands.go index 85fb12fa7..faa34a5d3 100644 --- a/internal/controller/clickhouse/commands.go +++ b/internal/controller/clickhouse/commands.go @@ -2,11 +2,15 @@ package clickhouse import ( "context" + "crypto/tls" "database/sql" "errors" "fmt" "maps" + "net" "slices" + "strconv" + "strings" "github.com/ClickHouse/clickhouse-go/v2" "github.com/google/uuid" @@ -23,6 +27,18 @@ WHERE engine NOT IN ('Atomic', 'Lazy', 'SQLite', 'Ordinary', 'Memory') SETTINGS format_display_secrets_in_show_and_select=1` + listClusterDatabasesQuery = `SELECT + name, + any(engine_full) AS engine_full, + any(uuid) AS uuid, + any(engine = 'Replicated')::Bool AS is_replicated +FROM clusterAllReplicas(default, system.databases) +WHERE + engine NOT IN ('Atomic', 'Lazy', 'SQLite', 'Ordinary', 'Memory') +GROUP BY name +SETTINGS + format_display_secrets_in_show_and_select=1, + skip_unavailable_shards=1` // system.clusters also lists static clusters from remote_servers and Replicated databases with // names the operator did not choose; their shard and replica names are empty or non-numeric. // toInt32OrNull keeps the cast from throwing on those rows, and the NULL filter drops them, so @@ -39,7 +55,7 @@ FROM ( toInt32OrNull(database_replica_name) AS replica_id, is_active FROM clusterAllReplicas(default, system.clusters) - WHERE shard_id IS NOT NULL AND replica_id IS NOT NULL AND (shard_id >= ? OR replica_id >= ?) + WHERE shard_id IS NOT NULL AND replica_id IS NOT NULL ) GROUP BY database, shard_id, replica_id SETTINGS skip_unavailable_shards=1` @@ -228,6 +244,19 @@ func (cmd *commander) SyncDatabases( maps.Copy(databases, replicaDatabases[id].Result) } + if len(cmd.cluster.Spec.ExternalReplicas) > 0 { + clusterDBs, err := cmd.ClusterDatabases(ctx) + if err != nil { + log.Warn("failed to discover databases from remote cluster replicas", "error", err) + } else { + for name, desc := range clusterDBs { + if _, exists := databases[name]; !exists { + databases[name] = desc + } + } + } + } + results := controllerutil.ExecuteParallel(ctx, targets, func(ctx context.Context, id v1.ClickHouseReplicaID) (struct{}, error) { if err := replicaDatabases[id].Err; err != nil { return struct{}{}, err @@ -290,6 +319,39 @@ func (cmd *commander) Databases(ctx context.Context, id v1.ClickHouseReplicaID) return databases, nil } +// ClusterDatabases discovers Replicated and integration databases across all reachable replicas in remote_servers.default. +func (cmd *commander) ClusterDatabases(ctx context.Context) (map[string]databaseDescriptor, error) { + id, conn, err := cmd.getAnyConn(ctx) + if err != nil { + return nil, fmt.Errorf("failed to get connection for cluster databases query: %w", err) + } + + rows, err := conn.Query(ctx, listClusterDatabasesQuery) + if err != nil { + return nil, fmt.Errorf("failed to query cluster databases via replica %s: %w", id, err) + } + + defer func() { + _ = rows.Close() + }() + + databases := map[string]databaseDescriptor{} + for rows.Next() { + var db databaseDescriptor + if err := rows.ScanStruct(&db); err != nil { + return nil, fmt.Errorf("failed to scan cluster database row via replica %s: %w", id, err) + } + + databases[db.Name] = db + } + + if err = rows.Err(); err != nil { + return nil, fmt.Errorf("failed to fetch all cluster database rows via replica %s: %w", id, err) + } + + return databases, nil +} + func (cmd *commander) CreateDatabases(ctx context.Context, log controllerutil.Logger, id v1.ClickHouseReplicaID, databases map[string]databaseDescriptor) error { conn, err := cmd.getConn(id) if err != nil { @@ -372,10 +434,10 @@ func (cmd *commander) EnsureReplicaDefaultDatabaseEngine(ctx context.Context, lo func (cmd *commander) SyncShard(ctx context.Context, log controllerutil.Logger, shardID int32, opts ...controllerutil.ParallelOption) error { replicasToSync := make([]v1.ClickHouseReplicaID, 0, cmd.cluster.Replicas()) - for id := range cmd.cluster.Replicas() { + for index := range cmd.cluster.ReplicaIndexes() { replicasToSync = append(replicasToSync, v1.ClickHouseReplicaID{ ShardID: shardID, - Index: id, + Index: index, }) } @@ -480,7 +542,7 @@ func (cmd *commander) CleanupDatabaseReplicas( log = log.With("replica_id", id) - rows, err := conn.Query(ctx, listStaleDatabaseReplicasQuery, cmd.cluster.Shards(), cmd.cluster.Replicas()) + rows, err := conn.Query(ctx, listStaleDatabaseReplicasQuery) if err != nil { return fmt.Errorf("query stale database replicas %v: %w", id, err) } @@ -499,13 +561,22 @@ func (cmd *commander) CleanupDatabaseReplicas( isActive bool ) - total++ - if err = rows.Scan(&database, &toDrop.ShardID, &toDrop.Index, &isActive); err != nil { + total++ + log.Warn("failed to scan stale database replica", "error", err) continue } + if !cmd.cluster.ReplicaObsolete(toDrop) || + cmd.cluster.IsExternalReplica(toDrop) || + toDrop.ShardID < cmd.cluster.Spec.ShardIDOffset || + toDrop.Index < cmd.cluster.Spec.ReplicaIDOffset { + continue + } + + total++ + if _, ok := running[toDrop]; ok { log.Debug("skipping stale database replica cleanup that is still running", "database", database, "replica_id", toDrop) continue @@ -581,30 +652,37 @@ func (cmd *commander) createDatabase( return nil } +type peerConn struct { + id v1.ClickHouseReplicaID + conn clickhouse.Conn + cleanup func() +} + // dropStaleReplicaMetadata removes the replica's metadata for the database from Keeper: the database // replica entry and the per-table replica entries. It runs on a peer of the same shard because // SYSTEM DROP REPLICA resolves table paths from the tables local to the executing host; both // statements refuse to drop an active replica. func (cmd *commander) dropStaleReplicaMetadata(ctx context.Context, id v1.ClickHouseReplicaID, database string) error { - peer, conn, err := cmd.shardPeerConn(ctx, id) + peer, err := cmd.shardPeerConn(ctx, id) if err != nil { return err } + defer peer.cleanup() // Neither statement accepts query parameters for these positions. for _, query := range []string{ fmt.Sprintf("SYSTEM DROP DATABASE REPLICA '%d|%d' FROM DATABASE `%s`", id.ShardID, id.Index, database), fmt.Sprintf("SYSTEM DROP REPLICA '%d' FROM DATABASE `%s`", id.Index, database), } { - if err := conn.Exec(ctx, query); err != nil { - return fmt.Errorf("on peer %s: %w", peer, err) + if err := peer.conn.Exec(ctx, query); err != nil { + return fmt.Errorf("on peer %s: %w", peer.id, err) } } return nil } -func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseReplicaID) (v1.ClickHouseReplicaID, clickhouse.Conn, error) { +func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseReplicaID) (peerConn, error) { for id := range cmd.cluster.ReplicaIDs() { if id.ShardID != exclude.ShardID || id.Index == exclude.Index { continue @@ -615,10 +693,50 @@ func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseRe continue } - return id, conn, nil + return peerConn{id: id, conn: conn, cleanup: func() {}}, nil + } + + for _, ext := range cmd.cluster.Spec.ExternalReplicas { + if ext.Shard != exclude.ShardID { + continue + } + + port := ext.Port + if port == 0 { + port = PortManagement + } + + opts := &clickhouse.Options{ + Addr: []string{net.JoinHostPort(strings.Trim(ext.Host, "[]"), strconv.Itoa(int(port)))}, + Auth: cmd.auth, + DialContext: cmd.dialer, + DialTimeout: dialTimeout, + } + if ext.TLS == v1.ExternalReplicaTLSEnabled { + opts.TLS = &tls.Config{ + //nolint:gosec // User managed certificate may be issued for external or custom hostnames. + InsecureSkipVerify: true, + } + } + + conn, err := clickhouse.Open(opts) + if err != nil { + continue + } + + if conn.Ping(ctx) != nil { + _ = conn.Close() + continue + } + + return peerConn{ + id: v1.ClickHouseReplicaID{ShardID: ext.Shard, Index: ext.Replica}, + conn: conn, + cleanup: func() { _ = conn.Close() }, + }, nil } - return v1.ClickHouseReplicaID{}, nil, fmt.Errorf("no reachable peer in shard %d for replica %s", exclude.ShardID, exclude) + return peerConn{}, fmt.Errorf("no reachable peer in shard %d for replica %s", exclude.ShardID, exclude) } func (cmd *commander) getConn(id v1.ClickHouseReplicaID) (clickhouse.Conn, error) { diff --git a/internal/controller/clickhouse/commands_test.go b/internal/controller/clickhouse/commands_test.go index 44da79f1c..b734c4390 100644 --- a/internal/controller/clickhouse/commands_test.go +++ b/internal/controller/clickhouse/commands_test.go @@ -502,13 +502,21 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { Expect(cmd.CleanupDatabaseReplicas(ctx, cmd.log, map[v1.ClickHouseReplicaID]struct{}{})).To(Succeed()) }) + It("should discover replicated databases across clusterAllReplicas", func(ctx context.Context) { + dbs, err := cmd.ClusterDatabases(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(dbs).To(HaveKey("default")) + Expect(dbs).To(HaveKey("testdb")) + Expect(dbs["testdb"].IsReplicated).To(BeTrue()) + }) + It("should do nothing if still active", func(ctx context.Context) { *cmd.cluster.Spec.Replicas = testReplicas - 1 err := cmd.CleanupDatabaseReplicas(ctx, cmd.log, map[v1.ClickHouseReplicaID]struct{}{}) Expect(err.Error()).To(ContainSubstring("not cleaned up")) }) - It("should do nothing if not in sync", func(ctx context.Context) { + It("should preserve inactive replicas declared in externalReplicas", func(ctx context.Context) { Expect(chContainers[len(chContainers)-1].Stop(ctx, new(time.Nanosecond))).To(Succeed()) Eventually(func() uint64 { _, conn, err := cmd.getAnyConn(ctx) @@ -523,6 +531,27 @@ var _ = Describe("commander", Ordered, Label("integration"), func() { return activeCount }, "1m", "1s").To(Equal(uint64(testReplicas - 1))) + cmd.cluster.Spec.ExternalReplicas = []v1.ExternalClickHouseReplica{{ + Shard: 0, + Replica: testReplicas - 1, + Host: fmt.Sprintf(clickhouseHostnameFormat, testReplicas-1), + }} + DeferCleanup(func() { + cmd.cluster.Spec.ExternalReplicas = nil + }) + + Expect(cmd.CleanupDatabaseReplicas(ctx, cmd.log, map[v1.ClickHouseReplicaID]struct{}{})).To(Succeed()) + + _, conn, err := cmd.getAnyConn(ctx) + Expect(err).ToNot(HaveOccurred()) + + var count uint32 + Expect(conn.QueryRow(ctx, `SELECT MAX(total_replicas) FROM system.database_replicas`).Scan(&count)).To(Succeed()) + Expect(count).To(Equal(uint32(testReplicas))) + }) + + It("should do nothing if not in sync", func(ctx context.Context) { + cmd.cluster.Spec.ExternalReplicas = nil err := cmd.CleanupDatabaseReplicas(ctx, cmd.log, map[v1.ClickHouseReplicaID]struct{}{ {Index: testReplicas - 1}: {}, }) diff --git a/internal/controller/clickhouse/config.go b/internal/controller/clickhouse/config.go index 134ffabdd..b50695830 100644 --- a/internal/controller/clickhouse/config.go +++ b/internal/controller/clickhouse/config.go @@ -1,10 +1,12 @@ package clickhouse import ( + "cmp" _ "embed" "errors" "fmt" "path" + "slices" "strings" "text/template" @@ -267,12 +269,21 @@ type clusterConfigParams struct { KeeperIdentityEnv string ClusterSecretEnv string - ManagementPort uint16 - ClusterHosts [][]string + ClusterShards []clusterShard NamedCollections []namedCollection } +type clusterShard struct { + Replicas []clusterReplica +} + +type clusterReplica struct { + Host string + Port int32 + Secure bool +} + type macro struct { Name string Value any @@ -310,38 +321,105 @@ func (r *clickhouseReconciler) keeperNodes() []keeperNode { return nodes } - nodes := make([]keeperNode, 0, r.keeper.Replicas()) + nodes := make([]keeperNode, 0, int(r.keeper.Replicas())+len(r.keeper.Spec.ExternalPeers)) + secure := r.keeper.Spec.Settings.TLS.Enabled + + defaultPort := int32(keeper.PortNative) + if secure { + defaultPort = keeper.PortNativeSecure + } + for _, host := range r.keeper.Hostnames() { - if r.keeper.Spec.Settings.TLS.Enabled { - nodes = append(nodes, keeperNode{ - Host: host, - Port: keeper.PortNativeSecure, - Secure: true, - }) - } else { - nodes = append(nodes, keeperNode{ - Host: host, - Port: keeper.PortNative, - }) + nodes = append(nodes, keeperNode{ + Host: host, + Port: defaultPort, + Secure: secure, + }) + } + + externalPeers := slices.Clone(r.keeper.Spec.ExternalPeers) + slices.SortFunc(externalPeers, func(a, b v1.ExternalKeeperPeer) int { + return cmp.Compare(a.ID, b.ID) + }) + + for _, peer := range externalPeers { + port := defaultPort + if peer.ClientPort > 0 { + port = peer.ClientPort } + + nodes = append(nodes, keeperNode{ + Host: peer.Host, + Port: port, + Secure: secure, + }) } return nodes } -func clusterConfigGenerator(tmpl *template.Template, r *clickhouseReconciler, id v1.ClickHouseReplicaID) (string, error) { - keeperNodes := r.keeperNodes() +func (r *clickhouseReconciler) clusterShards() []clusterShard { + type indexedReplica struct { + index int32 + replica clusterReplica + } + + byShard := map[int32][]indexedReplica{} + + for id := range r.Cluster.ReplicaIDs() { + byShard[id.ShardID] = append(byShard[id.ShardID], indexedReplica{ + index: id.Index, + replica: clusterReplica{ + Host: r.Cluster.InternalHostnameByID(id), + Port: PortManagement, + }, + }) + } + + for _, ext := range r.Cluster.Spec.ExternalReplicas { + port := ext.Port + if port == 0 { + port = PortManagement + } + + byShard[ext.Shard] = append(byShard[ext.Shard], indexedReplica{ + index: ext.Replica, + replica: clusterReplica{ + Host: ext.Host, + Port: port, + Secure: ext.TLS == v1.ExternalReplicaTLSEnabled, + }, + }) + } + + shardIDs := make([]int32, 0, len(byShard)) + for shardID := range byShard { + shardIDs = append(shardIDs, shardID) + } + + slices.Sort(shardIDs) + + shards := make([]clusterShard, 0, len(shardIDs)) + for _, shardID := range shardIDs { + entries := byShard[shardID] + slices.SortFunc(entries, func(a, b indexedReplica) int { + return cmp.Compare(a.index, b.index) + }) - clusterHosts := make([][]string, r.Cluster.Shards()) - for shard := range r.Cluster.Shards() { - hosts := make([]string, r.Cluster.Replicas()) - for replica := range r.Cluster.Replicas() { - hosts[replica] = r.Cluster.InternalHostnameByID(v1.ClickHouseReplicaID{ShardID: shard, Index: replica}) + replicas := make([]clusterReplica, 0, len(entries)) + for _, entry := range entries { + replicas = append(replicas, entry.replica) } - clusterHosts[shard] = hosts + shards = append(shards, clusterShard{Replicas: replicas}) } + return shards +} + +func clusterConfigGenerator(tmpl *template.Template, r *clickhouseReconciler, id v1.ClickHouseReplicaID) (string, error) { + keeperNodes := r.keeperNodes() + params := clusterConfigParams{ Macros: []macro{ {Name: "cluster", Value: DefaultClusterName}, @@ -353,8 +431,7 @@ func clusterConfigGenerator(tmpl *template.Template, r *clickhouseReconciler, id KeeperIdentityEnv: EnvKeeperIdentity, ClusterSecretEnv: EnvClusterSecret, - ManagementPort: PortManagement, - ClusterHosts: clusterHosts, + ClusterShards: r.clusterShards(), NamedCollections: []namedCollection{{ Name: OperatorNamedCollectionName, diff --git a/internal/controller/clickhouse/config_test.go b/internal/controller/clickhouse/config_test.go index 4ac857111..dafc8418a 100644 --- a/internal/controller/clickhouse/config_test.go +++ b/internal/controller/clickhouse/config_test.go @@ -189,6 +189,123 @@ var _ = Describe("ConfigGenerator", func() { Expect(err).ToNot(HaveOccurred()) Expect(data).To(ContainSubstring("interserver_http_host: " + ctx.Cluster.InternalHostnameByID(id))) }) + + It("should render multi-cluster Keeper peers when using keeperClusterRef", func() { + r := clickhouseReconciler{ + Cluster: ctx.Cluster.DeepCopy(), + keeper: v1.KeeperCluster{ + Name: "keeper", + Namespace: "test-namespace", + Spec: v1.KeeperClusterSpec{ + Replicas: new(int32(2)), + ReplicaIDOffset: 3, + ClusterDomain: "k8s.dc2", + ExternalPeers: []v1.ExternalKeeperPeer{ + {ID: 6, Host: "keeper-6.dc3", ClientPort: 9181}, + {ID: 0, Host: "keeper-0.dc1"}, + }, + }, + }, + } + + data, err := clusterConfigGenerator(template.Must(template.New("").Parse(clusterConfigTemplateStr)), &r, v1.ClickHouseReplicaID{}) + Expect(err).ToNot(HaveOccurred()) + + cfg := struct { + Zookeeper struct { + Nodes []struct { + Host string + Port int32 + Secure int + } + } + }{} + Expect(yaml.Unmarshal([]byte(data), &cfg)).To(Succeed()) + + Expect(cfg.Zookeeper.Nodes).To(Equal([]struct { + Host string + Port int32 + Secure int + }{ + {Host: "keeper-keeper-3-0.keeper-keeper-headless.test-namespace.svc.k8s.dc2", Port: keeper.PortNative, Secure: 0}, + {Host: "keeper-keeper-4-0.keeper-keeper-headless.test-namespace.svc.k8s.dc2", Port: keeper.PortNative, Secure: 0}, + {Host: "keeper-0.dc1", Port: keeper.PortNative, Secure: 0}, + {Host: "keeper-6.dc3", Port: 9181, Secure: 0}, + })) + }) + + It("should merge local offsets and externalReplicas in remote_servers and macros", func() { + r := clickhouseReconciler{ + Cluster: &v1.ClickHouseCluster{ + Name: "langfuse", + Namespace: "prod", + Spec: v1.ClickHouseClusterSpec{ + Shards: new(int32(1)), + Replicas: new(int32(1)), + ShardIDOffset: 0, + ReplicaIDOffset: 1, + ClusterDomain: "k8s.dc2", + ExternalReplicas: []v1.ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "langfuse-clickhouse-internal-0-0.prod.svc.k8s.dc1"}, + {Shard: 0, Replica: 2, Host: "langfuse-clickhouse-internal-0-2.prod.svc.k8s.dc3", Port: 9440, TLS: v1.ExternalReplicaTLSEnabled}, + {Shard: 1, Replica: 0, Host: "langfuse-clickhouse-internal-1-0.prod.svc.k8s.dc1", Port: 9001}, + }, + }, + }, + keeper: v1.KeeperCluster{ + Name: "keeper", + Namespace: "prod", + Spec: v1.KeeperClusterSpec{Replicas: new(int32(1))}, + }, + } + + localID := v1.ClickHouseReplicaID{ShardID: 0, Index: 1} + data, err := clusterConfigGenerator(template.Must(template.New("").Parse(clusterConfigTemplateStr)), &r, localID) + Expect(err).ToNot(HaveOccurred()) + + cfg := struct { + Macros struct { + Cluster string + Shard int32 + Replica int32 + } + RemoteServers struct { + Default struct { + Shard []struct { + InternalReplication bool `yaml:"internal_replication"` + Replica []struct { + Host string + Port int32 + Secure int + } + } + } + } `yaml:"remote_servers"` + }{} + Expect(yaml.Unmarshal([]byte(data), &cfg)).To(Succeed()) + + Expect(cfg.Macros.Cluster).To(Equal(DefaultClusterName)) + Expect(cfg.Macros.Shard).To(BeEquivalentTo(0)) + Expect(cfg.Macros.Replica).To(BeEquivalentTo(1)) + + Expect(cfg.RemoteServers.Default.Shard).To(HaveLen(2)) + Expect(cfg.RemoteServers.Default.Shard[0].Replica).To(Equal([]struct { + Host string + Port int32 + Secure int + }{ + {Host: "langfuse-clickhouse-internal-0-0.prod.svc.k8s.dc1", Port: PortManagement, Secure: 0}, + {Host: "langfuse-clickhouse-internal-0-1.prod.svc.k8s.dc2", Port: PortManagement, Secure: 0}, + {Host: "langfuse-clickhouse-internal-0-2.prod.svc.k8s.dc3", Port: 9440, Secure: 1}, + })) + Expect(cfg.RemoteServers.Default.Shard[1].Replica).To(Equal([]struct { + Host string + Port int32 + Secure int + }{ + {Host: "langfuse-clickhouse-internal-1-0.prod.svc.k8s.dc1", Port: PortManagement, Secure: 0}, + })) + }) }) func findExposedEnvVars(value any) []string { diff --git a/internal/controller/clickhouse/schemasync.go b/internal/controller/clickhouse/schemasync.go index 587c30ef9..2b7c23403 100644 --- a/internal/controller/clickhouse/schemasync.go +++ b/internal/controller/clickhouse/schemasync.go @@ -180,7 +180,7 @@ func (r *clickhouseReconciler) reconcilePreScaleDownSync(ctx context.Context, lo } switch { - case id.ShardID >= r.Cluster.Shards(): + case r.Cluster.ShardObsolete(id.ShardID): // Whole shard removal drops the shard data by design, no surviving replicas to sync. case shardHasReachableReplica[id.ShardID]: shardsToSyncSet[id.ShardID] = struct{}{} diff --git a/internal/controller/clickhouse/sync.go b/internal/controller/clickhouse/sync.go index 4ac180818..626599d94 100644 --- a/internal/controller/clickhouse/sync.go +++ b/internal/controller/clickhouse/sync.go @@ -252,7 +252,7 @@ func (r *clickhouseReconciler) reconcilePodDisruptionBudget(ctx context.Context, pdbEnabled := r.Cluster.Spec.PodDisruptionBudget.Enabled() if pdbEnabled { - for shard := range r.Cluster.Shards() { + for shard := range r.Cluster.ShardIDs() { pdb := templatePodDisruptionBudget(r.Cluster, shard) if _, err := r.ReconcilePodDisruptionBudget(ctx, log, pdb, v1.EventActionReconciling); err != nil { return chctrl.StepResult{}, fmt.Errorf("reconcile PodDisruptionBudget resource for shard %d: %w", shard, err) @@ -274,7 +274,7 @@ func (r *clickhouseReconciler) reconcilePodDisruptionBudget(ctx context.Context, continue } - if !pdbEnabled || shardID >= int(r.Cluster.Shards()) { + if !pdbEnabled || r.Cluster.ShardObsolete(int32(shardID)) { //nolint:gosec // Shard IDs are bounded by CRD validation. log.Info("removing PodDisruptionBudget", "poddisruptionbudget", pdb.Name) if err := r.Delete(ctx, &pdb, v1.EventActionReconciling); err != nil { @@ -688,22 +688,19 @@ func (r *clickhouseReconciler) reconcileClusterRevisions(ctx context.Context, lo } var notUpdated, reloadErr, notReloaded []string - for shard := range r.Cluster.Shards() { - for index := range r.Cluster.Replicas() { - id := v1.ClickHouseReplicaID{ShardID: shard, Index: index} - replica := r.ReplicaState[id] + for id := range r.Cluster.ReplicaIDs() { + replica := r.ReplicaState[id] - if replica.HasDiff(r.revs) || !replica.StatefulSetUpdated() { - notUpdated = append(notUpdated, id.String()) - } + if replica.HasDiff(r.revs) || !replica.StatefulSetUpdated() { + notUpdated = append(notUpdated, id.String()) + } - if replica.ReloadError != nil { - reloadErr = append(reloadErr, id.String()) - } + if replica.ReloadError != nil { + reloadErr = append(reloadErr, id.String()) + } - if !replica.Reloaded(r.revs.ReloadConfigRevision) { - notReloaded = append(notReloaded, id.String()) - } + if !replica.Reloaded(r.revs.ReloadConfigRevision) { + notReloaded = append(notReloaded, id.String()) } } @@ -947,9 +944,9 @@ func (r *clickhouseReconciler) evaluateReplicaConditions() { notReadyShards []int32 ) - for shard := range r.Cluster.Shards() { + for shard := range r.Cluster.ShardIDs() { hasReady := false - for index := range r.Cluster.Replicas() { + for index := range r.Cluster.ReplicaIndexes() { id := v1.ClickHouseReplicaID{ShardID: shard, Index: index} replica := r.ReplicaState[id] diff --git a/internal/controller/clickhouse/templates.go b/internal/controller/clickhouse/templates.go index fddec93d3..8988981a5 100644 --- a/internal/controller/clickhouse/templates.go +++ b/internal/controller/clickhouse/templates.go @@ -176,13 +176,14 @@ type configRevisions struct { func getConfigurationRevisions(r *clickhouseReconciler) (configRevisions, error) { reloadable := map[string]string{} restartable := map[string]string{} + templateID := v1.ClickHouseReplicaID{ShardID: r.Cluster.Spec.ShardIDOffset, Index: r.Cluster.Spec.ReplicaIDOffset} for _, generator := range generators { if !generator.Enabled(r) { continue } - data, err := generator.Generate(r, v1.ClickHouseReplicaID{}) + data, err := generator.Generate(r, templateID) if err != nil { return configRevisions{}, fmt.Errorf("generate config file %s: %w", generator.Path(), err) } @@ -212,7 +213,9 @@ func getConfigurationRevisions(r *clickhouseReconciler) (configRevisions, error) } func getStatefulSetRevision(r *clickhouseReconciler, cfgRestartRevision string) (string, error) { - sts, err := templateStatefulSet(r, v1.ClickHouseReplicaID{}, cfgRestartRevision) + templateID := v1.ClickHouseReplicaID{ShardID: r.Cluster.Spec.ShardIDOffset, Index: r.Cluster.Spec.ReplicaIDOffset} + + sts, err := templateStatefulSet(r, templateID, cfgRestartRevision) if err != nil { return "", fmt.Errorf("generate template StatefulSet: %w", err) } diff --git a/internal/controller/clickhouse/templates/cluster.yaml.tmpl b/internal/controller/clickhouse/templates/cluster.yaml.tmpl index fb2bcf064..500a4ac0b 100644 --- a/internal/controller/clickhouse/templates/cluster.yaml.tmpl +++ b/internal/controller/clickhouse/templates/cluster.yaml.tmpl @@ -23,13 +23,15 @@ remote_servers: "@from_env": {{ .ClusterSecretEnv }} "@hide_in_preprocessed": true shard: - {{- $ctx := .}} - {{- range $shard, $replicas := .ClusterHosts }} + {{- range $shard := .ClusterShards }} - internal_replication: true replica: - {{- range $i, $replica := $replicas }} - - host: {{ $replica }} - port: {{ $ctx.ManagementPort }} + {{- range $replica := $shard.Replicas }} + - host: {{ $replica.Host }} + port: {{ $replica.Port }} + {{- if $replica.Secure }} + secure: 1 + {{- end }} {{- end }} {{- end }} diff --git a/internal/controller/keeper/constants.go b/internal/controller/keeper/constants.go index 1182e2408..d39b497fc 100644 --- a/internal/controller/keeper/constants.go +++ b/internal/controller/keeper/constants.go @@ -7,10 +7,10 @@ import ( ) const ( - PortNative = 2181 - PortNativeSecure = 2281 + PortNative = internal.KeeperPortNative + PortNativeSecure = internal.KeeperPortNativeSecure PortPrometheusScrape = 9090 - PortInterserver = 9234 + PortInterserver = internal.KeeperPortInterserver PortHTTPControl = 9123 PortNameNative = "keeper" diff --git a/internal/controller/keeper/controller.go b/internal/controller/keeper/controller.go index 47d89ad4c..fe4ab49f7 100644 --- a/internal/controller/keeper/controller.go +++ b/internal/controller/keeper/controller.go @@ -4,6 +4,7 @@ import ( "cmp" "context" "fmt" + "slices" "strings" appsv1 "k8s.io/api/apps/v1" @@ -252,10 +253,7 @@ func (cc *ClusterController) observeDigest(ctx context.Context, cluster *v1.Keep } } - ids := make([]v1.KeeperReplicaID, 0, cluster.Replicas()) - for i := range cluster.Replicas() { - ids = append(ids, v1.KeeperReplicaID(i)) - } + ids := slices.Collect(cluster.ReplicaIDs()) states := controllerutil.ExecuteParallel(ctx, ids, func(ctx context.Context, id v1.KeeperReplicaID) (string, error) { if podIPs[id] == "" { diff --git a/internal/controller/keeper/sync.go b/internal/controller/keeper/sync.go index 4666dfd3c..07b17a18e 100644 --- a/internal/controller/keeper/sync.go +++ b/internal/controller/keeper/sync.go @@ -92,6 +92,10 @@ type keeperReconciler struct { HorizontalScaleAllowed bool } +func (r *keeperReconciler) totalEnsembleSize() int { + return len(r.ReplicaState) + len(r.Cluster.Spec.ExternalPeers) +} + var keeperConditionTypes = []v1.ConditionType{ v1.ConditionTypeReplicaStartupSucceeded, v1.ConditionTypeHealthy, @@ -328,7 +332,7 @@ func (r *keeperReconciler) reconcileQuorumMembership(_ context.Context, log ctrl "Initial cluster creation, creating %d replicas", requestedReplicas) r.SetCondition(metav1.Condition{Type: v1.ConditionTypeClusterSizeAligned, Status: metav1.ConditionTrue, Reason: v1.ConditionReasonUpToDate, Message: ""}) - for id := range v1.KeeperReplicaID(requestedReplicas) { //nolint:gosec + for id := range r.Cluster.ReplicaIDs() { log.Info("creating new replica", "replica_id", id) r.ReplicaState[id] = replicaState{} } @@ -375,10 +379,21 @@ func (r *keeperReconciler) reconcileQuorumMembership(_ context.Context, log ctrl return chctrl.StepRequeue(chctrl.RequeueProbePoll), nil } - // Add single replica in quorum, allocating the first free id. + // Add single replica in quorum, allocating the first free id in the cluster's local range. if activeReplicas < requestedReplicas { - for id := v1.KeeperReplicaID(1); ; id++ { - if _, ok := r.ReplicaState[id]; !ok { + for id := range r.Cluster.ReplicaIDs() { + if _, ok := r.ReplicaState[id]; !ok && !r.Cluster.IsExternalPeer(id) { + log.Info("creating new replica", "replica_id", id) + r.GetRecorder().Eventf(r.Cluster, nil, corev1.EventTypeNormal, v1.EventReasonReplicaCreated, + v1.EventActionScaling, "Adding new replica %q to the cluster", r.Cluster.HostnameByID(id)) + r.ReplicaState[id] = replicaState{} + + return chctrl.StepContinue(), nil + } + } + + for id := v1.KeeperReplicaID(r.Cluster.Spec.ReplicaIDOffset); ; id++ { + if _, ok := r.ReplicaState[id]; !ok && !r.Cluster.IsExternalPeer(id) { log.Info("creating new replica", "replica_id", id) r.GetRecorder().Eventf(r.Cluster, nil, corev1.EventTypeNormal, v1.EventReasonReplicaCreated, v1.EventActionScaling, "Adding new replica %q to the cluster", r.Cluster.HostnameByID(id)) @@ -492,8 +507,10 @@ func (r *keeperReconciler) reconcileReplicaResources(ctx context.Context, log ct var replicasInStatus []v1.KeeperReplicaID + totalReplicas := r.totalEnsembleSize() + for id, state := range r.ReplicaState { - stage := state.UpdateStage(r.revs, len(r.ReplicaState)) + stage := state.UpdateStage(r.revs, totalReplicas) if stage == highestStage { replicasInStatus = append(replicasInStatus, id) continue @@ -595,6 +612,8 @@ func (r *keeperReconciler) evaluateReplicaConditions() { replicasByMode = map[string][]v1.KeeperReplicaID{} ) + totalReplicas := r.totalEnsembleSize() + r.Cluster.Status.ReadyReplicas = 0 for id, replica := range r.ReplicaState { idStr := fmt.Sprintf("%d", id) @@ -603,7 +622,7 @@ func (r *keeperReconciler) evaluateReplicaConditions() { startupErrors[idStr] = *replica.StartupError } - if !replica.Ready(len(r.ReplicaState)) { + if !replica.Ready(totalReplicas) { notReadyIDs = append(notReadyIDs, idStr) } else { r.Cluster.Status.ReadyReplicas++ @@ -648,12 +667,12 @@ func (r *keeperReconciler) evaluateReplicaConditions() { eventReason := v1.EventReasonClusterNotReady eventAction := v1.EventActionBecameNotReady - switch exists { - case 0: + switch { + case exists == 0: status = metav1.ConditionFalse reason = v1.KeeperConditionReasonNoLeader message = "No replicas" - case 1: + case totalReplicas == 1: if len(replicasByMode[ModeStandalone]) == 1 { status = metav1.ConditionTrue reason = v1.KeeperConditionReasonStandaloneReady @@ -666,6 +685,54 @@ func (r *keeperReconciler) evaluateReplicaConditions() { message = "No replicas in standalone mode" } + case len(r.Cluster.Spec.ExternalPeers) > 0: + requiredFollowersForQuorum := int(math.Ceil(float64(totalReplicas)/2)) - 1 + + switch { + case len(replicasByMode[ModeStandalone]) > 0: + status = metav1.ConditionFalse + reason = v1.KeeperConditionReasonInconsistentState + + slices.Sort(replicasByMode[ModeStandalone]) + message = fmt.Sprintf("Standalone replica in cluster: %v", replicasByMode[ModeStandalone]) + + case len(replicasByMode[ModeLeader]) > 1: + status = metav1.ConditionFalse + reason = v1.KeeperConditionReasonInconsistentState + + slices.Sort(replicasByMode[ModeLeader]) + message = fmt.Sprintf("Multiple leaders in cluster: %v", replicasByMode[ModeLeader]) + + case len(replicasByMode[ModeLeader]) == 1: + leaderFollowers := r.ReplicaState[replicasByMode[ModeLeader][0]].Status.Followers + if leaderFollowers < requiredFollowersForQuorum { + status = metav1.ConditionFalse + reason = v1.KeeperConditionReasonNotEnoughFollowers + message = fmt.Sprintf("Not enough followers in cluster: %d/%d", leaderFollowers, requiredFollowersForQuorum) + } else { + status = metav1.ConditionTrue + reason = v1.KeeperConditionReasonClusterReady + eventType = corev1.EventTypeNormal + eventReason = v1.EventReasonClusterReady + eventAction = v1.EventActionBecameReady + message = "Cluster is ready" + } + + case len(replicasByMode[ModeFollower]) > 0: + // The Raft leader is hosted on an external peer; local followers passing /ready confirm an active leader. + status = metav1.ConditionTrue + reason = v1.KeeperConditionReasonClusterReady + eventType = corev1.EventTypeNormal + eventReason = v1.EventReasonClusterReady + eventAction = v1.EventActionBecameReady + message = "Cluster is ready" + + default: + status = metav1.ConditionFalse + reason = v1.KeeperConditionReasonNoLeader + message = "No ready leader or follower in the cluster" + } + default: requiredFollowersForQuorum := int(math.Ceil(float64(exists)/2)) - 1 @@ -823,7 +890,12 @@ func (r *keeperReconciler) loadQuorumReplicas(ctx context.Context) (map[v1.Keepe return nil, fmt.Errorf("parse replica ID %q: %w", member.ID, err) } - replicas[v1.KeeperReplicaID(id)] = struct{}{} + replicaID := v1.KeeperReplicaID(id) + if r.Cluster.IsExternalPeer(replicaID) || member.Hostname != r.Cluster.HostnameByID(replicaID) { + continue + } + + replicas[replicaID] = struct{}{} } return replicas, nil @@ -833,9 +905,10 @@ func (r *keeperReconciler) checkHorizontalScalingAllowed(_ context.Context, _ ct var leader v1.KeeperReplicaID = -1 activeReplicas := len(r.ReplicaState) + totalReplicas := r.totalEnsembleSize() leaderMode := ModeLeader - if activeReplicas == 1 { + if totalReplicas == 1 { leaderMode = ModeStandalone } @@ -881,7 +954,7 @@ func (r *keeperReconciler) checkHorizontalScalingAllowed(_ context.Context, _ ct updatedReplicas++ } - if replica.Ready(len(r.ReplicaState)) { + if replica.Ready(totalReplicas) { readyReplicas++ } @@ -893,22 +966,22 @@ func (r *keeperReconciler) checkHorizontalScalingAllowed(_ context.Context, _ ct leader = id // Wait for deleted replicas to leave the quorum. - if replica.Status.Followers > activeReplicas-1 { + if replica.Status.Followers > totalReplicas-1 { return scaleBlocked(v1.KeeperConditionReasonWaitingFollowers, "Leader has more followers than expected: %d/%d. "+ - "Obsolete replica has not left the quorum yet", replica.Status.Followers, activeReplicas-1, + "Obsolete replica has not left the quorum yet", replica.Status.Followers, totalReplicas-1, ) - } else if replica.Status.Followers < activeReplicas-1 { + } else if replica.Status.Followers < totalReplicas-1 { return scaleBlocked(v1.KeeperConditionReasonWaitingFollowers, "Leader has less followers than expected: %d/%d. "+ "Some replicas unavailable or not joined the quorum yet", - replica.Status.Followers, activeReplicas-1, + replica.Status.Followers, totalReplicas-1, ) } } } - if leader == -1 { + if leader == -1 && len(r.Cluster.Spec.ExternalPeers) == 0 { return scaleBlocked(v1.KeeperConditionReasonNoQuorum, "No leader in the cluster") } diff --git a/internal/controller/keeper/sync_test.go b/internal/controller/keeper/sync_test.go index ab91e811d..df9c7f4e5 100644 --- a/internal/controller/keeper/sync_test.go +++ b/internal/controller/keeper/sync_test.go @@ -324,6 +324,203 @@ var _ = Describe("Keeper version status", func() { }) }) +var _ = Describe("Multi-cluster Keeper", func() { + readySTS := func(cr *v1.KeeperCluster, id v1.KeeperReplicaID, rev string) *appsv1.StatefulSet { + sts := &appsv1.StatefulSet{ + Namespace: cr.Namespace, + Name: cr.StatefulSetNameByReplicaID(id), + Annotations: map[string]string{ + util.AnnotationSpecHash: rev, + }, + Spec: appsv1.StatefulSetSpec{ + Template: corev1.PodTemplateSpec{ + ObjectMeta: metav1.ObjectMeta{ + Annotations: map[string]string{ + util.AnnotationConfigHash: cr.Status.ConfigurationRevision, + }, + }, + }, + }, + Status: appsv1.StatefulSetStatus{ + ReadyReplicas: 1, + }, + } + + return sts + } + + readyCFG := func(cr *v1.KeeperCluster, id v1.KeeperReplicaID) *corev1.ConfigMap { + cm := &corev1.ConfigMap{ + Namespace: cr.Namespace, + Name: cr.ConfigMapNameByReplicaID(id), + } + util.AddObjectConfigHash(cm, cr.Status.ConfigurationRevision) + + return cm + } + + It("should include externalPeers and offset local replicas in quorum config", func(ctx context.Context) { + log, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.Cluster.Spec.Replicas = new(int32(2)) + rec.Cluster.Spec.ReplicaIDOffset = 3 + rec.Cluster.Spec.ClusterDomain = "k8s.dc2" + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 0, Host: "test-keeper-0-0.test-keeper-headless.default.svc.k8s.dc1"}, + {ID: 1, Host: "test-keeper-1-0.test-keeper-headless.default.svc.k8s.dc1", Port: 9234}, + {ID: 2, Host: "test-keeper-2-0.test-keeper-headless.default.svc.k8s.dc1", Port: 9235}, + } + + _, err := rec.reconcileQuorumMembership(ctx, log) + Expect(err).NotTo(HaveOccurred()) + Expect(rec.ReplicaState).To(HaveKey(v1.KeeperReplicaID(3))) + Expect(rec.ReplicaState).To(HaveKey(v1.KeeperReplicaID(4))) + Expect(rec.ReplicaState).To(HaveLen(2)) + + quorum := generateQuorumConfig(rec) + Expect(quorum).To(Equal(quorumConfig{ + {ID: "0", Hostname: "test-keeper-0-0.test-keeper-headless.default.svc.k8s.dc1", Port: PortInterserver}, + {ID: "1", Hostname: "test-keeper-1-0.test-keeper-headless.default.svc.k8s.dc1", Port: 9234}, + {ID: "2", Hostname: "test-keeper-2-0.test-keeper-headless.default.svc.k8s.dc1", Port: 9235}, + {ID: "3", Hostname: "test-keeper-3-0.test-keeper-headless.default.svc.k8s.dc2", Port: PortInterserver}, + {ID: "4", Hostname: "test-keeper-4-0.test-keeper-headless.default.svc.k8s.dc2", Port: PortInterserver}, + })) + }) + + It("should ignore external peers in loadQuorumReplicas", func(ctx context.Context) { + log, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.Cluster.Spec.Replicas = new(int32(2)) + rec.Cluster.Spec.ReplicaIDOffset = 3 + rec.Cluster.Spec.ClusterDomain = "k8s.dc2" + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 0, Host: "test-keeper-0-0.test-keeper-headless.default.svc.k8s.dc1"}, + {ID: 6, Host: "test-keeper-6-0.test-keeper-headless.default.svc.k8s.dc3"}, + } + rec.ReplicaState = map[v1.KeeperReplicaID]replicaState{ + 3: {}, + 4: {}, + } + + cm, err := templateQuorumConfig(rec) + Expect(err).NotTo(HaveOccurred()) + Expect(rec.GetClient().Create(ctx, cm)).To(Succeed()) + + // Even after peer 6 is removed from spec.externalPeers, its non-local hostname must not be treated as a local replica. + rec.Cluster.Spec.ExternalPeers = rec.Cluster.Spec.ExternalPeers[:1] + + loaded, err := rec.loadQuorumReplicas(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(loaded).To(HaveKey(v1.KeeperReplicaID(3))) + Expect(loaded).To(HaveKey(v1.KeeperReplicaID(4))) + Expect(loaded).To(HaveLen(2)) + + _ = log + }) + + It("should treat a single local follower with externalPeers as Ready and scale-allowed when leader is remote", func(ctx context.Context) { + log, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.Cluster.Spec.Replicas = new(int32(1)) + rec.Cluster.Spec.ReplicaIDOffset = 6 + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1"}, + {ID: 1, Host: "keeper-1.dc1"}, + } + rec.revs = controller.RevisionState{ + ConfigurationRevision: rec.Cluster.Status.ConfigurationRevision, + RestartConfigRevision: rec.Cluster.Status.ConfigurationRevision, + StatefulSetRevision: rec.Cluster.Status.StatefulSetRevision, + } + rec.ReplicaState = map[v1.KeeperReplicaID]replicaState{ + 6: { + Status: serverStatus{ServerState: ModeFollower, Version: "25.8.2.1"}, + ReplicaState: controller.ReplicaState{ + ReplicaResources: controller.ReplicaResources{ + STS: readySTS(rec.Cluster, 6, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 6), + }, + }, + }, + } + + Expect(rec.checkHorizontalScalingAllowed(ctx, log)).To(Succeed()) + Expect(rec.HorizontalScaleAllowed).To(BeTrue()) + + rec.evaluateReplicaConditions() + + readyCond := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionTrue)) + Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonClusterReady)) + Expect(rec.Cluster.Status.ReadyReplicas).To(BeEquivalentTo(1)) + }) + + It("should validate quorum followers against total ensemble size when leader is local", func(ctx context.Context) { + log, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.Cluster.Spec.Replicas = new(int32(2)) + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 2, Host: "keeper-2.dc2"}, + {ID: 3, Host: "keeper-3.dc2"}, + {ID: 4, Host: "keeper-4.dc3"}, + } + rec.revs = controller.RevisionState{ + ConfigurationRevision: rec.Cluster.Status.ConfigurationRevision, + RestartConfigRevision: rec.Cluster.Status.ConfigurationRevision, + StatefulSetRevision: rec.Cluster.Status.StatefulSetRevision, + } + rec.ReplicaState = map[v1.KeeperReplicaID]replicaState{ + 0: { + Status: serverStatus{ServerState: ModeLeader, Followers: 1, Version: "25.8.2.1"}, + ReplicaState: controller.ReplicaState{ + ReplicaResources: controller.ReplicaResources{ + STS: readySTS(rec.Cluster, 0, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 0), + }, + }, + }, + 1: { + Status: serverStatus{ServerState: ModeFollower, Version: "25.8.2.1"}, + ReplicaState: controller.ReplicaState{ + ReplicaResources: controller.ReplicaResources{ + STS: readySTS(rec.Cluster, 1, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 1), + }, + }, + }, + } + + // Total ensemble is 5 -> quorum requires at least 2 followers; 1 is not enough. + Expect(rec.checkHorizontalScalingAllowed(ctx, log)).To(Succeed()) + Expect(rec.HorizontalScaleAllowed).To(BeFalse()) + + rec.evaluateReplicaConditions() + readyCond := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionFalse)) + Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonNotEnoughFollowers)) + + // With all 4 followers connected across DCs, both Ready and ScaleAllowed become True. + leader := rec.ReplicaState[0] + leader.Status.Followers = 4 + rec.ReplicaState[0] = leader + + Expect(rec.checkHorizontalScalingAllowed(ctx, log)).To(Succeed()) + Expect(rec.HorizontalScaleAllowed).To(BeTrue()) + + rec.evaluateReplicaConditions() + readyCond = meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionTrue)) + Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonClusterReady)) + }) +}) + func mustGet[T client.Object](ctx context.Context, c client.Client, key types.NamespacedName) T { var result T diff --git a/internal/controller/keeper/templates.go b/internal/controller/keeper/templates.go index 9f59b6c5f..7f737e272 100644 --- a/internal/controller/keeper/templates.go +++ b/internal/controller/keeper/templates.go @@ -165,20 +165,28 @@ func templateQuorumConfig(r *keeperReconciler) (*corev1.ConfigMap, error) { } func generateQuorumConfig(r *keeperReconciler) quorumConfig { - hostnamesByID := map[v1.KeeperReplicaID]string{} + quorumConfig := make(quorumConfig, 0, len(r.ReplicaState)+len(r.Cluster.Spec.ExternalPeers)) for id := range r.ReplicaState { - hostnamesByID[id] = r.Cluster.HostnameByID(id) - } - - quorumConfig := make(quorumConfig, 0, len(hostnamesByID)) - for id, hostname := range hostnamesByID { quorumConfig = append(quorumConfig, serverConfig{ ID: strconv.FormatInt(int64(id), 10), - Hostname: hostname, + Hostname: r.Cluster.HostnameByID(id), Port: PortInterserver, }) } + for _, peer := range r.Cluster.Spec.ExternalPeers { + port := uint16(PortInterserver) + if peer.Port > 0 { + port = uint16(peer.Port) //nolint:gosec // Port is validated to [1, 65535]. + } + + quorumConfig = append(quorumConfig, serverConfig{ + ID: strconv.FormatInt(int64(peer.ID), 10), + Hostname: peer.Host, + Port: port, + }) + } + slices.SortFunc(quorumConfig, func(a, b serverConfig) int { return strings.Compare(a.ID, b.ID) }) @@ -213,7 +221,7 @@ type keeperServer struct { } func getConfigurationRevision(cr *v1.KeeperCluster) (string, error) { - cfg, err := generateConfigForSingleReplica(cr, 0) + cfg, err := generateConfigForSingleReplica(cr, v1.KeeperReplicaID(cr.Spec.ReplicaIDOffset)) if err != nil { return "", fmt.Errorf("generate template configuration: %w", err) } @@ -227,7 +235,7 @@ func getConfigurationRevision(cr *v1.KeeperCluster) (string, error) { } func getStatefulSetRevision(cr *v1.KeeperCluster, cfgRestartRevision string) (string, error) { - sts, err := templateStatefulSet(cr, 0, cfgRestartRevision) + sts, err := templateStatefulSet(cr, v1.KeeperReplicaID(cr.Spec.ReplicaIDOffset), cfgRestartRevision) if err != nil { return "", fmt.Errorf("generate template StatefulSet: %w", err) } diff --git a/internal/validation_constants.go b/internal/validation_constants.go index 10ac6b2b7..4206ed085 100644 --- a/internal/validation_constants.go +++ b/internal/validation_constants.go @@ -25,6 +25,11 @@ const ( ClickHousePortPrometheusScrape = 9363 ClickHousePortInterserver = 9009 + KeeperPortNative = 2181 + KeeperPortNativeSecure = 2281 + KeeperPortInterserver = 9234 + KeeperMaxReplicas = 15 + ClickHousePortNameManagement = "management" ClickHousePortNameManagementHTTP = "management-http" ClickHousePortNameTCP = "tcp" diff --git a/internal/webhook/v1alpha1/clickhousecluster_webhook.go b/internal/webhook/v1alpha1/clickhousecluster_webhook.go index 48244e7ed..49a9ab02f 100644 --- a/internal/webhook/v1alpha1/clickhousecluster_webhook.go +++ b/internal/webhook/v1alpha1/clickhousecluster_webhook.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "slices" + "strings" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -90,6 +91,14 @@ func (w *ClickHouseClusterWebhook) ValidateUpdate(_ context.Context, oldCluster, errs = append(errs, err) } + if oldCluster.Spec.ShardIDOffset != newCluster.Spec.ShardIDOffset { + errs = append(errs, errors.New("spec.shardIDOffset is immutable")) + } + + if oldCluster.Spec.ReplicaIDOffset != newCluster.Spec.ReplicaIDOffset { + errs = append(errs, errors.New("spec.replicaIDOffset is immutable")) + } + return warns, errors.Join(errs...) } @@ -203,5 +212,69 @@ func (w *ClickHouseClusterWebhook) validateImpl(obj *chv1.ClickHouseCluster) (ad } } + extWarns, extErrs := validateClickHouseExternalReplicas(obj) + warns = append(warns, extWarns...) + errs = append(errs, extErrs...) + + return warns, errs +} + +func validateClickHouseExternalReplicas(obj *chv1.ClickHouseCluster) (admission.Warnings, []error) { + var ( + warns admission.Warnings + errs []error + ) + + if len(obj.Spec.ExternalReplicas) == 0 { + return warns, errs + } + + if obj.Spec.ExternalSecret == nil { + warns = append(warns, ".spec.externalReplicas is set without .spec.externalSecret; "+ + "ensure cluster secrets (interserver-password, cluster-secret, keeper-identity, named-collections-key) match across all Kubernetes clusters") + } + + type hostPort struct { + host string + port int32 + } + + seenIDs := make(map[chv1.ClickHouseReplicaID]int, len(obj.Spec.ExternalReplicas)) + seenEndpoints := make(map[hostPort]int, len(obj.Spec.ExternalReplicas)) + + for i, ext := range obj.Spec.ExternalReplicas { + id := chv1.ClickHouseReplicaID{ShardID: ext.Shard, Index: ext.Replica} + if prev, ok := seenIDs[id]; ok { + errs = append(errs, fmt.Errorf( + "spec.externalReplicas[%d]: shard %d replica %d duplicates spec.externalReplicas[%d]", + i, ext.Shard, ext.Replica, prev, + )) + } else { + seenIDs[id] = i + } + + if !obj.ReplicaObsolete(id) { + errs = append(errs, fmt.Errorf( + "spec.externalReplicas[%d]: shard %d replica %d collides with locally managed replicas", + i, ext.Shard, ext.Replica, + )) + } + + port := ext.Port + if port == 0 { + port = internal.ClickHousePortManagement + } + + ep := hostPort{host: strings.ToLower(ext.Host), port: port} + if prev, ok := seenEndpoints[ep]; ok { + errs = append(errs, fmt.Errorf( + "spec.externalReplicas[%d]: %s:%d duplicates spec.externalReplicas[%d]", + i, ext.Host, port, prev, + )) + } else { + seenEndpoints[ep] = i + } + } + return warns, errs } diff --git a/internal/webhook/v1alpha1/clickhousecluster_webhook_test.go b/internal/webhook/v1alpha1/clickhousecluster_webhook_test.go index 2aa383f60..89dd8f644 100644 --- a/internal/webhook/v1alpha1/clickhousecluster_webhook_test.go +++ b/internal/webhook/v1alpha1/clickhousecluster_webhook_test.go @@ -548,6 +548,96 @@ var _ = Describe("ClickHouseCluster Webhook", func() { Expect(err.Error()).To(ContainSubstring("spec.additionalPorts[0].name")) Expect(err.Error()).To(ContainSubstring("reserved")) }) + + It("Should accept valid multi-cluster offsets and externalReplicas and default port/TLS", func(ctx context.Context) { + cluster := chCluster.DeepCopy() + cluster.Spec.Shards = new(int32(1)) + cluster.Spec.Replicas = new(int32(1)) + cluster.Spec.ReplicaIDOffset = 1 + cluster.Spec.ExternalSecret = &chv1.ExternalSecret{Name: "shared-secret"} + cluster.Spec.ExternalReplicas = []chv1.ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "ch-internal-0-0.ns.svc.k8s.dc1"}, + {Shard: 1, Replica: 0, Host: "ch-internal-1-0.ns.svc.k8s.dc1", Port: 9440, TLS: chv1.ExternalReplicaTLSEnabled}, + } + + Expect(k8sClient.Create(ctx, cluster)).To(Succeed()) + deferCleanup(cluster) + Expect(k8sClient.Get(ctx, cluster.NamespacedName(), cluster)).To(Succeed()) + Expect(cluster.Spec.ExternalReplicas[0].Port).To(BeEquivalentTo(9001)) + Expect(cluster.Spec.ExternalReplicas[0].TLS).To(Equal(chv1.ExternalReplicaTLSDisabled)) + Expect(warnings).NotTo(ContainElement(ContainSubstring("without .spec.externalSecret"))) + }) + + It("Should warn when externalReplicas is set without externalSecret", func(ctx context.Context) { + cluster := chCluster.DeepCopy() + cluster.Spec.Shards = new(int32(1)) + cluster.Spec.Replicas = new(int32(1)) + cluster.Spec.ReplicaIDOffset = 1 + cluster.Spec.ExternalReplicas = []chv1.ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "ch-internal-0-0.ns.svc.k8s.dc1"}, + } + + Expect(k8sClient.Create(ctx, cluster)).To(Succeed()) + deferCleanup(cluster) + Expect(warnings).To(ContainElement(ContainSubstring("without .spec.externalSecret"))) + }) + + It("Should reject colliding or duplicate externalReplicas", func(ctx context.Context) { + By("rejecting collision with local shard and replica") + + cluster := chCluster.DeepCopy() + cluster.Spec.Shards = new(int32(1)) + cluster.Spec.Replicas = new(int32(2)) + cluster.Spec.ShardIDOffset = 1 + cluster.Spec.ReplicaIDOffset = 2 + cluster.Spec.ExternalReplicas = []chv1.ExternalClickHouseReplica{ + {Shard: 1, Replica: 3, Host: "ch-internal-1-3.ns.svc.k8s.dc1"}, + } + + err := k8sClient.Create(ctx, cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("collide")) + + By("rejecting duplicate shard and replica") + + cluster.Spec.ExternalReplicas = []chv1.ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "ch-0.dc1"}, + {Shard: 0, Replica: 0, Host: "ch-1.dc1"}, + } + err = k8sClient.Create(ctx, cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("externalReplicas must not repeat the same shard and replica")) + + By("rejecting duplicate host and port") + + cluster.Spec.ExternalReplicas = []chv1.ExternalClickHouseReplica{ + {Shard: 0, Replica: 0, Host: "ch-0.dc1", Port: 9001}, + {Shard: 0, Replica: 1, Host: "CH-0.dc1"}, + } + err = k8sClient.Create(ctx, cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("duplicates")) + }) + + It("Should reject changing shardIDOffset or replicaIDOffset after creation", func(ctx context.Context) { + cluster := chCluster.DeepCopy() + cluster.Spec.ShardIDOffset = 1 + cluster.Spec.ReplicaIDOffset = 2 + Expect(k8sClient.Create(ctx, cluster)).To(Succeed()) + deferCleanup(cluster) + + updated := cluster.DeepCopy() + updated.Spec.ShardIDOffset = 2 + err := k8sClient.Update(ctx, updated) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("shardIDOffset is immutable")) + + updated = cluster.DeepCopy() + updated.Spec.ReplicaIDOffset = 3 + err = k8sClient.Update(ctx, updated) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("replicaIDOffset is immutable")) + }) }) Context("When validating additionalVolumeClaimTemplates (JBOD)", func() { diff --git a/internal/webhook/v1alpha1/keepercluster_webhook.go b/internal/webhook/v1alpha1/keepercluster_webhook.go index 648c5f90d..259bcd669 100644 --- a/internal/webhook/v1alpha1/keepercluster_webhook.go +++ b/internal/webhook/v1alpha1/keepercluster_webhook.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "strings" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/webhook/admission" @@ -66,6 +67,10 @@ func (w *KeeperClusterWebhook) ValidateUpdate(_ context.Context, oldCluster, new errs = append(errs, err) } + if oldCluster.Spec.ReplicaIDOffset != newCluster.Spec.ReplicaIDOffset { + errs = append(errs, errors.New("spec.replicaIDOffset is immutable")) + } + return warns, errors.Join(errs...) } @@ -78,8 +83,7 @@ func (w *KeeperClusterWebhook) validateImpl(obj *chv1.KeeperCluster) (admission. w.Log.Debug("Validating spec", "name", obj.Name, "namespace", obj.Namespace) var ( - warns admission.Warnings - errs []error + errs []error ) if err := obj.Spec.PodDisruptionBudget.Validate(); err != nil { @@ -99,5 +103,78 @@ func (w *KeeperClusterWebhook) validateImpl(obj *chv1.KeeperCluster) (admission. errs = append(errs, err) } + peerWarns, peerErrs := validateKeeperExternalPeers(obj) + warns = append(warns, peerWarns...) + errs = append(errs, peerErrs...) + + return warns, errs +} + +func validateKeeperExternalPeers(obj *chv1.KeeperCluster) (admission.Warnings, []error) { + var ( + warns admission.Warnings + errs []error + ) + + replicas := obj.Replicas() + peers := obj.Spec.ExternalPeers + offset := obj.Spec.ReplicaIDOffset + + if len(peers) == 0 { + if replicas > 0 && replicas%2 == 0 { + errs = append(errs, fmt.Errorf("spec.replicas: %d must be odd (or 0) unless spec.externalPeers is configured", replicas)) + } + + return warns, errs + } + + total := int(replicas) + len(peers) + if total > internal.KeeperMaxReplicas { + errs = append(errs, fmt.Errorf( + "total Keeper ensemble size (%d local + %d external = %d) must not exceed %d", + replicas, len(peers), total, internal.KeeperMaxReplicas, + )) + } else if replicas > 0 && total%2 == 0 { + warns = append(warns, fmt.Sprintf( + "total Keeper ensemble size (%d local + %d external = %d) is even; an odd number of Raft voting members is recommended for fault tolerance", + replicas, len(peers), total, + )) + } + + type hostPort struct { + host string + port int32 + } + + seenIDs := make(map[int32]int, len(peers)) + seenEndpoints := make(map[hostPort]int, len(peers)) + + for i, peer := range peers { + if prev, ok := seenIDs[peer.ID]; ok { + errs = append(errs, fmt.Errorf("spec.externalPeers[%d].id: %d duplicates spec.externalPeers[%d].id", i, peer.ID, prev)) + } else { + seenIDs[peer.ID] = i + } + + if replicas > 0 && peer.ID >= offset && peer.ID < offset+replicas { + errs = append(errs, fmt.Errorf( + "spec.externalPeers[%d].id: %d collides with locally managed replica IDs [%d..%d]", + i, peer.ID, offset, offset+replicas-1, + )) + } + + port := peer.Port + if port == 0 { + port = internal.KeeperPortInterserver + } + + ep := hostPort{host: strings.ToLower(peer.Host), port: port} + if prev, ok := seenEndpoints[ep]; ok { + errs = append(errs, fmt.Errorf("spec.externalPeers[%d]: %s:%d duplicates spec.externalPeers[%d]", i, peer.Host, port, prev)) + } else { + seenEndpoints[ep] = i + } + } + return warns, errs } diff --git a/internal/webhook/v1alpha1/keepercluster_webhook_test.go b/internal/webhook/v1alpha1/keepercluster_webhook_test.go index 6e4d5036d..3840e2883 100644 --- a/internal/webhook/v1alpha1/keepercluster_webhook_test.go +++ b/internal/webhook/v1alpha1/keepercluster_webhook_test.go @@ -237,5 +237,124 @@ var _ = Describe("KeeperCluster Webhook", func() { Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("only one of")) }) + + It("Should reject even replicas when externalPeers is empty", func(ctx context.Context) { + cluster := chv1.KeeperCluster{ + ObjectMeta: meta, + Spec: chv1.KeeperClusterSpec{ + Replicas: new(int32(2)), + }, + } + + err := k8sClient.Create(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("must be odd")) + }) + + It("Should accept even replicas with externalPeers and default peer Raft port", func(ctx context.Context) { + cluster := chv1.KeeperCluster{ + ObjectMeta: meta, + Spec: chv1.KeeperClusterSpec{ + Replicas: new(int32(2)), + ReplicaIDOffset: 3, + ClusterDomain: "k8s.dc2", + ExternalPeers: []chv1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1"}, + {ID: 1, Host: "keeper-1.dc1", Port: 9234, ClientPort: 2181}, + {ID: 2, Host: "keeper-2.dc1"}, + }, + }, + } + + Expect(k8sClient.Create(ctx, &cluster)).To(Succeed()) + deferCleanup(&cluster) + Expect(k8sClient.Get(ctx, cluster.NamespacedName(), &cluster)).To(Succeed()) + Expect(cluster.Spec.ExternalPeers[0].Port).To(BeEquivalentTo(9234)) + }) + + It("Should warn when total multi-cluster Keeper ensemble size is even", func(ctx context.Context) { + cluster := chv1.KeeperCluster{ + ObjectMeta: meta, + Spec: chv1.KeeperClusterSpec{ + Replicas: new(int32(2)), + ReplicaIDOffset: 2, + ExternalPeers: []chv1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1"}, + {ID: 1, Host: "keeper-1.dc1"}, + }, + }, + } + + Expect(k8sClient.Create(ctx, &cluster)).To(Succeed()) + deferCleanup(&cluster) + Expect(warnings).To(ContainElement(ContainSubstring("total Keeper ensemble size"))) + }) + + It("Should reject externalPeers colliding with local replica IDs or repeating ids/endpoints", func(ctx context.Context) { + By("rejecting collision with local replica range") + + cluster := chv1.KeeperCluster{ + ObjectMeta: meta, + Spec: chv1.KeeperClusterSpec{ + Replicas: new(int32(3)), + ReplicaIDOffset: 3, + ExternalPeers: []chv1.ExternalKeeperPeer{ + {ID: 4, Host: "keeper-4.dc1"}, + }, + }, + } + err := k8sClient.Create(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("collide")) + + By("rejecting duplicate peer IDs") + + cluster.Spec.ExternalPeers = []chv1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1"}, + {ID: 0, Host: "keeper-1.dc1"}, + } + err = k8sClient.Create(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("externalPeers must not repeat the same id")) + + By("rejecting duplicate peer host and port") + + cluster.Spec.ExternalPeers = []chv1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1", Port: 9234}, + {ID: 1, Host: "KEEPER-0.dc1"}, + } + err = k8sClient.Create(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("externalPeers must not repeat the same host and port")) + + By("rejecting total ensemble size above 15") + + cluster.Spec.Replicas = new(int32(14)) + cluster.Spec.ReplicaIDOffset = 2 + cluster.Spec.ExternalPeers = []chv1.ExternalKeeperPeer{ + {ID: 0, Host: "keeper-0.dc1"}, + {ID: 1, Host: "keeper-1.dc1"}, + } + err = k8sClient.Create(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("must not exceed 15")) + }) + + It("Should reject changing replicaIDOffset after creation", func(ctx context.Context) { + cluster := chv1.KeeperCluster{ + ObjectMeta: meta, + Spec: chv1.KeeperClusterSpec{ + Replicas: new(int32(1)), + ReplicaIDOffset: 3, + }, + } + Expect(k8sClient.Create(ctx, &cluster)).To(Succeed()) + deferCleanup(&cluster) + + cluster.Spec.ReplicaIDOffset = 6 + err := k8sClient.Update(ctx, &cluster) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("replicaIDOffset is immutable")) + }) }) }) From 250bc5e044c113c90e59a98c82d06decaf9fad5e Mon Sep 17 00:00:00 2001 From: Vasiliy Koshkin <61789920+melancholictheory@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:10:59 +0300 Subject: [PATCH 2/4] fix(keeper): require strict majority (N/2 followers) for quorum readiness --- internal/controller/keeper/sync.go | 6 +- internal/controller/keeper/sync_test.go | 77 +++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/internal/controller/keeper/sync.go b/internal/controller/keeper/sync.go index 07b17a18e..464791f5b 100644 --- a/internal/controller/keeper/sync.go +++ b/internal/controller/keeper/sync.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "maps" - "math" "slices" "strconv" "strings" @@ -686,7 +685,8 @@ func (r *keeperReconciler) evaluateReplicaConditions() { } case len(r.Cluster.Spec.ExternalPeers) > 0: - requiredFollowersForQuorum := int(math.Ceil(float64(totalReplicas)/2)) - 1 + // Raft strict majority is totalReplicas/2 + 1, so excluding the leader quorum requires totalReplicas/2 followers. + requiredFollowersForQuorum := totalReplicas / 2 switch { case len(replicasByMode[ModeStandalone]) > 0: @@ -734,7 +734,7 @@ func (r *keeperReconciler) evaluateReplicaConditions() { } default: - requiredFollowersForQuorum := int(math.Ceil(float64(exists)/2)) - 1 + requiredFollowersForQuorum := exists / 2 switch { case len(replicasByMode[ModeStandalone]) > 0: diff --git a/internal/controller/keeper/sync_test.go b/internal/controller/keeper/sync_test.go index df9c7f4e5..0536ea7d1 100644 --- a/internal/controller/keeper/sync_test.go +++ b/internal/controller/keeper/sync_test.go @@ -519,6 +519,83 @@ var _ = Describe("Multi-cluster Keeper", func() { Expect(readyCond.Status).To(Equal(metav1.ConditionTrue)) Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonClusterReady)) }) + + It("should require strict Raft majority (N/2 followers) for even-sized multi-cluster ensembles", func() { + _, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.revs = controller.RevisionState{ + ConfigurationRevision: rec.Cluster.Status.ConfigurationRevision, + RestartConfigRevision: rec.Cluster.Status.ConfigurationRevision, + StatefulSetRevision: rec.Cluster.Status.StatefulSetRevision, + } + + By("requiring 1 follower for a 2-node ensemble (1 local + 1 external)") + + rec.Cluster.Spec.Replicas = new(int32(1)) + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 1, Host: "keeper-1.dc2"}, + } + rec.ReplicaState = map[v1.KeeperReplicaID]replicaState{ + 0: { + Status: serverStatus{ServerState: ModeLeader, Followers: 0, Version: "25.8.2.1"}, + ReplicaState: controller.ReplicaState{ + ReplicaResources: controller.ReplicaResources{ + STS: readySTS(rec.Cluster, 0, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 0), + }, + }, + }, + } + + rec.evaluateReplicaConditions() + readyCond := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionFalse)) + Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonNotEnoughFollowers)) + + leader := rec.ReplicaState[0] + leader.Status.Followers = 1 + rec.ReplicaState[0] = leader + + rec.evaluateReplicaConditions() + readyCond = meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionTrue)) + + By("requiring 2 followers for a 4-node ensemble (2 local + 2 external)") + + rec.Cluster.Spec.Replicas = new(int32(2)) + rec.Cluster.Spec.ExternalPeers = []v1.ExternalKeeperPeer{ + {ID: 2, Host: "keeper-2.dc2"}, + {ID: 3, Host: "keeper-3.dc2"}, + } + rec.ReplicaState[0] = replicaState{ + Status: serverStatus{ServerState: ModeLeader, Followers: 1, Version: "25.8.2.1"}, + STS: readySTS(rec.Cluster, 0, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 0), + } + rec.ReplicaState[1] = replicaState{ + Status: serverStatus{ServerState: ModeFollower, Version: "25.8.2.1"}, + STS: readySTS(rec.Cluster, 1, rec.revs.StatefulSetRevision), + CFG: readyCFG(rec.Cluster, 1), + } + + rec.evaluateReplicaConditions() + readyCond = meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionFalse)) + Expect(readyCond.Reason).To(Equal(v1.KeeperConditionReasonNotEnoughFollowers)) + + leader = rec.ReplicaState[0] + leader.Status.Followers = 2 + rec.ReplicaState[0] = leader + + rec.evaluateReplicaConditions() + readyCond = meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(readyCond).NotTo(BeNil()) + Expect(readyCond.Status).To(Equal(metav1.ConditionTrue)) + }) }) func mustGet[T client.Object](ctx context.Context, c client.Client, key types.NamespacedName) T { From eca7e321ada2b2bd7b685b5447bf4f62eebd9032 Mon Sep 17 00:00:00 2001 From: Vasiliy Koshkin <61789920+melancholictheory@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:46:38 +0300 Subject: [PATCH 3/4] fix(clickhouse): parse PDB shard ID with ParseInt(..., 10, 32) --- internal/controller/clickhouse/sync.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/controller/clickhouse/sync.go b/internal/controller/clickhouse/sync.go index 626599d94..4fb384972 100644 --- a/internal/controller/clickhouse/sync.go +++ b/internal/controller/clickhouse/sync.go @@ -268,13 +268,13 @@ func (r *clickhouseReconciler) reconcilePodDisruptionBudget(ctx context.Context, } for _, pdb := range disruptionBudgets.Items { - shardID, err := strconv.Atoi(pdb.Labels[ctrlutil.LabelClickHouseShardID]) + shardID, err := strconv.ParseInt(pdb.Labels[ctrlutil.LabelClickHouseShardID], 10, 32) if err != nil { log.Warn("failed to get shard ID from PodDisruptionBudget labels", "poddisruptionbudget", pdb.Name, "error", err) continue } - if !pdbEnabled || r.Cluster.ShardObsolete(int32(shardID)) { //nolint:gosec // Shard IDs are bounded by CRD validation. + if !pdbEnabled || r.Cluster.ShardObsolete(int32(shardID)) { log.Info("removing PodDisruptionBudget", "poddisruptionbudget", pdb.Name) if err := r.Delete(ctx, &pdb, v1.EventActionReconciling); err != nil { From deac6d8676a13c7ae2b0a3c68e98cef99905a3f9 Mon Sep 17 00:00:00 2001 From: Vasiliy Koshkin <61789920+melancholictheory@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:45:39 +0300 Subject: [PATCH 4/4] Enforce CRD CEL offset immutability, verify external peer TLS, and fix Vale docs lint --- api/v1alpha1/clickhousecluster_types.go | 12 +- api/v1alpha1/keepercluster_types.go | 7 +- .../clickhouse.com_clickhouseclusters.yaml | 12 +- .../bases/clickhouse.com_keeperclusters.yaml | 9 +- dist/chart-cluster/values.yaml | 8 +- .../clickhouseclusters.clickhouse.com.yaml | 12 +- .../crd/keeperclusters.clickhouse.com.yaml | 9 +- docs/guides/configuration.mdx | 2 +- docs/reference/api-reference.mdx | 14 +- internal/controller/clickhouse/commands.go | 53 +++++- .../controller/clickhouse/commands_test.go | 174 ++++++++++++++++++ internal/controller/clickhouse/constants.go | 1 + .../controller/clickhouse/controller_test.go | 27 +++ internal/controller/clickhouse/sync.go | 40 +++- internal/controller/clickhouse/sync_test.go | 70 +++++++ internal/controller/keeper/controller_test.go | 17 ++ 16 files changed, 422 insertions(+), 45 deletions(-) diff --git a/api/v1alpha1/clickhousecluster_types.go b/api/v1alpha1/clickhousecluster_types.go index 417b12c07..3b263bf7a 100644 --- a/api/v1alpha1/clickhousecluster_types.go +++ b/api/v1alpha1/clickhousecluster_types.go @@ -37,6 +37,8 @@ func (s *ClickHouseNetworkPolicySpec) Enabled() bool { // ClickHouseClusterSpec defines the desired state of ClickHouseCluster. // +kubebuilder:validation:XValidation:rule="has(self.keeperClusterRef) != has(self.externalKeeper)",message="exactly one of keeperClusterRef or externalKeeper must be set" // +kubebuilder:validation:XValidation:rule="!has(self.externalReplicas) || self.externalReplicas.all(r, r.shard < (has(self.shardIDOffset) ? self.shardIDOffset : 0) || r.shard >= (has(self.shardIDOffset) ? self.shardIDOffset : 0) + (has(self.shards) ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))",message="externalReplicas must not collide with locally managed shard and replica IDs" +// +kubebuilder:validation:XValidation:rule="(has(self.shardIDOffset) ? self.shardIDOffset : 0) == (has(oldSelf.shardIDOffset) ? oldSelf.shardIDOffset : 0)",message="shardIDOffset is immutable" +// +kubebuilder:validation:XValidation:rule="(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) ? oldSelf.replicaIDOffset : 0)",message="replicaIDOffset is immutable" type ClickHouseClusterSpec struct { // Number of replicas in the single shard. // +optional @@ -70,7 +72,7 @@ type ClickHouseClusterSpec struct { // ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster // (for example, by another clickhouse-operator instance in a different cluster or region). - // The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + // The operator includes them in `remote_servers` and preserves their Keeper metadata during cleanup // without creating Kubernetes workloads for them. // +optional // +listType=atomic @@ -434,12 +436,12 @@ type ExternalKeeperNode struct { Port int32 `json:"port,omitempty"` } -// ExternalReplicaTLSPolicy controls how remote_servers connects to an external ClickHouse replica. +// ExternalReplicaTLSPolicy controls how `remote_servers` connects to an external ClickHouse replica. // +kubebuilder:validation:Enum=Enabled;Disabled type ExternalReplicaTLSPolicy string const ( - // ExternalReplicaTLSEnabled makes remote_servers connect to the external replica over TLS. + // ExternalReplicaTLSEnabled makes `remote_servers` connect to the external replica over TLS. ExternalReplicaTLSEnabled ExternalReplicaTLSPolicy = "Enabled" // ExternalReplicaTLSDisabled is the default policy: connections are made in plain text. ExternalReplicaTLSDisabled ExternalReplicaTLSPolicy = "Disabled" @@ -464,7 +466,7 @@ type ExternalClickHouseReplica struct { // +kubebuilder:validation:MaxLength=253 Host string `json:"host"` - // Port is the native TCP port used for remote_servers communication. + // Port is the native TCP port used for `remote_servers` communication. // Defaults to 9001 (the operator internal management TCP port). // +optional // +kubebuilder:default:=9001 @@ -472,7 +474,7 @@ type ExternalClickHouseReplica struct { // +kubebuilder:validation:Maximum=65535 Port int32 `json:"port,omitempty"` - // TLS controls whether remote_servers connects to this external replica over TLS. + // TLS controls whether `remote_servers` connects to this external replica over TLS. // Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. // +optional // +kubebuilder:default:=Disabled diff --git a/api/v1alpha1/keepercluster_types.go b/api/v1alpha1/keepercluster_types.go index ad339d3f1..80d583a73 100644 --- a/api/v1alpha1/keepercluster_types.go +++ b/api/v1alpha1/keepercluster_types.go @@ -37,10 +37,11 @@ func (s *KeeperNetworkPolicySpec) Enabled() bool { // +kubebuilder:validation:XValidation:rule="(has(self.externalPeers) && size(self.externalPeers) > 0) || !has(self.replicas) || self.replicas == 0 || self.replicas % 2 == 1",message="replicas must be odd (or 0) unless externalPeers is configured" // +kubebuilder:validation:XValidation:rule="!has(self.externalPeers) || (has(self.replicas) ? self.replicas : 3) + size(self.externalPeers) <= 15",message="total Keeper ensemble size (replicas + externalPeers) must not exceed 15" // +kubebuilder:validation:XValidation:rule="!has(self.externalPeers) || self.externalPeers.all(p, p.id < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))",message="externalPeers must not collide with locally managed replica IDs" +// +kubebuilder:validation:XValidation:rule="(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) ? oldSelf.replicaIDOffset : 0)",message="replicaIDOffset is immutable" type KeeperClusterSpec struct { // Number of locally managed replicas in the cluster. - // Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, - // as long as replicas + len(externalPeers) <= 15. + // Must be odd (or 0) when `externalPeers` is empty; may be any value from 0 to 15 when `externalPeers` is set, + // as long as `replicas + len(externalPeers) <= 15`. // +optional // +kubebuilder:default:=3 // +kubebuilder:validation:Enum=0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15 @@ -58,7 +59,7 @@ type KeeperClusterSpec struct { // ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster // (for example, by another clickhouse-operator instance in a different cluster or region). - // The operator includes them in raft_configuration without creating Kubernetes workloads for them. + // The operator includes them in `raft_configuration` without creating Kubernetes workloads for them. // +optional // +listType=atomic // +kubebuilder:validation:MaxItems=14 diff --git a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml index 46d37faa1..bf3dee4bd 100644 --- a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml +++ b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml @@ -1040,7 +1040,7 @@ spec: description: |- ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster (for example, by another clickhouse-operator instance in a different cluster or region). - The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + The operator includes them in `remote_servers` and preserves their Keeper metadata during cleanup without creating Kubernetes workloads for them. items: description: ExternalClickHouseReplica addresses a single ClickHouse @@ -1056,7 +1056,7 @@ spec: port: default: 9001 description: |- - Port is the native TCP port used for remote_servers communication. + Port is the native TCP port used for `remote_servers` communication. Defaults to 9001 (the operator internal management TCP port). format: int32 maximum: 65535 @@ -1080,7 +1080,7 @@ spec: tls: default: Disabled description: |- - TLS controls whether remote_servers connects to this external replica over TLS. + TLS controls whether `remote_servers` connects to this external replica over TLS. Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. enum: - Enabled @@ -4085,6 +4085,12 @@ spec: ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))' + - message: shardIDOffset is immutable + rule: '(has(self.shardIDOffset) ? self.shardIDOffset : 0) == (has(oldSelf.shardIDOffset) + ? oldSelf.shardIDOffset : 0)' + - message: replicaIDOffset is immutable + rule: '(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) + ? oldSelf.replicaIDOffset : 0)' status: description: ClickHouseClusterStatus defines the observed state of ClickHouseCluster. properties: diff --git a/config/crd/bases/clickhouse.com_keeperclusters.yaml b/config/crd/bases/clickhouse.com_keeperclusters.yaml index 8f82a4c70..e9cb6e9e7 100644 --- a/config/crd/bases/clickhouse.com_keeperclusters.yaml +++ b/config/crd/bases/clickhouse.com_keeperclusters.yaml @@ -825,7 +825,7 @@ spec: description: |- ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster (for example, by another clickhouse-operator instance in a different cluster or region). - The operator includes them in raft_configuration without creating Kubernetes workloads for them. + The operator includes them in `raft_configuration` without creating Kubernetes workloads for them. items: description: ExternalKeeperPeer addresses a single Raft peer of a Keeper ensemble managed outside this Kubernetes cluster. @@ -3256,8 +3256,8 @@ spec: default: 3 description: |- Number of locally managed replicas in the cluster. - Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, - as long as replicas + len(externalPeers) <= 15. + Must be odd (or 0) when `externalPeers` is empty; may be any value from 0 to 15 when `externalPeers` is set, + as long as `replicas + len(externalPeers) <= 15`. enum: - 0 - 1 @@ -3691,6 +3691,9 @@ spec: (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))' + - message: replicaIDOffset is immutable + rule: '(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) + ? oldSelf.replicaIDOffset : 0)' status: description: KeeperClusterStatus defines the observed state of KeeperCluster. properties: diff --git a/dist/chart-cluster/values.yaml b/dist/chart-cluster/values.yaml index 6e3c0a3c4..2a72d6333 100644 --- a/dist/chart-cluster/values.yaml +++ b/dist/chart-cluster/values.yaml @@ -78,7 +78,7 @@ clickhouse: # ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster # (for example, by another clickhouse-operator instance in a different cluster or region). - # The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + # The operator includes them in `remote_servers` and preserves their Keeper metadata during cleanup # without creating Kubernetes workloads for them. # externalReplicas: [] @@ -176,7 +176,7 @@ keeper: # ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster # (for example, by another clickhouse-operator instance in a different cluster or region). - # The operator includes them in raft_configuration without creating Kubernetes workloads for them. + # The operator includes them in `raft_configuration` without creating Kubernetes workloads for them. # externalPeers: [] # Additional labels that are added to resources. @@ -200,8 +200,8 @@ keeper: # replicaIDOffset: 0 # Number of locally managed replicas in the cluster. - # Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, - # as long as replicas + len(externalPeers) <= 15. + # Must be odd (or 0) when `externalPeers` is empty; may be any value from 0 to 15 when `externalPeers` is set, + # as long as `replicas + len(externalPeers) <= 15`. replicas: 3 # Configuration parameters for ClickHouse Keeper server. diff --git a/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml b/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml index da9b1c6d7..661909a50 100644 --- a/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml @@ -1043,7 +1043,7 @@ spec: description: |- ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster (for example, by another clickhouse-operator instance in a different cluster or region). - The operator includes them in remote_servers and preserves their Keeper metadata during cleanup + The operator includes them in `remote_servers` and preserves their Keeper metadata during cleanup without creating Kubernetes workloads for them. items: description: ExternalClickHouseReplica addresses a single ClickHouse @@ -1059,7 +1059,7 @@ spec: port: default: 9001 description: |- - Port is the native TCP port used for remote_servers communication. + Port is the native TCP port used for `remote_servers` communication. Defaults to 9001 (the operator internal management TCP port). format: int32 maximum: 65535 @@ -1083,7 +1083,7 @@ spec: tls: default: Disabled description: |- - TLS controls whether remote_servers connects to this external replica over TLS. + TLS controls whether `remote_servers` connects to this external replica over TLS. Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. enum: - Enabled @@ -4088,6 +4088,12 @@ spec: ? self.shards : 1) || r.replica < (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || r.replica >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))' + - message: shardIDOffset is immutable + rule: '(has(self.shardIDOffset) ? self.shardIDOffset : 0) == (has(oldSelf.shardIDOffset) + ? oldSelf.shardIDOffset : 0)' + - message: replicaIDOffset is immutable + rule: '(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) + ? oldSelf.replicaIDOffset : 0)' status: description: ClickHouseClusterStatus defines the observed state of ClickHouseCluster. properties: diff --git a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml index 1c3d34c9b..8fe2f733f 100644 --- a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml @@ -828,7 +828,7 @@ spec: description: |- ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster (for example, by another clickhouse-operator instance in a different cluster or region). - The operator includes them in raft_configuration without creating Kubernetes workloads for them. + The operator includes them in `raft_configuration` without creating Kubernetes workloads for them. items: description: ExternalKeeperPeer addresses a single Raft peer of a Keeper ensemble managed outside this Kubernetes cluster. @@ -3259,8 +3259,8 @@ spec: default: 3 description: |- Number of locally managed replicas in the cluster. - Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set, - as long as replicas + len(externalPeers) <= 15. + Must be odd (or 0) when `externalPeers` is empty; may be any value from 0 to 15 when `externalPeers` is set, + as long as `replicas + len(externalPeers) <= 15`. enum: - 0 - 1 @@ -3694,6 +3694,9 @@ spec: (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) || p.id >= (has(self.replicaIDOffset) ? self.replicaIDOffset : 0) + (has(self.replicas) ? self.replicas : 3))' + - message: replicaIDOffset is immutable + rule: '(has(self.replicaIDOffset) ? self.replicaIDOffset : 0) == (has(oldSelf.replicaIDOffset) + ? oldSelf.replicaIDOffset : 0)' status: description: KeeperClusterStatus defines the observed state of KeeperCluster. properties: diff --git a/docs/guides/configuration.mdx b/docs/guides/configuration.mdx index 79603f241..b519a2820 100644 --- a/docs/guides/configuration.mdx +++ b/docs/guides/configuration.mdx @@ -1282,7 +1282,7 @@ Use `spec.shardIDOffset`, `spec.replicaIDOffset`, and `spec.externalReplicas` to or replicas of a single ClickHouse cluster across Kubernetes clusters: - Set `replicaIDOffset` to place replicas of the same shard in different clusters (active-active HA - and datacenter failover). + and regional redundancy). - Set `shardIDOffset` to place different shards in different clusters. - List every remote replica in `externalReplicas` with its `(shard, replica)` coordinates and reachable `host` (typically the remote replica's internal headless Service diff --git a/docs/reference/api-reference.mdx b/docs/reference/api-reference.mdx index 1db3970ce..c941e7ad5 100644 --- a/docs/reference/api-reference.mdx +++ b/docs/reference/api-reference.mdx @@ -78,7 +78,7 @@ ClickHouseClusterSpec defines the desired state of ClickHouseCluster. | `shards` | integer | Number of shards in the cluster. | false | 1 | | `shardIDOffset` | integer | ShardIDOffset is the starting shard index for locally managed shards.
Set distinct offsets across Kubernetes clusters when distributing shards across multiple clusters.
Defaults to 0. Cannot be changed after cluster creation. | false | | | `replicaIDOffset` | integer | ReplicaIDOffset is the starting replica index within each shard for locally managed replicas.
Set distinct non-overlapping offsets across Kubernetes clusters sharing the same shards
(for example 0, 10, 20 to leave room for independent scaling in each cluster).
Defaults to 0. Cannot be changed after cluster creation. | false | | -| `externalReplicas` | [ExternalClickHouseReplica](#externalclickhousereplica) array | ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in remote_servers and preserves their Keeper metadata during cleanup
without creating Kubernetes workloads for them. | false | | +| `externalReplicas` | [ExternalClickHouseReplica](#externalclickhousereplica) array | ExternalReplicas lists ClickHouse replicas of the same logical cluster managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in `remote_servers` and preserves their Keeper metadata during cleanup
without creating Kubernetes workloads for them. | false | | | `keeperClusterRef` | [KeeperClusterReference](#keeperclusterreference) | Reference to the KeeperCluster that is used for ClickHouse coordination.
When namespace is omitted, the ClickHouseCluster namespace is used.
Mutually exclusive with `externalKeeper`, exactly one of them must be set. | false | | | `externalKeeper` | [ExternalKeeperSpec](#externalkeeperspec) | Keeper ensemble that is not managed by this operator, used for ClickHouse coordination.
The operator does not own the lifecycle of these servers and only points ClickHouse at them.
Mutually exclusive with `keeperClusterRef`, exactly one of them must be set. | false | | | `podTemplate` | [PodTemplateSpec](#podtemplatespec) | Parameters passed to the ClickHouse pod spec. | false | | @@ -249,8 +249,8 @@ ExternalClickHouseReplica addresses a single ClickHouse replica managed outside | `shard` | integer | Shard is the shard index this external replica belongs to. | true | | | `replica` | integer | Replica is the replica index within the shard.
Must not collide with any locally managed replica in the same shard. | true | | | `host` | string | Host is the DNS name or IP address of the external ClickHouse replica reachable from this cluster.
IPv6 addresses must be enclosed in square brackets. | true | | -| `port` | integer | Port is the native TCP port used for remote_servers communication.
Defaults to 9001 (the operator internal management TCP port). | false | 9001 | -| `tls` | [ExternalReplicaTLSPolicy](#externalreplicatlspolicy) | TLS controls whether remote_servers connects to this external replica over TLS.
Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. | false | Disabled | +| `port` | integer | Port is the native TCP port used for `remote_servers` communication.
Defaults to 9001 (the operator internal management TCP port). | false | 9001 | +| `tls` | [ExternalReplicaTLSPolicy](#externalreplicatlspolicy) | TLS controls whether `remote_servers` connects to this external replica over TLS.
Server certificates are verified against the system trust store and `spec.settings.tls.caBundle`. | false | Disabled | Appears in: - [ClickHouseClusterSpec](#clickhouseclusterspec) @@ -307,11 +307,11 @@ Appears in: ## ExternalReplicaTLSPolicy {#externalreplicatlspolicy} -ExternalReplicaTLSPolicy controls how remote_servers connects to an external ClickHouse replica. +ExternalReplicaTLSPolicy controls how `remote_servers` connects to an external ClickHouse replica. | Field | Description | |-------|-------------| -| `Enabled` | ExternalReplicaTLSEnabled makes remote_servers connect to the external replica over TLS.
| +| `Enabled` | ExternalReplicaTLSEnabled makes `remote_servers` connect to the external replica over TLS.
| | `Disabled` | ExternalReplicaTLSDisabled is the default policy: connections are made in plain text.
| Appears in: @@ -405,9 +405,9 @@ KeeperClusterSpec defines the desired state of KeeperCluster. | Field | Type | Description | Required | Default | |-------|------|-------------|----------|---------| -| `replicas` | integer | Number of locally managed replicas in the cluster.
Must be odd (or 0) when externalPeers is empty; may be any value from 0 to 15 when externalPeers is set,
as long as replicas + len(externalPeers) <= 15. | false | 3 | +| `replicas` | integer | Number of locally managed replicas in the cluster.
Must be odd (or 0) when `externalPeers` is empty; may be any value from 0 to 15 when `externalPeers` is set,
as long as `replicas + len(externalPeers) <= 15`. | false | 3 | | `replicaIDOffset` | integer | ReplicaIDOffset is the starting Raft server ID for locally managed replicas.
Set distinct non-overlapping offsets across Kubernetes clusters participating in the same Keeper ensemble
(for example 0, 10, 20 to leave room for independent scaling in each cluster).
Defaults to 0. Cannot be changed after cluster creation. | false | | -| `externalPeers` | [ExternalKeeperPeer](#externalkeeperpeer) array | ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in raft_configuration without creating Kubernetes workloads for them. | false | | +| `externalPeers` | [ExternalKeeperPeer](#externalkeeperpeer) array | ExternalPeers lists Raft peers of the same Keeper ensemble managed outside this Kubernetes cluster
(for example, by another clickhouse-operator instance in a different cluster or region).
The operator includes them in `raft_configuration` without creating Kubernetes workloads for them. | false | | | `podTemplate` | [PodTemplateSpec](#podtemplatespec) | Parameters passed to the Keeper pod spec. | false | | | `containerTemplate` | [ContainerTemplateSpec](#containertemplatespec) | Parameters passed to the Keeper container spec. | false | | | `dataVolumeClaimSpec` | [PersistentVolumeClaimSpec](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.28/#persistentvolumeclaimspec-v1-core) | Specification of persistent storage for ClickHouse Keeper data. | false | | diff --git a/internal/controller/clickhouse/commands.go b/internal/controller/clickhouse/commands.go index faa34a5d3..f5f149ae5 100644 --- a/internal/controller/clickhouse/commands.go +++ b/internal/controller/clickhouse/commands.go @@ -3,6 +3,7 @@ package clickhouse import ( "context" "crypto/tls" + "crypto/x509" "database/sql" "errors" "fmt" @@ -77,11 +78,12 @@ type databaseDescriptor struct { type replicaResolver func(id v1.ClickHouseReplicaID) (string, error) type commander struct { - log controllerutil.Logger - cluster *v1.ClickHouseCluster - auth clickhouse.Auth - dialer controllerutil.DialContextFunc - resolver replicaResolver + log controllerutil.Logger + cluster *v1.ClickHouseCluster + auth clickhouse.Auth + dialer controllerutil.DialContextFunc + resolver replicaResolver + caBundleLoader func(context.Context) ([]byte, error) entry *connCacheEntry } @@ -706,17 +708,22 @@ func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseRe port = PortManagement } + host := strings.Trim(ext.Host, "[]") opts := &clickhouse.Options{ - Addr: []string{net.JoinHostPort(strings.Trim(ext.Host, "[]"), strconv.Itoa(int(port)))}, + Addr: []string{net.JoinHostPort(host, strconv.Itoa(int(port)))}, Auth: cmd.auth, DialContext: cmd.dialer, DialTimeout: dialTimeout, } + if ext.TLS == v1.ExternalReplicaTLSEnabled { - opts.TLS = &tls.Config{ - //nolint:gosec // User managed certificate may be issued for external or custom hostnames. - InsecureSkipVerify: true, + tlsCfg, err := cmd.externalPeerTLSConfig(ctx, host) + if err != nil { + cmd.log.Warn("failed to build TLS config for external shard peer", "host", ext.Host, "error", err) + continue } + + opts.TLS = tlsCfg } conn, err := clickhouse.Open(opts) @@ -739,6 +746,34 @@ func (cmd *commander) shardPeerConn(ctx context.Context, exclude v1.ClickHouseRe return peerConn{}, fmt.Errorf("no reachable peer in shard %d for replica %s", exclude.ShardID, exclude) } +func (cmd *commander) externalPeerTLSConfig(ctx context.Context, host string) (*tls.Config, error) { + rootCAs, err := x509.SystemCertPool() + if err != nil || rootCAs == nil { + rootCAs = x509.NewCertPool() + } + + if cmd.cluster.Spec.Settings.TLS.CABundle != nil { + if cmd.caBundleLoader == nil { + return nil, errors.New("CA bundle configured but loader is not set") + } + + caPEM, err := cmd.caBundleLoader(ctx) + if err != nil { + return nil, fmt.Errorf("load CA bundle: %w", err) + } + + if !rootCAs.AppendCertsFromPEM(caPEM) { + return nil, errors.New("CA bundle contains no valid PEM certificates") + } + } + + return &tls.Config{ + RootCAs: rootCAs, + ServerName: strings.Trim(host, "[]"), + MinVersion: tls.VersionTLS12, + }, nil +} + func (cmd *commander) getConn(id v1.ClickHouseReplicaID) (clickhouse.Conn, error) { addr, err := cmd.resolver(id) if err != nil { diff --git a/internal/controller/clickhouse/commands_test.go b/internal/controller/clickhouse/commands_test.go index b734c4390..e52cd7d74 100644 --- a/internal/controller/clickhouse/commands_test.go +++ b/internal/controller/clickhouse/commands_test.go @@ -2,7 +2,16 @@ package clickhouse import ( "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" "fmt" + "math/big" "net" "slices" "strconv" @@ -619,3 +628,168 @@ var _ = Describe("connCache", func() { Expect(err).To(MatchError("connection cache entry is closed")) }) }) + +var _ = Describe("externalPeerTLSConfig", func() { + generateTestTLS := func(dnsName string) ([]byte, tls.Certificate) { + caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + Expect(err).NotTo(HaveOccurred()) + + now := time.Now() + caTemplate := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{CommonName: "test-ca"}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + IsCA: true, + } + + caDER, err := x509.CreateCertificate(rand.Reader, caTemplate, caTemplate, &caKey.PublicKey, caKey) + Expect(err).NotTo(HaveOccurred()) + + caPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: caDER}) + + leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + Expect(err).NotTo(HaveOccurred()) + + leafTemplate := &x509.Certificate{ + SerialNumber: big.NewInt(2), + Subject: pkix.Name{CommonName: dnsName}, + DNSNames: []string{dnsName}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + } + + leafDER, err := x509.CreateCertificate(rand.Reader, leafTemplate, caTemplate, &leafKey.PublicKey, caKey) + Expect(err).NotTo(HaveOccurred()) + + return caPEM, tls.Certificate{ + Certificate: [][]byte{leafDER}, + PrivateKey: leafKey, + } + } + + startTLSServer := func(cert tls.Certificate) string { + ln, err := tls.Listen("tcp", "127.0.0.1:0", &tls.Config{ + Certificates: []tls.Certificate{cert}, + MinVersion: tls.VersionTLS12, + }) + Expect(err).NotTo(HaveOccurred()) + + DeferCleanup(func() { + _ = ln.Close() + }) + + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + + go func(c net.Conn) { + defer func() { _ = c.Close() }() + + tlsConn, ok := c.(*tls.Conn) + if ok { + _ = tlsConn.Handshake() + } + }(conn) + } + }() + + return ln.Addr().String() + } + + It("verifies peer certificates using configured CA bundle and rejects untrusted servers", func(ctx context.Context) { + const peerHost = "peer.dc2.example.com" + + caPEM, serverCert := generateTestTLS(peerHost) + addr := startTLSServer(serverCert) + + By("accepting a peer whose certificate is signed by spec.settings.tls.caBundle") + + trustedCmd := &commander{ + cluster: &v1.ClickHouseCluster{ + Spec: v1.ClickHouseClusterSpec{ + Settings: v1.ClickHouseSettings{ + TLS: v1.ClusterTLSSpec{ + CABundle: &v1.CABundleSelector{Name: "custom-ca", Key: "ca.crt"}, + }, + }, + }, + }, + caBundleLoader: func(context.Context) ([]byte, error) { + return caPEM, nil + }, + } + + tlsCfg, err := trustedCmd.externalPeerTLSConfig(ctx, peerHost) + Expect(err).NotTo(HaveOccurred()) + Expect(tlsCfg.InsecureSkipVerify).To(BeFalse()) + Expect(tlsCfg.MinVersion).To(Equal(uint16(tls.VersionTLS12))) + Expect(tlsCfg.ServerName).To(Equal(peerHost)) + + dialer := tls.Dialer{Config: tlsCfg} + conn, err := dialer.DialContext(ctx, "tcp", addr) + Expect(err).NotTo(HaveOccurred()) + Expect(conn.Close()).To(Succeed()) + + By("rejecting a peer when the CA bundle is not trusted") + + untrustedCmd := &commander{ + cluster: &v1.ClickHouseCluster{}, + } + + untrustedCfg, err := untrustedCmd.externalPeerTLSConfig(ctx, peerHost) + Expect(err).NotTo(HaveOccurred()) + Expect(untrustedCfg.InsecureSkipVerify).To(BeFalse()) + + untrustedDialer := tls.Dialer{Config: untrustedCfg} + _, err = untrustedDialer.DialContext(ctx, "tcp", addr) + Expect(err).To(HaveOccurred()) + + By("rejecting a peer whose certificate SAN does not match the host") + + wrongHostCfg, err := trustedCmd.externalPeerTLSConfig(ctx, "other.dc2.example.com") + Expect(err).NotTo(HaveOccurred()) + + wrongHostDialer := tls.Dialer{Config: wrongHostCfg} + _, err = wrongHostDialer.DialContext(ctx, "tcp", addr) + Expect(err).To(HaveOccurred()) + }) + + It("returns an error when CA bundle loading fails or PEM is invalid", func(ctx context.Context) { + clusterWithCA := &v1.ClickHouseCluster{ + Spec: v1.ClickHouseClusterSpec{ + Settings: v1.ClickHouseSettings{ + TLS: v1.ClusterTLSSpec{ + CABundle: &v1.CABundleSelector{Name: "custom-ca", Key: "ca.crt"}, + }, + }, + }, + } + + _, err := (&commander{cluster: clusterWithCA}).externalPeerTLSConfig(ctx, "peer.example.com") + Expect(err).To(MatchError(ContainSubstring("loader is not set"))) + + _, err = (&commander{ + cluster: clusterWithCA, + caBundleLoader: func(context.Context) ([]byte, error) { + return nil, errors.New("secret not found") + }, + }).externalPeerTLSConfig(ctx, "peer.example.com") + Expect(err).To(MatchError(ContainSubstring("secret not found"))) + + _, err = (&commander{ + cluster: clusterWithCA, + caBundleLoader: func(context.Context) ([]byte, error) { + return []byte("not-a-pem"), nil + }, + }).externalPeerTLSConfig(ctx, "peer.example.com") + Expect(err).To(MatchError(ContainSubstring("no valid PEM certificates"))) + }) +}) diff --git a/internal/controller/clickhouse/constants.go b/internal/controller/clickhouse/constants.go index 128006423..1d6c5fb07 100644 --- a/internal/controller/clickhouse/constants.go +++ b/internal/controller/clickhouse/constants.go @@ -48,6 +48,7 @@ const ( CertificateFilename = "clickhouse-server.crt" KeyFilename = "clickhouse-server.key" CustomCAFilename = "custom-ca.crt" + DefaultCABundleKey = "ca.crt" LogPath = "/var/log/clickhouse-server/" diff --git a/internal/controller/clickhouse/controller_test.go b/internal/controller/clickhouse/controller_test.go index ef1ee4a6a..4937cd6f5 100644 --- a/internal/controller/clickhouse/controller_test.go +++ b/internal/controller/clickhouse/controller_test.go @@ -971,6 +971,33 @@ var _ = When("reconciling ClickHouseCluster", Ordered, func() { By("checking the dependent was not recreated") Expect(k8serrors.IsNotFound(suite.Client.Get(ctx, stsKey, &sts))).To(BeTrue()) }) + + It("should reject mutating shardIDOffset and replicaIDOffset via CRD CEL validation", func(ctx context.Context) { + immutableCR := &v1.ClickHouseCluster{ + Name: "immutable-offset", + Namespace: "default", + Spec: v1.ClickHouseClusterSpec{ + Replicas: new(int32(1)), + Shards: new(int32(1)), + ShardIDOffset: 2, + ReplicaIDOffset: 10, + KeeperClusterRef: &v1.KeeperClusterReference{Name: keeperName}, + }, + } + Expect(suite.Client.Create(ctx, immutableCR)).To(Succeed()) + + updated := immutableCR.DeepCopy() + updated.Spec.ShardIDOffset = 3 + err := suite.Client.Update(ctx, updated) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("shardIDOffset is immutable")) + + updated = immutableCR.DeepCopy() + updated.Spec.ReplicaIDOffset = 11 + err = suite.Client.Update(ctx, updated) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("replicaIDOffset is immutable")) + }) }) var _ = Describe("keeper watch mapping", func() { diff --git a/internal/controller/clickhouse/sync.go b/internal/controller/clickhouse/sync.go index 4fb384972..9fe22b357 100644 --- a/internal/controller/clickhouse/sync.go +++ b/internal/controller/clickhouse/sync.go @@ -303,7 +303,7 @@ func (r *clickhouseReconciler) reconcileClusterSecret(ctx context.Context, log c secretExists = false } else { - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.initCommander(log) } if !r.versionProbe.Completed() { @@ -335,7 +335,7 @@ func (r *clickhouseReconciler) reconcileClusterSecret(ctx context.Context, log c } // Create or recreate commander with new credentials - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.initCommander(log) if !secretExists { log.Info("cluster secret not found, creating", "secret", r.Cluster.SecretName()) @@ -396,7 +396,7 @@ func (r *clickhouseReconciler) reconcileExternalSecret(ctx context.Context, log r.secret.Data = make(map[string][]byte) } - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.initCommander(log) if !r.versionProbe.Completed() { log.Info("version probe is not completed yet, skipping external secret validation") @@ -449,7 +449,7 @@ func (r *clickhouseReconciler) reconcileExternalSecret(ctx context.Context, log return chctrl.StepResult{}, fmt.Errorf("fill external secret %q: %w", r.Cluster.SecretName(), err) } - r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.initCommander(log) r.SetCondition(metav1.Condition{ Type: v1.ClickHouseConditionTypeExternalSecretValid, @@ -1043,3 +1043,35 @@ func (r *clickhouseReconciler) updateReplica(ctx context.Context, log ctrlutil.L return result, nil } + +func (r *clickhouseReconciler) initCommander(log ctrlutil.Logger) { + r.commander = newCommander(log, r.Cluster, &r.secret, r.Dialer, r.replicaAddress, r.connCache) + r.commander.caBundleLoader = r.loadCABundle +} + +func (r *clickhouseReconciler) loadCABundle(ctx context.Context) ([]byte, error) { + selector := r.Cluster.Spec.Settings.TLS.CABundle + if selector == nil { + return nil, nil + } + + var secret corev1.Secret + if err := r.GetClient().Get(ctx, types.NamespacedName{ + Namespace: r.Cluster.Namespace, + Name: selector.Name, + }, &secret); err != nil { + return nil, fmt.Errorf("get CA bundle secret %q: %w", selector.Name, err) + } + + key := selector.Key + if key == "" { + key = DefaultCABundleKey + } + + data, ok := secret.Data[key] + if !ok || len(data) == 0 { + return nil, fmt.Errorf("CA bundle secret %q is missing key %q", selector.Name, key) + } + + return data, nil +} diff --git a/internal/controller/clickhouse/sync_test.go b/internal/controller/clickhouse/sync_test.go index b94af7afe..80b8c2fe5 100644 --- a/internal/controller/clickhouse/sync_test.go +++ b/internal/controller/clickhouse/sync_test.go @@ -1,6 +1,7 @@ package clickhouse import ( + "context" "errors" . "github.com/onsi/ginkgo/v2" @@ -8,7 +9,10 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" chctrl "github.com/ClickHouse/clickhouse-operator/internal/controller" ctrlutil "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" ) @@ -102,3 +106,69 @@ var _ = Describe("UpdateStage", func() { Expect(replica.UpdateStage(rev)).To(Equal(chctrl.StageUpdating)) }) }) + +var _ = Describe("loadCABundle", func() { + newReconciler := func(caBundle *v1.CABundleSelector, objs ...runtime.Object) *clickhouseReconciler { + scheme := runtime.NewScheme() + Expect(corev1.AddToScheme(scheme)).To(Succeed()) + + client := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(objs...).Build() + cluster := &v1.ClickHouseCluster{ + Name: "test", + Namespace: "default", + Spec: v1.ClickHouseClusterSpec{ + Settings: v1.ClickHouseSettings{ + TLS: v1.ClusterTLSSpec{ + CABundle: caBundle, + }, + }, + }, + } + + return &clickhouseReconciler{ + Controller: &ClusterController{ + Client: client, + Scheme: scheme, + }, + Cluster: cluster, + } + } + + It("loads the CA bundle from the default key when key is omitted", func(ctx context.Context) { + secret := &corev1.Secret{ + Name: "custom-ca", Namespace: "default", + Data: map[string][]byte{DefaultCABundleKey: []byte("ca-pem-data")}, + } + r := newReconciler(&v1.CABundleSelector{Name: "custom-ca"}, secret) + + data, err := r.loadCABundle(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(data).To(Equal([]byte("ca-pem-data"))) + }) + + It("loads the CA bundle from a custom key", func(ctx context.Context) { + secret := &corev1.Secret{ + Name: "custom-ca", Namespace: "default", + Data: map[string][]byte{"root.pem": []byte("custom-pem-data")}, + } + r := newReconciler(&v1.CABundleSelector{Name: "custom-ca", Key: "root.pem"}, secret) + + data, err := r.loadCABundle(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(data).To(Equal([]byte("custom-pem-data"))) + }) + + It("returns an error when the secret or key is missing", func(ctx context.Context) { + rMissingSecret := newReconciler(&v1.CABundleSelector{Name: "missing-ca"}) + _, err := rMissingSecret.loadCABundle(ctx) + Expect(err).To(MatchError(ContainSubstring(`get CA bundle secret "missing-ca"`))) + + secret := &corev1.Secret{ + Name: "custom-ca", Namespace: "default", + Data: map[string][]byte{"other.crt": []byte("data")}, + } + rMissingKey := newReconciler(&v1.CABundleSelector{Name: "custom-ca", Key: "ca.crt"}, secret) + _, err = rMissingKey.loadCABundle(ctx) + Expect(err).To(MatchError(ContainSubstring(`missing key "ca.crt"`))) + }) +}) diff --git a/internal/controller/keeper/controller_test.go b/internal/controller/keeper/controller_test.go index a569b0af4..bf24556b9 100644 --- a/internal/controller/keeper/controller_test.go +++ b/internal/controller/keeper/controller_test.go @@ -454,6 +454,23 @@ var _ = When("reconciling standalone KeeperCluster resource", Ordered, func() { By("checking the dependent was not recreated") Expect(k8serrors.IsNotFound(suite.Client.Get(ctx, stsKey, &sts))).To(BeTrue()) }) + + It("should reject mutating replicaIDOffset via CRD CEL validation", func(ctx context.Context) { + immutableCR := &v1.KeeperCluster{ + Name: "immutable-offset", + Namespace: "default", + Spec: v1.KeeperClusterSpec{ + Replicas: new(int32(1)), + ReplicaIDOffset: 10, + }, + } + Expect(suite.Client.Create(ctx, immutableCR)).To(Succeed()) + + immutableCR.Spec.ReplicaIDOffset = 11 + err := suite.Client.Update(ctx, immutableCR) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("replicaIDOffset is immutable")) + }) }) var _ = Describe("KeeperClustersForClickHouse", func() {