diff --git a/api/v1alpha1/clickhousecluster_types.go b/api/v1alpha1/clickhousecluster_types.go index 0bf998af4..1702ab6b4 100644 --- a/api/v1alpha1/clickhousecluster_types.go +++ b/api/v1alpha1/clickhousecluster_types.go @@ -38,6 +38,7 @@ func (s *ClickHouseNetworkPolicySpec) Enabled() bool { // +kubebuilder:validation:XValidation:rule="has(self.keeperClusterRef) != has(self.externalKeeper)",message="exactly one of keeperClusterRef or externalKeeper must be set" type ClickHouseClusterSpec struct { // Number of replicas in the single shard. + // Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. // +optional // +kubebuilder:default:=3 // +kubebuilder:validation:Minimum=0 diff --git a/api/v1alpha1/conditions.go b/api/v1alpha1/conditions.go index ffdf70179..f23dfd767 100644 --- a/api/v1alpha1/conditions.go +++ b/api/v1alpha1/conditions.go @@ -58,8 +58,9 @@ const ( ConditionReasonVersionOutdated ConditionReason = "VersionOutdated" ConditionReasonUpgradeCheckFailed ConditionReason = "UpgradeCheckFailed" - // ConditionTypeReady indicates that cluster is ready to serve client requests. + // ConditionTypeReady indicates that cluster is ready to serve client requests or is fully scaled to zero. ConditionTypeReady ConditionType = "Ready" + ConditionReasonScaledToZero ConditionReason = "ScaledToZero" ClickHouseConditionAllShardsReady ConditionReason = "AllShardsReady" ClickHouseConditionSomeShardsNotReady ConditionReason = "SomeShardsNotReady" KeeperConditionReasonStandaloneReady ConditionReason = "StandaloneReady" diff --git a/api/v1alpha1/events.go b/api/v1alpha1/events.go index 959b2e0f7..b6814a23e 100644 --- a/api/v1alpha1/events.go +++ b/api/v1alpha1/events.go @@ -43,6 +43,11 @@ const ( EventReasonClickHouseWarning EventReason = "ClickHouseWarning" ) +// Event reason for a ClickHouseCluster running without Keeper nodes. +const ( + EventReasonNoKeeperNodes EventReason = "NoKeeperNodes" +) + // EventAction represents the action associated with an event. type EventAction = string diff --git a/api/v1alpha1/keepercluster_types.go b/api/v1alpha1/keepercluster_types.go index 3a1576a2e..31fa8869b 100644 --- a/api/v1alpha1/keepercluster_types.go +++ b/api/v1alpha1/keepercluster_types.go @@ -34,7 +34,8 @@ func (s *KeeperNetworkPolicySpec) Enabled() bool { // KeeperClusterSpec defines the desired state of KeeperCluster. type KeeperClusterSpec struct { - // Number of replicas in the cluster + // Number of replicas in the cluster. + // Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. // +optional // +kubebuilder:default:=3 // +kubebuilder:validation:Enum=0;1;3;5;7;9;11;13;15 diff --git a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml index 8053101cb..bab004679 100644 --- a/config/crd/bases/clickhouse.com_clickhouseclusters.yaml +++ b/config/crd/bases/clickhouse.com_clickhouseclusters.yaml @@ -3487,7 +3487,9 @@ spec: rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' replicas: default: 3 - description: Number of replicas in the single shard. + description: |- + Number of replicas in the single shard. + Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. format: int32 minimum: 0 type: integer diff --git a/config/crd/bases/clickhouse.com_keeperclusters.yaml b/config/crd/bases/clickhouse.com_keeperclusters.yaml index 03a72b21f..9bdc6dd8c 100644 --- a/config/crd/bases/clickhouse.com_keeperclusters.yaml +++ b/config/crd/bases/clickhouse.com_keeperclusters.yaml @@ -3189,7 +3189,9 @@ spec: rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' replicas: default: 3 - description: Number of replicas in the cluster + description: |- + Number of replicas in the cluster. + Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. enum: - 0 - 1 diff --git a/dist/chart-cluster/values.yaml b/dist/chart-cluster/values.yaml index c0fabbb83..d210097db 100644 --- a/dist/chart-cluster/values.yaml +++ b/dist/chart-cluster/values.yaml @@ -106,6 +106,7 @@ clickhouse: # podTemplate: {} # Number of replicas in the single shard. + # Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. replicas: 3 # Configuration parameters for ClickHouse server. @@ -171,7 +172,8 @@ keeper: # Parameters passed to the Keeper pod spec. # podTemplate: {} - # Number of replicas in the cluster + # Number of replicas in the cluster. + # Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. 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..a7f5e91b7 100644 --- a/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/clickhouseclusters.clickhouse.com.yaml @@ -3490,7 +3490,9 @@ spec: rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' replicas: default: 3 - description: Number of replicas in the single shard. + description: |- + Number of replicas in the single shard. + Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. format: int32 minimum: 0 type: integer diff --git a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml index 9b369e4da..ae42fe2eb 100644 --- a/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml +++ b/dist/chart/templates/crd/keeperclusters.clickhouse.com.yaml @@ -3192,7 +3192,9 @@ spec: rule: '!has(self.topologyMinDomains) || has(self.topologyZoneKey)' replicas: default: 3 - description: Number of replicas in the cluster + description: |- + Number of replicas in the cluster. + Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. enum: - 0 - 1 diff --git a/docs/guides/configuration.mdx b/docs/guides/configuration.mdx index e3f64e5e1..b873325a4 100644 --- a/docs/guides/configuration.mdx +++ b/docs/guides/configuration.mdx @@ -316,6 +316,8 @@ spec: | `Disabled` | The operator does **not** create PDBs and **deletes** any existing ones with matching labels. Useful for development clusters where every voluntary disruption should be allowed. | | `Ignored` | The operator neither creates nor deletes PDBs. Existing PDBs are left alone. Use this when another system (e.g. policy admission, GitOps tool) owns PDB management for you. | +With `Enabled`, the operator deletes the PDBs while the cluster is [scaled to zero](/products/kubernetes-operator/guides/scaling#scaling-to-zero), since no Pods are left to protect. + Example — disable PDB management completely on a development cluster: ```yaml @@ -982,7 +984,7 @@ Every replica Pod carries the `clickhouse.com/ReplicaInitialized` readiness gate The operator never drops a populated non-Replicated `default` database. Such a replica still starts serving client traffic after schema preparation, but the cluster reports `SchemaInSync=False` with reason `DefaultDatabaseNotReplicated` until you resolve that database yourself. -Before a replica is removed on scale-down, the operator unloads client traffic from it, replicates its remaining data to the surviving replicas, and only then deletes it. On shutdown, the replica waits up to a minute for the surviving replicas to fetch the data parts only it has. +Before a replica is removed on scale-down, the operator unloads client traffic from it, replicates its remaining data to the surviving replicas, and only then deletes it. On shutdown, the replica waits up to a minute for the surviving replicas to fetch the data parts only it has. [Scaling to zero](/products/kubernetes-operator/guides/scaling#scaling-to-zero) leaves no surviving replicas, so each replica keeps its data on its volume. ### Server logging {#server-logging} diff --git a/docs/guides/kubernetes-events.mdx b/docs/guides/kubernetes-events.mdx index 8b6e06ca3..3d2a2e193 100644 --- a/docs/guides/kubernetes-events.mdx +++ b/docs/guides/kubernetes-events.mdx @@ -78,11 +78,12 @@ apply an owned resource during reconciliation. ### Cluster readiness {#cluster-readiness} -Emitted on both kinds when the cluster crosses a readiness boundary. +Emitted on both kinds when the cluster crosses a readiness boundary. Stopping a +cluster by scaling it to zero emits no `ClusterNotReady`. | Reason | Type | Meaning | |---|---|---| -| `ClusterReady` | Normal | The cluster became ready: every ClickHouse shard has at least one ready replica, or the Keeper quorum has a leader and enough followers (or its single standalone replica is up). | +| `ClusterReady` | Normal | The cluster became ready: every ClickHouse shard has at least one ready replica, or the Keeper quorum has a leader and enough followers (or its single standalone replica is up), or the cluster is scaled to zero and no replicas are left. | | `ClusterNotReady` | Warning | The cluster left the ready state — a ClickHouse shard has no ready replica left, or the Keeper quorum lost its leader or too many followers. | ### Scaling {#scaling} @@ -115,6 +116,17 @@ the operator cannot use. See the External Secret feature in the | `ExternalSecretNotFound` | Warning | The referenced Secret does not exist in the cluster's namespace. | | `ExternalSecretInvalid` | Warning | The Secret exists but is missing required keys (only reported under the `Observe` policy). | +### Keeper availability {#keeper-availability} + +Emitted on `ClickHouseCluster` repeatedly while the cluster has replicas but its +Keeper has no nodes, for example after the `KeeperCluster` was +[scaled to zero](/products/kubernetes-operator/guides/scaling#scaling-to-zero) +before the `ClickHouseCluster`. + +| Reason | Type | Meaning | +|---|---|---| +| `NoKeeperNodes` | Warning | The Keeper has no nodes, so replicated tables are read-only until it is scaled up. | + ### Version checks {#version-checks} Emitted by the version checks for `ClickHouseCluster` and `KeeperCluster`. @@ -182,6 +194,8 @@ A few common signals and where they point: operator can use it. - **`ClickHouseWarning`** — the problem is inside ClickHouse, not the operator. Treat the message as you would a row from `system.warnings`. +- **`NoKeeperNodes`** — ClickHouse runs while its `KeeperCluster` is scaled to + zero. Scale the Keeper back up, or stop the `ClickHouseCluster` first. ## Related guides {#related-guides} diff --git a/docs/guides/scaling.mdx b/docs/guides/scaling.mdx index 947f3b2a0..370662dce 100644 --- a/docs/guides/scaling.mdx +++ b/docs/guides/scaling.mdx @@ -29,7 +29,7 @@ spec: ``` On scale up the operator creates the new per-replica StatefulSets, synchronizes the schema to the new replicas (see [Automatic schema sync](#automatic-schema-sync)), and only then lets each new pod become ready for client traffic. -On scale down it removes the surplus StatefulSets and cleans up the stale replicated-database replica registrations the removed replicas left behind. +On scale down it removes the surplus StatefulSets and cleans up the stale replicated-database replica registrations the removed replicas left behind, except when [scaling to zero](#scaling-to-zero). ## Scaling shards {#scaling-shards} @@ -44,13 +44,23 @@ spec: Each shard holds a distinct slice of the data, and the operator does not copy or move rows between shards. A `Distributed` table or an explicit routing scheme decides which shard a row lands on, so adding a shard gives new writes somewhere to land without touching the rows already stored in the existing shards. +## Scaling to zero {#scaling-to-zero} + +Set `replicas: 0` to stop a `ClickHouseCluster` or a `KeeperCluster`. The operator removes the per-replica resources, such as StatefulSets and ConfigMaps, and the PodDisruptionBudgets it manages, and keeps the PersistentVolumeClaims and the replica registrations in Keeper. Once no replica Pods are left, the cluster reports `Ready` with the `ScaledToZero` reason. Scale back to the previous replica count to resume: each replica reattaches its volume. + +Unlike a regular scale down, stopping does not replicate data between replicas: each replica keeps its own data on its volume, so resuming with fewer replicas than before leaves the data held only by the others on their volumes. Data survives only on persistent volumes: a `ClickHouseCluster` without `dataVolumeClaimSpec` loses its data, and a `KeeperCluster` without one loses the replication metadata of every `ClickHouseCluster` that uses it. + +A `KeeperCluster` stops and resumes all quorum members at once instead of one at a time, so resume it with the same replica count it had before. + +To stop ClickHouse together with its Keeper, scale the `ClickHouseCluster` to zero first, wait until it reports `ScaledToZero`, and then scale the `KeeperCluster`. Resume in the reverse order: wait until all `KeeperCluster` replicas are ready (`status.readyReplicas`) before scaling up the `ClickHouseCluster`. While a `ClickHouseCluster` runs without Keeper nodes, the operator emits the [`NoKeeperNodes`](/products/kubernetes-operator/guides/kubernetes-events#keeper-availability) warning event. + ## Automatic schema sync {#automatic-schema-sync} When `spec.settings.enableDatabaseSync` is `true` (the default), the operator keeps the schema aligned as the topology changes: - **On scale up** — the operator replicates the database definitions of the replicas already serving client traffic to the newly created replicas, so a fresh replica joins with the same `Replicated` and integration databases as the rest of the cluster. Before any replica serves traffic, for example on cluster creation, the definitions of all reachable replicas are merged. Replicas that already serve traffic are never changed, so create databases with `ON CLUSTER` to have them on every replica. While replicas that served traffic exist but none of them is reachable, new replicas wait. -- **On scale down** — once a replica is gone, the operator drops its registration from each `Replicated` database with `SYSTEM DROP DATABASE REPLICA`, so the shrunk cluster does not wait on a `Replicated` database replica that no longer exists. +- **On scale down** — once a replica is gone, the operator drops its registration from each `Replicated` database with `SYSTEM DROP DATABASE REPLICA`, so the shrunk cluster does not wait on a `Replicated` database replica that no longer exists. [Scaling to zero](#scaling-to-zero) keeps the registrations for the resume. This covers `Replicated` databases and integration database engines. It does not move table data — row data lives in `ReplicatedMergeTree` tables and replicates through Keeper independently of this schema sync. With a single replica there is nothing to replicate. @@ -75,12 +85,14 @@ kubectl get clickhousecluster sample -o yaml | sed -n '/conditions:/,/^[^ ]/p' | `SchemaInSync` | `SchemaSyncDisabled` | `enableDatabaseSync` is `false` | | `Ready` | `AllShardsReady` | Every shard has a ready replica | | `Ready` | `SomeShardsNotReady` | At least one shard has no ready replica | +| `Ready` | `ScalingDown` | The cluster is scaled to zero, but replicas are still stopping | +| `Ready` | `ScaledToZero` | The cluster is scaled to zero and no replica Pods are left | -A scale operation is complete when `ClusterSizeAligned` reports `UpToDate`, `SchemaInSync` reports `ReplicasInSync`, and `Ready` reports `AllShardsReady`. +A scale operation is complete when `ClusterSizeAligned` reports `UpToDate`, `SchemaInSync` reports `ReplicasInSync`, and `Ready` reports `AllShardsReady`, or `ScaledToZero` after scaling to zero. ## Scaling Keeper {#scaling-keeper} -A `KeeperCluster` runs a RAFT quorum, so the operator changes its membership **one replica at a time** and only while the cluster is in a stable state. This protects the quorum: a `2F+1` cluster tolerates `F` members down, so a 3-node cluster keeps working with one member missing and a 5-node cluster with two. +A `KeeperCluster` runs a RAFT quorum, so the operator changes its membership **one replica at a time** and only while the cluster is in a stable state, except when [scaling to or from zero](#scaling-to-zero). This protects the quorum: a `2F+1` cluster tolerates `F` members down, so a 3-node cluster keeps working with one member missing and a 5-node cluster with two. ```yaml spec: diff --git a/docs/reference/api-reference.mdx b/docs/reference/api-reference.mdx index 6a77691ca..3269d6a0e 100644 --- a/docs/reference/api-reference.mdx +++ b/docs/reference/api-reference.mdx @@ -74,7 +74,7 @@ ClickHouseClusterSpec defines the desired state of ClickHouseCluster. | Field | Type | Description | Required | Default | |-------|------|-------------|----------|---------| -| `replicas` | integer | Number of replicas in the single shard. | false | 3 | +| `replicas` | integer | Number of replicas in the single shard.
Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. | false | 3 | | `shards` | integer | Number of shards in the cluster. | false | 1 | | `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 | | @@ -361,7 +361,7 @@ 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 replicas in the cluster.
Set to 0 to stop the cluster: replicas are removed, their PersistentVolumeClaims are kept. | false | 3 | | `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/controller_test.go b/internal/controller/clickhouse/controller_test.go index ef1ee4a6a..8a128f5a1 100644 --- a/internal/controller/clickhouse/controller_test.go +++ b/internal/controller/clickhouse/controller_test.go @@ -920,6 +920,128 @@ var _ = When("reconciling ClickHouseCluster", Ordered, func() { Expect(updatedCR.Status.UpdateRevision).NotTo(Equal(beforeRevision)) }) + It("should be ready once scaled to zero", func(ctx context.Context) { + setKeeperReplicas := func(replicas *int32) *int32 { + keeper := v1.KeeperCluster{Name: keeperName, Namespace: "default"} + Expect(suite.Client.Get(ctx, keeper.NamespacedName(), &keeper)).To(Succeed()) + + previous := keeper.Spec.Replicas + keeper.Spec.Replicas = replicas + Expect(suite.Client.Update(ctx, &keeper)).To(Succeed()) + + return previous + } + + stoppingCR := &v1.ClickHouseCluster{ + Name: "stopping", + Namespace: "default", + Spec: v1.ClickHouseClusterSpec{ + Replicas: new(int32(1)), + Shards: new(int32(1)), + KeeperClusterRef: &v1.KeeperClusterReference{Name: keeperName}, + }, + } + Expect(suite.Client.Create(ctx, stoppingCR)).To(Succeed()) + + _, err := controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + testutil.CompleteVersionProbeJob(ctx, suite, stoppingCR.Namespace, stoppingCR.SpecificName(), "26.1.1.1") + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + testutil.AssertEvents(recorder.Events, map[string]int{ + "ClusterNotReady": 1, + }) + + listOpts := controllerutil.AppRequirements(stoppingCR.Namespace, stoppingCR.SpecificName()) + Expect(suite.Client.List(ctx, &statefulsets, listOpts)).To(Succeed()) + Expect(statefulsets.Items).To(HaveLen(1)) + Expect(suite.Client.List(ctx, &pdbs, listOpts)).To(Succeed()) + Expect(pdbs.Items).To(HaveLen(1)) + + By("warning while the Keeper has no nodes") + + keeperReplicas := setKeeperReplicas(new(int32(0))) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + testutil.AssertEvents(recorder.Events, map[string]int{ + "NoKeeperNodes": 1, + }) + + setKeeperReplicas(keeperReplicas) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + By("keeping a replica Pod that is still terminating") + + pod := &corev1.Pod{ + Name: "stopping-replica", + Namespace: stoppingCR.Namespace, + Finalizers: []string{"test.clickhouse.com/hold"}, + Labels: controllerutil.MergeMaps(v1.ClickHouseReplicaID{ShardID: 0, Index: 0}.Labels(), map[string]string{ + controllerutil.LabelAppKey: stoppingCR.SpecificName(), + }), + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "clickhouse", Image: "clickhouse"}}}, + } + Expect(suite.Client.Create(ctx, pod)).To(Succeed()) + Expect(suite.Client.Delete(ctx, pod)).To(Succeed()) + + By("scaling to zero replicas") + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + stoppingCR.Spec.Replicas = new(int32(0)) + Expect(suite.Client.Update(ctx, stoppingCR)).To(Succeed()) + + for range 2 { + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + } + + Expect(suite.Client.List(ctx, &statefulsets, listOpts)).To(Succeed()) + Expect(statefulsets.Items).To(BeEmpty()) + Expect(suite.Client.List(ctx, &pdbs, listOpts)).To(Succeed()) + Expect(pdbs.Items).To(BeEmpty()) + + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + ready := meta.FindStatusCondition(stoppingCR.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Status).To(Equal(metav1.ConditionFalse)) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScalingDown)) + + By("letting the last replica Pod terminate") + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(pod), pod)).To(Succeed()) + pod.Finalizers = nil + Expect(suite.Client.Update(ctx, pod)).To(Succeed()) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + Expect(stoppingCR.Status.CurrentRevision).To(Equal(stoppingCR.Status.UpdateRevision)) + + ready = meta.FindStatusCondition(stoppingCR.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Status).To(Equal(metav1.ConditionTrue)) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScaledToZero)) + + testutil.AssertEvents(recorder.Events, map[string]int{ + "ClusterReady": 1, + }) + + By("stopping the Keeper after ClickHouse") + setKeeperReplicas(new(int32(0))) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + testutil.EnsureNoEvents(recorder.Events) + + setKeeperReplicas(keeperReplicas) + }) + It("should not recreate resources while the cluster is being deleted", func(ctx context.Context) { By("creating a cluster to delete") diff --git a/internal/controller/clickhouse/schemasync.go b/internal/controller/clickhouse/schemasync.go index 587c30ef9..c2d918420 100644 --- a/internal/controller/clickhouse/schemasync.go +++ b/internal/controller/clickhouse/schemasync.go @@ -180,8 +180,8 @@ func (r *clickhouseReconciler) reconcilePreScaleDownSync(ctx context.Context, lo } switch { - case id.ShardID >= r.Cluster.Shards(): - // Whole shard removal drops the shard data by design, no surviving replicas to sync. + case id.ShardID >= r.Cluster.Shards() || r.Cluster.Replicas() == 0: + // Whole shard removal or scale to zero, no surviving replicas to sync. case shardHasReachableReplica[id.ShardID]: shardsToSyncSet[id.ShardID] = struct{}{} default: diff --git a/internal/controller/clickhouse/schemasync_test.go b/internal/controller/clickhouse/schemasync_test.go index 0f5b7dacf..156eb76d9 100644 --- a/internal/controller/clickhouse/schemasync_test.go +++ b/internal/controller/clickhouse/schemasync_test.go @@ -121,4 +121,14 @@ var _ = Describe("schema sync steps", func() { Expect(cond).NotTo(BeNil()) Expect(cond.Reason).To(Equal(v1.ClickHouseConditionReplicasInSync)) }) + + It("allows deleting every replica of a shard scaled to zero", func(ctx context.Context) { + r := reconciler(true, map[v1.ClickHouseReplicaID]replicaState{{ShardID: 0, Index: 0}: replica(false)}, schemaSyncResult{}) + r.Cluster.Spec.Replicas = new(int32(0)) + r.commander = &commander{} + + _, err := r.reconcilePreScaleDownSync(ctx, log) + Expect(err).NotTo(HaveOccurred()) + Expect(r.unsyncedShards).To(BeEmpty()) + }) }) diff --git a/internal/controller/clickhouse/sync.go b/internal/controller/clickhouse/sync.go index 4ac180818..041b833b0 100644 --- a/internal/controller/clickhouse/sync.go +++ b/internal/controller/clickhouse/sync.go @@ -249,7 +249,7 @@ func (r *clickhouseReconciler) reconcileService(ctx context.Context, log ctrluti func (r *clickhouseReconciler) reconcilePodDisruptionBudget(ctx context.Context, log ctrlutil.Logger) (chctrl.StepResult, error) { pdbIgnored := r.Cluster.Spec.PodDisruptionBudget.Ignored() - pdbEnabled := r.Cluster.Spec.PodDisruptionBudget.Enabled() + pdbEnabled := r.Cluster.Spec.PodDisruptionBudget.Enabled() && r.Cluster.Replicas() > 0 if pdbEnabled { for shard := range r.Cluster.Shards() { @@ -517,7 +517,7 @@ func (r *clickhouseReconciler) reconcileActiveReplicaStatus(ctx context.Context, return chctrl.StepResult{}, fmt.Errorf("list replicas ConfigMaps: %w", err) } - pods, err := r.ListReplicaResources[v1.ClickHouseReplicaID, *corev1.Pod, *corev1.PodList](ctx, log, v1.ClickHouseIDFromLabels) + pods, err := r.ListReplicaResources[v1.ClickHouseReplicaID, *corev1.Pod, *corev1.PodList](ctx, log, v1.ClickHouseIDFromLabels, chctrl.IncludeTerminating()) if err != nil { return chctrl.StepResult{}, fmt.Errorf("list replicas Pods: %w", err) } @@ -530,12 +530,17 @@ func (r *clickhouseReconciler) reconcileActiveReplicaStatus(ctx context.Context, log.Debug("load replica state done", "replica_id", id, "statefulset", sts.Name) + pod := pods[id] + if pod != nil && pod.DeletionTimestamp != nil { + pod = nil + } + r.ReplicaState[id] = replicaState{ STS: sts, CFG: configMaps[id], PVCs: pvcs, - Pod: pods[id], - StartupError: chctrl.PodStartupError(pods[id]), + Pod: pod, + StartupError: chctrl.PodStartupError(pod), } } @@ -569,7 +574,14 @@ func (r *clickhouseReconciler) reconcileActiveReplicaStatus(ctx context.Context, r.ReplicaState[id] = res.Result } - r.evaluateReplicaConditions() + replicasLeft := len(pods) + for id := range statefulSets { + if _, ok := pods[id]; !ok { + replicasLeft++ + } + } + + r.evaluateReplicaConditions(replicasLeft) return chctrl.StepContinue(), nil } @@ -650,6 +662,11 @@ func (r *clickhouseReconciler) reconcileClusterRevisions(ctx context.Context, lo } } + if r.Cluster.Replicas()*r.Cluster.Shards() > 0 && len(r.keeperNodes()) == 0 { + r.GetRecorder().Eventf(r.Cluster, nil, corev1.EventTypeWarning, v1.EventReasonNoKeeperNodes, v1.EventActionReconciling, + "KeeperCluster %s has no nodes, replicated tables are read-only until it is scaled up", r.Cluster.KeeperClusterNamespacedName()) + } + if !r.versionProbe.Completed() { log.Info("version probe is not completed yet, waiting") @@ -940,7 +957,7 @@ func (r *clickhouseReconciler) replicaAddress(id v1.ClickHouseReplicaID) (string return net.JoinHostPort(pod.Status.PodIP, strconv.FormatInt(int64(PortManagement), 10)), nil } -func (r *clickhouseReconciler) evaluateReplicaConditions() { +func (r *clickhouseReconciler) evaluateReplicaConditions(replicasLeft int) { var ( startupErrors = map[string]string{} notReadyIDs []string @@ -983,7 +1000,14 @@ func (r *clickhouseReconciler) evaluateReplicaConditions() { r.SetCondition(chctrl.ReplicaStartupCondition(startupErrors)) r.SetCondition(chctrl.ClusterSizeCondition(exists, expected)) - if r.commander == nil { + switch { + case expected == 0: + r.SetCondition(chctrl.HealthyCondition(notReadyIDs)) + + cond, events := chctrl.ScaledToZeroCondition(replicasLeft) + r.SetCondition(cond, events...) + + case r.commander == nil: r.SetCondition(metav1.Condition{ Type: v1.ConditionTypeHealthy, Status: metav1.ConditionUnknown, @@ -996,7 +1020,8 @@ func (r *clickhouseReconciler) evaluateReplicaConditions() { Reason: v1.ClickHouseConditionReasonPingImpossible, Message: "Cannot probe replicas", }) - } else { + + default: r.SetCondition(chctrl.HealthyCondition(notReadyIDs)) if len(notReadyShards) == 0 { diff --git a/internal/controller/clickhouse/sync_test.go b/internal/controller/clickhouse/sync_test.go index b94af7afe..f7489802c 100644 --- a/internal/controller/clickhouse/sync_test.go +++ b/internal/controller/clickhouse/sync_test.go @@ -1,14 +1,22 @@ package clickhouse import ( + "context" "errors" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + k8sruntime "k8s.io/apimachinery/pkg/runtime" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/events" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + 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 +110,72 @@ var _ = Describe("UpdateStage", func() { Expect(replica.UpdateStage(rev)).To(Equal(chctrl.StageUpdating)) }) }) + +var _ = Describe("reconcileActiveReplicaStatus", func() { + var ( + cc *ClusterController + r *clickhouseReconciler + log ctrlutil.Logger + id v1.ClickHouseReplicaID + sts *appsv1.StatefulSet + ) + + BeforeEach(func(ctx context.Context) { + scheme := k8sruntime.NewScheme() + Expect(clientgoscheme.AddToScheme(scheme)).To(Succeed()) + Expect(v1.AddToScheme(scheme)).To(Succeed()) + + cc = &ClusterController{ + Client: fake.NewClientBuilder().WithScheme(scheme).Build(), + Scheme: scheme, + Recorder: events.NewFakeRecorder(32), + } + cluster := &v1.ClickHouseCluster{ + Namespace: "default", + Name: "test", + Spec: v1.ClickHouseClusterSpec{Replicas: new(int32(1)), Shards: new(int32(1))}, + } + r = &clickhouseReconciler{ + Controller: cc, + statusManager: chctrl.NewStatusManager(cc, cluster), + ResourceManager: chctrl.NewResourceManager(cc, cluster), + Cluster: cluster, + ReplicaState: map[v1.ClickHouseReplicaID]replicaState{}, + } + log = ctrlutil.NewLogger(zap.NewRaw(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + id = v1.ClickHouseReplicaID{ShardID: 0, Index: 0} + sts = &appsv1.StatefulSet{ + Namespace: cluster.Namespace, + Name: cluster.StatefulSetNameByReplicaID(id), + Labels: ctrlutil.MergeMaps(id.Labels(), map[string]string{ctrlutil.LabelAppKey: cluster.SpecificName()}), + } + Expect(cc.Create(ctx, sts)).To(Succeed()) + }) + + It("should ignore a replica pod that is being deleted", func(ctx context.Context) { + pod := &corev1.Pod{Namespace: sts.Namespace, Name: sts.Name + "-0", Labels: sts.Labels, Finalizers: []string{"test/keep"}} + Expect(cc.Create(ctx, pod)).To(Succeed()) + + _, err := r.reconcileActiveReplicaStatus(ctx, log) + Expect(err).ToNot(HaveOccurred()) + Expect(r.ReplicaState[id].Pod.Name).To(Equal(pod.Name)) + + Expect(cc.Delete(ctx, pod)).To(Succeed()) + + _, err = r.reconcileActiveReplicaStatus(ctx, log) + Expect(err).ToNot(HaveOccurred()) + Expect(r.ReplicaState[id].Pod).To(BeNil()) + }) + + It("should not be ready while scaled to zero with a replica StatefulSet left", func(ctx context.Context) { + r.Cluster.Spec.Replicas = new(int32(0)) + + _, err := r.reconcileActiveReplicaStatus(ctx, log) + Expect(err).ToNot(HaveOccurred()) + + ready := meta.FindStatusCondition(r.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScalingDown)) + }) +}) diff --git a/internal/controller/keeper/controller_test.go b/internal/controller/keeper/controller_test.go index a569b0af4..3ba401f38 100644 --- a/internal/controller/keeper/controller_test.go +++ b/internal/controller/keeper/controller_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "io" + "maps" "net" "testing" "time" @@ -409,6 +410,106 @@ var _ = When("reconciling standalone KeeperCluster resource", Ordered, func() { Expect(updatedCR.Status.UpdateRevision).NotTo(Equal(beforeRevision)) }) + It("should be ready once scaled to zero", func(ctx context.Context) { + stoppingCR := &v1.KeeperCluster{ + Name: "stopping", + Namespace: "default", + Spec: v1.KeeperClusterSpec{ + Replicas: new(int32(1)), + }, + } + Expect(suite.Client.Create(ctx, stoppingCR)).To(Succeed()) + + _, err := controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + testutil.AssertEvents(recorder.Events, map[string]int{ + "ReplicaCreated": 1, + "ClusterNotReady": 1, + }) + + listOpts := controllerutil.AppRequirements(stoppingCR.Namespace, stoppingCR.SpecificName()) + Expect(suite.Client.List(ctx, &statefulsets, listOpts)).To(Succeed()) + Expect(statefulsets.Items).To(HaveLen(1)) + Expect(suite.Client.List(ctx, &pdbs, listOpts)).To(Succeed()) + Expect(pdbs.Items).To(HaveLen(1)) + + quorumKey := types.NamespacedName{Namespace: stoppingCR.Namespace, Name: stoppingCR.QuorumConfigMapName()} + + var quorumConfig corev1.ConfigMap + Expect(suite.Client.Get(ctx, quorumKey, &quorumConfig)).To(Succeed()) + lastMembership := maps.Clone(quorumConfig.Data) + + By("keeping a replica Pod that is still terminating") + + pod := &corev1.Pod{ + Name: "stopping-replica", + Namespace: stoppingCR.Namespace, + Finalizers: []string{"test.clickhouse.com/hold"}, + Labels: controllerutil.MergeMaps(v1.KeeperReplicaID(0).Labels(), map[string]string{ + controllerutil.LabelAppKey: stoppingCR.SpecificName(), + }), + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "keeper", Image: "keeper"}}}, + } + Expect(suite.Client.Create(ctx, pod)).To(Succeed()) + Expect(suite.Client.Delete(ctx, pod)).To(Succeed()) + + By("scaling to zero replicas") + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + stoppingCR.Spec.Replicas = new(int32(0)) + Expect(suite.Client.Update(ctx, stoppingCR)).To(Succeed()) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + sizeAligned := meta.FindStatusCondition(stoppingCR.Status.Conditions, v1.ConditionTypeClusterSizeAligned) + Expect(sizeAligned).NotTo(BeNil()) + Expect(sizeAligned.Status).To(Equal(metav1.ConditionFalse)) + Expect(sizeAligned.Reason).To(Equal(v1.ConditionReasonScalingDown)) + + result, err := controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + Expect(suite.Client.Get(ctx, quorumKey, &quorumConfig)).To(Succeed()) + Expect(quorumConfig.Data).To(Equal(lastMembership)) + + Expect(suite.Client.List(ctx, &statefulsets, listOpts)).To(Succeed()) + Expect(statefulsets.Items).To(BeEmpty()) + Expect(suite.Client.List(ctx, &pdbs, listOpts)).To(Succeed()) + Expect(pdbs.Items).To(BeEmpty()) + + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + ready := meta.FindStatusCondition(stoppingCR.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Status).To(Equal(metav1.ConditionFalse)) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScalingDown)) + Expect(result.RequeueAfter).To(BeNumerically("<", controller.ResyncPeriod)) + + By("letting the last replica Pod terminate") + Expect(suite.Client.Get(ctx, client.ObjectKeyFromObject(pod), pod)).To(Succeed()) + pod.Finalizers = nil + Expect(suite.Client.Update(ctx, pod)).To(Succeed()) + + _, err = controller.Reconcile(ctx, ctrl.Request{NamespacedName: stoppingCR.NamespacedName()}) + Expect(err).NotTo(HaveOccurred()) + + Expect(suite.Client.Get(ctx, stoppingCR.NamespacedName(), stoppingCR)).To(Succeed()) + Expect(stoppingCR.Status.CurrentRevision).To(Equal(stoppingCR.Status.UpdateRevision)) + + ready = meta.FindStatusCondition(stoppingCR.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Status).To(Equal(metav1.ConditionTrue)) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScaledToZero)) + + testutil.AssertEvents(recorder.Events, map[string]int{ + "HorizontalScaleStarted": 1, + "ReplicaDeleted": 1, + "HorizontalScaleCompleted": 1, + "ClusterReady": 1, + }) + }) + It("should not recreate resources while the cluster is being deleted", func(ctx context.Context) { By("creating a cluster to delete") diff --git a/internal/controller/keeper/sync.go b/internal/controller/keeper/sync.go index 4666dfd3c..3ab7a8796 100644 --- a/internal/controller/keeper/sync.go +++ b/internal/controller/keeper/sync.go @@ -213,11 +213,6 @@ func (r *keeperReconciler) reconcileClusterRevisions(_ context.Context, log ctrl } func (r *keeperReconciler) reconcileActiveReplicaStatus(ctx context.Context, log ctrlutil.Logger) (chctrl.StepResult, error) { - if r.Cluster.Replicas() == 0 { - log.Debug("keeper replicaState count is zero") - return chctrl.StepContinue(), nil - } - statefulSets, err := r.ListReplicaResources[v1.KeeperReplicaID, *appsv1.StatefulSet, *appsv1.StatefulSetList](ctx, log, v1.KeeperReplicaIDFromLabels) if err != nil { return chctrl.StepResult{}, fmt.Errorf("list StatefulSets: %w", err) @@ -228,14 +223,18 @@ func (r *keeperReconciler) reconcileActiveReplicaStatus(ctx context.Context, log return chctrl.StepResult{}, fmt.Errorf("list ConfigMaps: %w", err) } - pods, err := r.ListReplicaResources[v1.KeeperReplicaID, *corev1.Pod, *corev1.PodList](ctx, log, v1.KeeperReplicaIDFromLabels) + pods, err := r.ListReplicaResources[v1.KeeperReplicaID, *corev1.Pod, *corev1.PodList](ctx, log, v1.KeeperReplicaIDFromLabels, chctrl.IncludeTerminating()) if err != nil { return chctrl.StepResult{}, fmt.Errorf("list Pods: %w", err) } execResults := ctrlutil.ExecuteParallel(ctx, slices.Collect(maps.Keys(statefulSets)), func(ctx context.Context, id v1.KeeperReplicaID) (replicaState, error) { sts := statefulSets[id] + pod := pods[id] + if pod != nil && pod.DeletionTimestamp != nil { + pod = nil + } startupErr := chctrl.PodStartupError(pod) @@ -294,12 +293,24 @@ func (r *keeperReconciler) reconcileActiveReplicaStatus(ctx context.Context, log return chctrl.StepResult{}, err } - r.evaluateReplicaConditions() + replicasLeft := len(pods) + for id := range statefulSets { + if _, ok := pods[id]; !ok { + replicasLeft++ + } + } + + r.evaluateReplicaConditions(replicasLeft) if !r.HorizontalScaleAllowed { return chctrl.StepRequeue(chctrl.RequeueProbePoll), nil } + // Pods are not watched, poll until the last replica is gone. + if r.Cluster.Replicas() == 0 && replicasLeft > 0 { + return chctrl.StepRequeue(chctrl.RequeueProbePoll), nil + } + return chctrl.StepContinue(), nil } @@ -339,7 +350,12 @@ func (r *keeperReconciler) reconcileQuorumMembership(_ context.Context, log ctrl // Scale to zero replica count could be applied without checks. if requestedReplicas == 0 && activeReplicas > 0 { log.Debug("deleting all replicas", "replicas", slices.Collect(maps.Keys(r.ReplicaState))) - r.SetCondition(metav1.Condition{Type: v1.ConditionTypeClusterSizeAligned, Status: metav1.ConditionTrue, Reason: v1.ConditionReasonUpToDate, Message: ""}) + r.SetCondition(chctrl.ClusterSizeCondition(activeReplicas, requestedReplicas), chctrl.EventSpec{ + Type: corev1.EventTypeNormal, + Reason: v1.EventReasonHorizontalScaleStarted, + Action: v1.EventActionScaling, + Message: fmt.Sprintf("Cluster scale down is started: current replicas %d, requested %d", activeReplicas, requestedReplicas), + }) r.GetRecorder().Eventf(r.Cluster, nil, corev1.EventTypeNormal, v1.EventReasonReplicaDeleted, v1.EventActionScaling, "Cluster scaled to 0 nodes, removing all %d replicas", len(r.ReplicaState)) r.ReplicaState = map[v1.KeeperReplicaID]replicaState{} @@ -416,13 +432,13 @@ func (r *keeperReconciler) reconcileQuorumMembership(_ context.Context, log ctrl func (r *keeperReconciler) reconcilePodDisruptionBudget(ctx context.Context, log ctrlutil.Logger) (chctrl.StepResult, error) { if !r.Cluster.Spec.PodDisruptionBudget.Ignored() { pdb := templatePodDisruptionBudget(r.Cluster) - if r.Cluster.Spec.PodDisruptionBudget.Enabled() { + if r.Cluster.Spec.PodDisruptionBudget.Enabled() && r.Cluster.Replicas() > 0 { if _, err := r.ReconcilePodDisruptionBudget(ctx, log, pdb, v1.EventActionReconciling); err != nil { return chctrl.StepResult{}, fmt.Errorf("reconcile PodDisruptionBudget resource: %w", err) } } else { if err := r.Delete(ctx, pdb, v1.EventActionReconciling); err != nil { - return chctrl.StepResult{}, fmt.Errorf("delete disabled PodDisruptionBudget resource: %w", err) + return chctrl.StepResult{}, fmt.Errorf("delete PodDisruptionBudget resource: %w", err) } } } @@ -436,6 +452,11 @@ func (r *keeperReconciler) reconcileCommonResources(ctx context.Context, log ctr return chctrl.StepResult{}, fmt.Errorf("reconcile service resource: %w", err) } + // Keep the last quorum membership while scaled to zero. + if r.Cluster.Replicas() == 0 { + return chctrl.StepContinue(), nil + } + configMap, err := templateQuorumConfig(r) if err != nil { return chctrl.StepResult{}, fmt.Errorf("template quorum config: %w", err) @@ -588,7 +609,7 @@ func (r *keeperReconciler) reconcileCleanUp(ctx context.Context, log ctrlutil.Lo return chctrl.StepContinue(), nil } -func (r *keeperReconciler) evaluateReplicaConditions() { +func (r *keeperReconciler) evaluateReplicaConditions(replicasLeft int) { var ( notReadyIDs, notUpdatedIDs []string startupErrors = map[string]string{} @@ -638,6 +659,13 @@ func (r *keeperReconciler) evaluateReplicaConditions() { r.Cluster.Status.CurrentRevision = r.Cluster.Status.UpdateRevision } + if r.Cluster.Replicas() == 0 { + cond, events := chctrl.ScaledToZeroCondition(replicasLeft) + r.SetCondition(cond, events...) + + return + } + var ( status metav1.ConditionStatus reason v1.ConditionReason @@ -722,6 +750,11 @@ func (r *keeperReconciler) evaluateVersionConditions(isUpdating bool) { } } + // Keep reporting the last observed version while no replicas run. + if observedVersion == "" && r.Cluster.Replicas() == 0 { + observedVersion = r.Cluster.Status.Version + } + if observedVersion == "" { r.SetCondition(metav1.Condition{ Type: v1.ConditionTypeVersionInSync, @@ -839,8 +872,8 @@ func (r *keeperReconciler) checkHorizontalScalingAllowed(_ context.Context, _ ct leaderMode = ModeStandalone } - // Allow any scaling from 0 replicas - if activeReplicas == 0 { + // Allow any scaling from or to 0 replicas + if activeReplicas == 0 || r.Cluster.Replicas() == 0 { r.HorizontalScaleAllowed = true r.SetCondition(metav1.Condition{ Type: v1.KeeperConditionTypeScaleAllowed, diff --git a/internal/controller/keeper/sync_test.go b/internal/controller/keeper/sync_test.go index ab91e811d..284a7368f 100644 --- a/internal/controller/keeper/sync_test.go +++ b/internal/controller/keeper/sync_test.go @@ -227,6 +227,28 @@ var _ = Describe("ActiveReplicaStatus", func() { Expect(err).NotTo(HaveOccurred()) Expect(dialed).To(ConsistOf(net.JoinHostPort("10.1.2.3", strconv.Itoa(PortNative)))) }) + + It("should not be ready while scaled to zero with a replica StatefulSet left", func(ctx context.Context) { + log, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + rec.Cluster.Spec.Replicas = new(int32(0)) + + id := v1.KeeperReplicaID(0) + Expect(rec.GetClient().Create(ctx, &appsv1.StatefulSet{ + Namespace: rec.Cluster.Namespace, + Name: rec.Cluster.StatefulSetNameByReplicaID(id), + Labels: util.MergeMaps(id.Labels(), map[string]string{util.LabelAppKey: rec.Cluster.SpecificName()}), + })).To(Succeed()) + + result, err := rec.reconcileActiveReplicaStatus(ctx, log) + Expect(err).NotTo(HaveOccurred()) + Expect(result.RequeueAfter).To(BeNumerically(">", 0)) + + ready := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeReady) + Expect(ready).NotTo(BeNil()) + Expect(ready.Reason).To(Equal(v1.ConditionReasonScalingDown)) + }) }) var _ = Describe("Keeper version status", func() { @@ -239,7 +261,7 @@ var _ = Describe("Keeper version status", func() { 1: {Status: serverStatus{Version: "25.8.2.1"}}, } - rec.evaluateReplicaConditions() + rec.evaluateReplicaConditions(len(rec.ReplicaState)) Expect(rec.Cluster.Status.Version).To(Equal("25.8.2.1")) cond := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeVersionInSync) @@ -258,7 +280,7 @@ var _ = Describe("Keeper version status", func() { 1: {Status: serverStatus{Version: "25.10.2.5"}}, } - rec.evaluateReplicaConditions() + rec.evaluateReplicaConditions(len(rec.ReplicaState)) Expect(rec.Cluster.Status.Version).To(Equal("25.10.2.5")) }) @@ -272,7 +294,7 @@ var _ = Describe("Keeper version status", func() { 0: {Status: serverStatus{}}, } - rec.evaluateReplicaConditions() + rec.evaluateReplicaConditions(len(rec.ReplicaState)) Expect(rec.Cluster.Status.Version).To(Equal("25.8.2.1")) cond := meta.FindStatusCondition(rec.Cluster.Status.Conditions, v1.ConditionTypeVersionInSync) @@ -308,7 +330,7 @@ var _ = Describe("Keeper version status", func() { Eventually(updater.GetReleasesData).ShouldNot(BeNil()) - rec.evaluateReplicaConditions() + rec.evaluateReplicaConditions(len(rec.ReplicaState)) Expect(rec.Cluster.Status.Version).To(Equal("25.8.2.1")) diff --git a/internal/controller/resourcemanager.go b/internal/controller/resourcemanager.go index b2a4ecd48..416b21a40 100644 --- a/internal/controller/resourcemanager.go +++ b/internal/controller/resourcemanager.go @@ -409,13 +409,33 @@ func diffFilter(specFields []string) gcmp.Option { }, gcmp.Ignore()) } +// ListReplicaOption configures ListReplicaResources. +type ListReplicaOption func(*listReplicaOptions) + +type listReplicaOptions struct { + includeTerminating bool +} + +// IncludeTerminating makes ListReplicaResources keep the resources that are being deleted. +func IncludeTerminating() ListReplicaOption { + return func(o *listReplicaOptions) { + o.includeTerminating = true + } +} + // ListReplicaResources lists the resources for replicas and maps them to replica IDs using the provided labelToID function. // Resources without replica labels are skipped silently, resources with invalid replica labels are skipped with a warning. +// Resources that are being deleted are skipped unless IncludeTerminating is passed. func (rm *ResourceManager) ListReplicaResources[ ID comparable, Res client.Object, RList client.ObjectList, -](ctx context.Context, log util.Logger, labelToID func(map[string]string) (ID, error)) (map[ID]Res, error) { +](ctx context.Context, log util.Logger, labelToID func(map[string]string) (ID, error), opts ...ListReplicaOption) (map[ID]Res, error) { + var options listReplicaOptions + for _, opt := range opts { + opt(&options) + } + list, ok := reflect.TypeAssert[RList](reflect.New(reflect.TypeFor[RList]().Elem())) if !ok { return nil, fmt.Errorf("ListReplicaResources: unsupported RList type %T", list) @@ -436,7 +456,7 @@ func (rm *ResourceManager) ListReplicaResources[ return nil, fmt.Errorf("not compatible list item type: %s", items.Index(i).Addr().Type().Name()) } - if !item.GetDeletionTimestamp().IsZero() { + if !options.includeTerminating && !item.GetDeletionTimestamp().IsZero() { continue } diff --git a/internal/controller/statusmanager.go b/internal/controller/statusmanager.go index 6482e3ffd..61ceac338 100644 --- a/internal/controller/statusmanager.go +++ b/internal/controller/statusmanager.go @@ -10,6 +10,7 @@ import ( "unicode/utf8" gcmp "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -266,6 +267,32 @@ func ClusterSizeCondition(existing, expected int) metav1.Condition { } } +// ScaledToZeroCondition evaluates Ready of a cluster scaled to zero: ready once no replicas are left. +func ScaledToZeroCondition(replicasLeft int) (metav1.Condition, []EventSpec) { + if replicasLeft > 0 { + return metav1.Condition{ + Type: v1.ConditionTypeReady, + Status: metav1.ConditionFalse, + Reason: v1.ConditionReasonScalingDown, + Message: fmt.Sprintf("Waiting for replicas to stop: %d left", replicasLeft), + }, nil + } + + message := "Cluster is scaled to zero replicas" + + return metav1.Condition{ + Type: v1.ConditionTypeReady, + Status: metav1.ConditionTrue, + Reason: v1.ConditionReasonScaledToZero, + Message: message, + }, []EventSpec{{ + Type: corev1.EventTypeNormal, + Reason: v1.EventReasonClusterReady, + Action: v1.EventActionBecameReady, + Message: message, + }} +} + func truncateString(value string, maxLength int) string { const suffix = "..." diff --git a/internal/controllerutil/common.go b/internal/controllerutil/common.go index 326f0cf27..8bc7a87cf 100644 --- a/internal/controllerutil/common.go +++ b/internal/controllerutil/common.go @@ -137,7 +137,7 @@ func applyDefaultRecursive(sourceValue reflect.Value, defaults reflect.Value) er } if sourceValue.Kind() == reflect.Pointer { - if !sourceValue.IsNil() && !defaults.IsNil() && sourceValue.Elem().Kind() != reflect.Bool { + if !sourceValue.IsNil() && !defaults.IsNil() && sourceValue.Elem().Kind() == reflect.Struct { return applyDefaultRecursive(sourceValue.Elem(), defaults.Elem()) } } diff --git a/internal/controllerutil/common_test.go b/internal/controllerutil/common_test.go index 23138253c..36051e836 100644 --- a/internal/controllerutil/common_test.go +++ b/internal/controllerutil/common_test.go @@ -102,6 +102,17 @@ var _ = Describe("ApplyDefault", func() { Expect(ApplyDefault(&source, defaults)).To(Succeed()) Expect(*source.BoolPtr).To(BeFalse()) }) + + It("should not update pointer to zero value if it is not nil", func() { + source := SampleStruct{ + Pointer: new(0), + } + defaults := SampleStruct{ + Pointer: new(42), + } + Expect(ApplyDefault(&source, defaults)).To(Succeed()) + Expect(*source.Pointer).To(BeZero()) + }) }) var _ = Describe("UpdateResult", func() { diff --git a/test/e2e/clickhouse_e2e_test.go b/test/e2e/clickhouse_e2e_test.go index 88d0c1c6b..a82826bf5 100644 --- a/test/e2e/clickhouse_e2e_test.go +++ b/test/e2e/clickhouse_e2e_test.go @@ -19,6 +19,7 @@ import ( . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" networkingv1 "k8s.io/api/networking/v1" + policyv1 "k8s.io/api/policy/v1" storagev1 "k8s.io/api/storage/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" @@ -1097,6 +1098,63 @@ var _ = Describe("ClickHouse controller", Label("clickhouse"), func() { }) }) + It("should successfully stop and start cluster", func(ctx context.Context) { + cr := testutil.NewClickHouseCluster(ns, "stoppable"). + WithStorage(defaultStorage). + WithKeeper(keeper.Name). + WithReplicas(2). + Cluster() + checks := 0 + + By("creating cluster CR", func() { + Expect(k8sClient.Create(ctx, &cr)).To(Succeed()) + DeferCleanup(func(ctx context.Context) { + Expect(k8sClient.Delete(ctx, &cr)).To(Succeed()) + }) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 2*time.Minute) + env.ClickHouseRWChecks(ctx, &cr, &checks) + }) + + assertNothingLeft := func(app string) { + for _, list := range []client.ObjectList{&corev1.PodList{}, &policyv1.PodDisruptionBudgetList{}} { + Expect(k8sClient.List(ctx, list, client.InNamespace(ns), + client.MatchingLabels{controllerutil.LabelAppKey: app})).To(Succeed()) + Expect(meta.ExtractList(list)).To(BeEmpty()) + } + } + + By("stopping ClickHouse", func() { + Expect(k8sClient.Get(ctx, cr.NamespacedName(), &cr)).To(Succeed()) + cr.Spec.Replicas = new(int32(0)) + Expect(k8sClient.Update(ctx, &cr)).To(Succeed()) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 2*time.Minute) + assertNothingLeft(cr.SpecificName()) + }) + + By("stopping Keeper", func() { + Expect(k8sClient.Get(ctx, keeper.NamespacedName(), &keeper)).To(Succeed()) + keeper.Spec.Replicas = new(int32(0)) + Expect(k8sClient.Update(ctx, &keeper)).To(Succeed()) + env.WaitKeeperUpdatedAndReady(ctx, &keeper, 2*time.Minute) + assertNothingLeft(keeper.SpecificName()) + }) + + By("starting Keeper", func() { + Expect(k8sClient.Get(ctx, keeper.NamespacedName(), &keeper)).To(Succeed()) + keeper.Spec.Replicas = new(int32(1)) + Expect(k8sClient.Update(ctx, &keeper)).To(Succeed()) + env.WaitKeeperUpdatedAndReady(ctx, &keeper, 2*time.Minute) + }) + + By("starting ClickHouse", func() { + Expect(k8sClient.Get(ctx, cr.NamespacedName(), &cr)).To(Succeed()) + cr.Spec.Replicas = new(int32(1)) + Expect(k8sClient.Update(ctx, &cr)).To(Succeed()) + env.WaitClickHouseUpdatedAndReady(ctx, &cr, 2*time.Minute) + env.ClickHouseRWChecks(ctx, &cr, &checks) + }) + }) + It("should support named collections in Keeper with encryption", func(ctx context.Context) { cr := v1.ClickHouseCluster{ ObjectMeta: metav1.ObjectMeta{