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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
123 changes: 118 additions & 5 deletions api/v1alpha1/clickhousecluster_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ 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
Expand All @@ -50,6 +53,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"`
Comment thread
melancholictheory marked this conversation as resolved.
Resolved

// 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.
Expand Down Expand Up @@ -406,6 +436,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
Expand Down Expand Up @@ -540,11 +615,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
}
Expand All @@ -553,9 +650,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.
Expand Down
87 changes: 83 additions & 4 deletions api/v1alpha1/keepercluster_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package v1alpha1

import (
"fmt"
"iter"
"strconv"

corev1 "k8s.io/api/core/v1"
Expand Down Expand Up @@ -33,14 +34,39 @@ 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"
// +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 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"`
Comment thread
melancholictheory marked this conversation as resolved.
Resolved

// 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"`
Expand Down Expand Up @@ -139,6 +165,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.
Expand Down Expand Up @@ -324,15 +381,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))
}

Expand Down
68 changes: 68 additions & 0 deletions api/v1alpha1/types_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package v1alpha1

import (
"slices"
"testing"

. "github.com/onsi/ginkgo/v2"
Expand Down Expand Up @@ -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() {
Expand Down Expand Up @@ -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())
})
})
})
Loading