From 823a29429930c52000abb29d9a08d3d245ef9f72 Mon Sep 17 00:00:00 2001 From: Julian Early Date: Wed, 2 Dec 2026 11:24:30 -0800 Subject: [PATCH 1/5] fix: restrict informer caches to operator-managed objects The operator watched every Pod, Service, ConfigMap, Secret, Job, StatefulSet, PDB and NetworkPolicy in the cluster, so on large clusters the initial cache sync alone could exceed the manager's memory limit and OOMKill it shortly after acquiring the leader lease. - Stamp app.kubernetes.io/managed-by=clickhouse-operator on every object the operator creates directly (via ReconcileResource, replica StatefulSets, version probe Jobs and the cluster Secret). - Restrict those kinds' informers to that label. Pods and PVCs are restricted by the existing clickhouse.com/role label instead, so existing replicas don't need a pod template change (rolling restart). - Read Secrets directly from the API server, since user-supplied secrets (externalSecret or a pre-created cluster secret) are unlabeled. - At startup, label objects created by older operator versions that are controlled by a ClickHouseCluster/KeeperCluster, so they stay visible through the filtered cache. Adds the patch RBAC verb this needs. Co-Authored-By: Claude Opus 5.5 --- config/rbac/role.yaml | 19 ++- dist/chart/templates/rbac/manager-role.yaml | 19 ++- internal/app/app.go | 29 ++++ internal/app/cache.go | 176 ++++++++++++++++++++ internal/app/cache_test.go | 111 ++++++++++++ internal/controller/clickhouse/templates.go | 2 +- internal/controller/resourcemanager.go | 4 + internal/controller/testutil/suite.go | 4 +- internal/controller/versionprobe.go | 6 +- internal/controllerutil/labels.go | 8 + 10 files changed, 370 insertions(+), 8 deletions(-) create mode 100644 internal/app/cache.go create mode 100644 internal/app/cache_test.go diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 9cdf173d1..763b3ea4a 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -8,8 +8,6 @@ rules: - "" resources: - configmaps - - persistentvolumeclaims - - pods - secrets - services verbs: @@ -17,6 +15,19 @@ rules: - delete - get - list + - patch + - update + - watch +- apiGroups: + - "" + resources: + - persistentvolumeclaims + - pods + verbs: + - create + - delete + - get + - list - update - watch - apiGroups: @@ -36,6 +47,7 @@ rules: - delete - get - list + - patch - update - watch - apiGroups: @@ -53,6 +65,7 @@ rules: - delete - get - list + - patch - watch - apiGroups: - clickhouse.com @@ -99,6 +112,7 @@ rules: - delete - get - list + - patch - update - watch - apiGroups: @@ -110,5 +124,6 @@ rules: - delete - get - list + - patch - update - watch diff --git a/dist/chart/templates/rbac/manager-role.yaml b/dist/chart/templates/rbac/manager-role.yaml index 90f92fea8..4a0d20e7e 100644 --- a/dist/chart/templates/rbac/manager-role.yaml +++ b/dist/chart/templates/rbac/manager-role.yaml @@ -14,8 +14,6 @@ rules: - "" resources: - configmaps - - persistentvolumeclaims - - pods - secrets - services verbs: @@ -23,6 +21,19 @@ rules: - delete - get - list + - patch + - update + - watch +- apiGroups: + - "" + resources: + - persistentvolumeclaims + - pods + verbs: + - create + - delete + - get + - list - update - watch - apiGroups: @@ -42,6 +53,7 @@ rules: - delete - get - list + - patch - update - watch - apiGroups: @@ -59,6 +71,7 @@ rules: - delete - get - list + - patch - watch - apiGroups: - clickhouse.com @@ -105,6 +118,7 @@ rules: - delete - get - list + - patch - update - watch - apiGroups: @@ -116,5 +130,6 @@ rules: - delete - get - list + - patch - update - watch diff --git a/internal/app/app.go b/internal/app/app.go index a19e4994a..6eab3c978 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -1,6 +1,7 @@ package app import ( + "context" "crypto/tls" "errors" "fmt" @@ -12,6 +13,7 @@ import ( "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/metrics/filters" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" @@ -26,6 +28,9 @@ import ( whchv1 "github.com/ClickHouse/clickhouse-operator/internal/webhook/v1alpha1" ) +// Upper bound for labeling resources created by older operator versions at startup. +const migrationTimeout = 2 * time.Minute + // Below the deployment's terminationGracePeriodSeconds so the post-drain lease release still happens before SIGKILL. const shutdownTimeout = 8 * time.Second @@ -106,6 +111,13 @@ func New(components Components, settings Settings) (ctrl.Manager, error) { GracefulShutdownTimeout: &timeout, } + mgrOptions.Cache.ByObject = cacheByObject() + mgrOptions.Client.Cache = &client.CacheOptions{DisableFor: uncachedObjects()} + + if err := migrateManagedLabels(components, settings); err != nil { + return nil, err + } + if len(settings.WatchNamespace) > 0 { components.Logger.Info("Watching namespaces", "namespaces", settings.WatchNamespace) @@ -180,3 +192,20 @@ func New(components Components, settings Settings) (ctrl.Manager, error) { return mgr, nil } + +// migrateManagedLabels labels resources created by older operator versions using a direct, uncached client. +func migrateManagedLabels(components Components, settings Settings) error { + cli, err := client.New(components.RestConfig, client.Options{Scheme: NewScheme()}) + if err != nil { + return fmt.Errorf("create migration client: %w", err) + } + + ctx, cancel := context.WithTimeout(context.Background(), migrationTimeout) + defer cancel() + + if err := labelManagedResources(ctx, cli, settings.WatchNamespace, components.Logger); err != nil { + return fmt.Errorf("label existing managed resources: %w", err) + } + + return nil +} diff --git a/internal/app/cache.go b/internal/app/cache.go new file mode 100644 index 000000000..0815f2433 --- /dev/null +++ b/internal/app/cache.go @@ -0,0 +1,176 @@ +package app + +import ( + "context" + "fmt" + + appsv1 "k8s.io/api/apps/v1" + batchv1 "k8s.io/api/batch/v1" + corev1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + policyv1 "k8s.io/api/policy/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/selection" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +// managedKinds are the kinds the operator creates directly and labels with controllerutil.ManagedByLabels. +var managedKinds = []schema.GroupVersionKind{ + corev1.SchemeGroupVersion.WithKind("Service"), + corev1.SchemeGroupVersion.WithKind("ConfigMap"), + corev1.SchemeGroupVersion.WithKind("Secret"), + appsv1.SchemeGroupVersion.WithKind("StatefulSet"), + batchv1.SchemeGroupVersion.WithKind("Job"), + policyv1.SchemeGroupVersion.WithKind("PodDisruptionBudget"), + networkingv1.SchemeGroupVersion.WithKind("NetworkPolicy"), +} + +// managedSelector matches objects the operator created directly. +func managedSelector() labels.Selector { + return labels.SelectorFromSet(controllerutil.ManagedByLabels()) +} + +// workloadSelector matches Pods and PVCs created on the operator's behalf by StatefulSets and Jobs. +// They are selected by role rather than the managed-by label, so that existing replicas don't need +// a pod template change (and therefore a rolling restart) to stay visible to the operator. +func workloadSelector() labels.Selector { + req, err := labels.NewRequirement(controllerutil.LabelRoleKey, selection.In, []string{ + controllerutil.LabelClickHouseValue, + controllerutil.LabelKeeperValue, + controllerutil.LabelVersionProbe, + }) + if err != nil { + panic(fmt.Sprintf("make %q requirement: %s", controllerutil.LabelRoleKey, err)) + } + + return labels.NewSelector().Add(*req) +} + +// cacheByObject restricts the informers for namespaced built-in kinds to objects owned by the operator. +// Without it, the operator caches every Pod, Service, ConfigMap, Secret, etc. in the cluster, which can +// exhaust its memory limit on large clusters. +func cacheByObject() map[client.Object]cache.ByObject { + managed := cache.ByObject{Label: managedSelector()} + workload := cache.ByObject{Label: workloadSelector()} + + return map[client.Object]cache.ByObject{ + &corev1.Service{}: managed, + &corev1.ConfigMap{}: managed, + &corev1.Secret{}: managed, + &appsv1.StatefulSet{}: managed, + &batchv1.Job{}: managed, + &policyv1.PodDisruptionBudget{}: managed, + &networkingv1.NetworkPolicy{}: managed, + &corev1.Pod{}: workload, + &corev1.PersistentVolumeClaim{}: workload, + } +} + +// uncachedObjects are read directly from the API server. Secrets may be supplied by the user +// (spec.externalSecret, or a pre-created cluster secret) and therefore lack the managed-by label. +func uncachedObjects() []client.Object { + return []client.Object{&corev1.Secret{}} +} + +type clusterOwner interface { + client.Object + SpecificName() string +} + +// The startup migration patches labels onto existing operator-managed objects. +// +kubebuilder:rbac:groups="",resources=configmaps;services;secrets,verbs=patch +// +kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=patch +// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=patch +// +kubebuilder:rbac:groups=policy,resources=poddisruptionbudgets,verbs=patch +// +kubebuilder:rbac:groups=networking.k8s.io,resources=networkpolicies,verbs=patch + +// labelManagedResources adds the managed-by label to objects created by older operator versions, +// so they remain visible through the label-filtered cache. It must complete before controllers start: +// an unlabeled object would look missing, and the operator would try to recreate it. +func labelManagedResources(ctx context.Context, cli client.Client, namespaces []string, log controllerutil.Logger) error { + if len(namespaces) == 0 { + namespaces = []string{metav1.NamespaceAll} + } + + var owners []clusterOwner + + for _, ns := range namespaces { + var chList v1.ClickHouseClusterList + if err := cli.List(ctx, &chList, client.InNamespace(ns)); err != nil { + return fmt.Errorf("list ClickHouseClusters: %w", err) + } + + for i := range chList.Items { + owners = append(owners, &chList.Items[i]) + } + + var keeperList v1.KeeperClusterList + if err := cli.List(ctx, &keeperList, client.InNamespace(ns)); err != nil { + return fmt.Errorf("list KeeperClusters: %w", err) + } + + for i := range keeperList.Items { + owners = append(owners, &keeperList.Items[i]) + } + } + + // NotEquals also matches objects without the label, and objects that inherited another + // managed-by value (e.g. "Helm") from the cluster's spec.labels. + notManaged, err := labels.NewRequirement(controllerutil.LabelManagedByKey, selection.NotEquals, + []string{controllerutil.LabelManagedByValue}) + if err != nil { + return fmt.Errorf("make %q requirement: %w", controllerutil.LabelManagedByKey, err) + } + + labeled := 0 + + for _, owner := range owners { + appReq, err := labels.NewRequirement(controllerutil.LabelAppKey, selection.Equals, []string{owner.SpecificName()}) + if err != nil { + return fmt.Errorf("make %q requirement: %w", controllerutil.LabelAppKey, err) + } + + selector := labels.NewSelector().Add(*appReq, *notManaged) + + for _, gvk := range managedKinds { + // Metadata-only list: no need to pull Secret data or full StatefulSet specs into memory. + var list metav1.PartialObjectMetadataList + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + + if err := cli.List(ctx, &list, client.InNamespace(owner.GetNamespace()), + client.MatchingLabelsSelector{Selector: selector}); err != nil { + return fmt.Errorf("list %s in %s: %w", gvk.Kind, owner.GetNamespace(), err) + } + + for i := range list.Items { + obj := &list.Items[i] + if !metav1.IsControlledBy(obj, owner) { + continue + } + + obj.SetGroupVersionKind(gvk) + + patch := client.MergeFrom(obj.DeepCopy()) + obj.SetLabels(controllerutil.MergeMaps(obj.GetLabels(), controllerutil.ManagedByLabels())) + + if err := cli.Patch(ctx, obj, patch); err != nil { + return fmt.Errorf("label %s %s/%s: %w", gvk.Kind, obj.Namespace, obj.Name, err) + } + + labeled++ + } + } + } + + if labeled > 0 { + log.Info("labeled existing operator-managed resources", "count", labeled, "label", controllerutil.LabelManagedByKey) + } + + return nil +} diff --git a/internal/app/cache_test.go b/internal/app/cache_test.go new file mode 100644 index 000000000..bfb8e0cbd --- /dev/null +++ b/internal/app/cache_test.go @@ -0,0 +1,111 @@ +package app + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "go.uber.org/zap" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/types" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +var _ = Describe("Label-filtered cache", func() { + It("selects only operator-managed objects", func() { + Expect(managedSelector().Matches(labels.Set(controllerutil.ManagedByLabels()))).To(BeTrue()) + Expect(managedSelector().Matches(labels.Set{"app": "unrelated"})).To(BeFalse()) + }) + + It("selects ClickHouse, Keeper and version probe pods", func() { + for _, role := range []string{ + controllerutil.LabelClickHouseValue, + controllerutil.LabelKeeperValue, + controllerutil.LabelVersionProbe, + } { + Expect(workloadSelector().Matches(labels.Set{controllerutil.LabelRoleKey: role})).To(BeTrue(), role) + } + + Expect(workloadSelector().Matches(labels.Set{"app": "unrelated"})).To(BeFalse()) + }) + + It("restricts every watched built-in kind", func() { + byObject := cacheByObject() + for obj, cfg := range byObject { + Expect(cfg.Label).NotTo(BeNil(), "%T", obj) + Expect(cfg.Label.Empty()).To(BeFalse(), "%T", obj) + } + + Expect(byObject).To(HaveLen(len(managedKinds) + 2)) + }) +}) + +var _ = Describe("labelManagedResources", func() { + const namespace = "default" + + var ( + cli client.Client + cluster *v1.ClickHouseCluster + ) + + controlledBy := func(owner client.Object) []metav1.OwnerReference { + return []metav1.OwnerReference{{ + APIVersion: v1.GroupVersion.String(), + Kind: "ClickHouseCluster", + Name: owner.GetName(), + UID: owner.GetUID(), + Controller: new(true), + }} + } + + BeforeEach(func() { + cluster = &v1.ClickHouseCluster{ + Name: "test", Namespace: namespace, UID: "cluster-uid", + } + + appLabels := map[string]string{controllerutil.LabelAppKey: cluster.SpecificName()} + + cli = fake.NewClientBuilder().WithScheme(NewScheme()).WithObjects( + cluster, + // Created by an older operator version: must be labeled. + &corev1.ConfigMap{ + Name: "owned-cm", Namespace: namespace, Labels: appLabels, OwnerReferences: controlledBy(cluster)}, + // Inherited another managed-by value from the cluster's spec.labels: must be relabeled. + &appsv1.StatefulSet{ + Name: "owned-sts", Namespace: namespace, OwnerReferences: controlledBy(cluster), + Labels: controllerutil.MergeMaps(appLabels, map[string]string{controllerutil.LabelManagedByKey: "Helm"})}, + // Same app label but not controlled by the cluster: must be left alone. + &corev1.Secret{ + Name: "foreign-secret", Namespace: namespace, Labels: appLabels}, + ).Build() + }) + + It("labels objects controlled by a cluster and nothing else", func(ctx context.Context) { + Expect(labelManagedResources(ctx, cli, nil, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) + + var cm corev1.ConfigMap + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "owned-cm"}, &cm)).To(Succeed()) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelManagedByKey, controllerutil.LabelManagedByValue)) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelAppKey, cluster.SpecificName())) + + var sts appsv1.StatefulSet + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "owned-sts"}, &sts)).To(Succeed()) + Expect(sts.Labels).To(HaveKeyWithValue(controllerutil.LabelManagedByKey, controllerutil.LabelManagedByValue)) + + var secret corev1.Secret + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "foreign-secret"}, &secret)).To(Succeed()) + Expect(secret.Labels).NotTo(HaveKey(controllerutil.LabelManagedByKey)) + }) + + It("is idempotent", func(ctx context.Context) { + Expect(labelManagedResources(ctx, cli, []string{namespace}, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) + Expect(labelManagedResources(ctx, cli, []string{namespace}, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) + }) +}) diff --git a/internal/controller/clickhouse/templates.go b/internal/controller/clickhouse/templates.go index fddec93d3..663bd6d00 100644 --- a/internal/controller/clickhouse/templates.go +++ b/internal/controller/clickhouse/templates.go @@ -132,7 +132,7 @@ func templateClusterSecrets(cr *v1.ClickHouseCluster, existing corev1.Secret) (c secret.Name = cr.SecretName() secret.Namespace = cr.Namespace - secret.Labels = controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ + secret.Labels = controllerutil.MergeMaps(cr.Spec.Labels, controllerutil.ManagedByLabels(), map[string]string{ controllerutil.LabelAppKey: cr.SpecificName(), controllerutil.LabelClusterKey: cr.Name, }) diff --git a/internal/controller/resourcemanager.go b/internal/controller/resourcemanager.go index b2a4ecd48..496d8cc53 100644 --- a/internal/controller/resourcemanager.go +++ b/internal/controller/resourcemanager.go @@ -62,6 +62,8 @@ func (rm *ResourceManager) ReconcileResource( kind := resource.GetObjectKind().GroupVersionKind().Kind log = log.With("kind", kind, "resource", resource.GetName()) + resource.SetLabels(util.MergeMaps(resource.GetLabels(), util.ManagedByLabels())) + if err := ctrlruntime.SetControllerReference(rm.owner, resource, rm.ctrl.GetScheme()); err != nil { return false, fmt.Errorf("set %s/%s Ctrl reference: %w", kind, resource.GetName(), err) } @@ -298,6 +300,8 @@ func (rm *ResourceManager) ReconcileReplicaResources( } statefulSet := input.Desired.STS + // Only the StatefulSet object itself is labeled: changing the pod template would roll every replica. + statefulSet.Labels = util.MergeMaps(statefulSet.Labels, util.ManagedByLabels()) if err = ctrlruntime.SetControllerReference(rm.owner, statefulSet, rm.ctrl.GetScheme()); err != nil { return nil, fmt.Errorf("set replica StatefulSet controller reference: %w", err) diff --git a/internal/controller/testutil/suite.go b/internal/controller/testutil/suite.go index 1e826ee6c..07ce13c44 100644 --- a/internal/controller/testutil/suite.go +++ b/internal/controller/testutil/suite.go @@ -196,10 +196,10 @@ func CompleteVersionProbeJob(ctx context.Context, suite TestSuit, namespace, spe pod := &corev1.Pod{ Name: fmt.Sprintf("%s-%s-pod", job.Name, job.UID[:8]), Namespace: namespace, - Labels: map[string]string{ + Labels: controllerutil.MergeMaps(job.Spec.Template.Labels, map[string]string{ batchv1.ControllerUidLabel: string(job.UID), batchv1.JobNameLabel: job.Name, - }, + }), Spec: corev1.PodSpec{ Containers: []corev1.Container{{ Name: v1.VersionProbeContainerName, diff --git a/internal/controller/versionprobe.go b/internal/controller/versionprobe.go index 96d72a6e2..d18b0228a 100644 --- a/internal/controller/versionprobe.go +++ b/internal/controller/versionprobe.go @@ -371,11 +371,15 @@ func (rm *ResourceManager) buildVersionProbeJob(cfg VersionProbeConfig, revision job.Name = rm.owner.SpecificResourceName("version-probe-" + revision[:8]) // Set reserved labels after overrides to ensure they are not modified by user overrides. - job.Labels = controllerutil.MergeMaps(job.Labels, map[string]string{ + job.Labels = controllerutil.MergeMaps(job.Labels, controllerutil.ManagedByLabels(), map[string]string{ controllerutil.LabelAppKey: rm.owner.SpecificName(), controllerutil.LabelClusterKey: rm.owner.GetName(), controllerutil.LabelRoleKey: controllerutil.LabelVersionProbe, }) + // The operator's Pod cache only holds pods with a known role, so the probe pod must carry one. + job.Spec.Template.Labels = controllerutil.MergeMaps(job.Spec.Template.Labels, map[string]string{ + controllerutil.LabelRoleKey: controllerutil.LabelVersionProbe, + }) specHash, err := controllerutil.DeepHashObject(job.Spec) if err != nil { diff --git a/internal/controllerutil/labels.go b/internal/controllerutil/labels.go index 623dbdfe6..3e43f6941 100644 --- a/internal/controllerutil/labels.go +++ b/internal/controllerutil/labels.go @@ -13,6 +13,7 @@ const ( LabelAppKey = "app" LabelAppK8sKey = "app.kubernetes.io/name" LabelInstanceK8sKey = "app.kubernetes.io/instance" + LabelManagedByKey = "app.kubernetes.io/managed-by" LabelRoleKey = "clickhouse.com/role" LabelClusterKey = "clickhouse.com/cluster" @@ -28,8 +29,15 @@ const ( LabelClickHouseValue = "clickhouse-server" LabelVersionProbe = "version-probe" LabelOperatorValue = "operator" + LabelManagedByValue = "clickhouse-operator" ) +// ManagedByLabels returns the label set stamped on every object the operator creates directly. +// The operator's informer caches are restricted to objects carrying it. +func ManagedByLabels() map[string]string { + return map[string]string{LabelManagedByKey: LabelManagedByValue} +} + // DiskLabel returns the label set identifying a disk's volumeClaimTemplate/PVC by name. func DiskLabel(name string) map[string]string { return map[string]string{LabelDiskName: name} From bcda37a1b3f0231a374d3555fbd665bf6a24f71b Mon Sep 17 00:00:00 2001 From: Julian Early Date: Wed, 2 Dec 2026 11:49:53 -0800 Subject: [PATCH 2/5] fix: filter caches on existing labels instead of a new managed-by label Replace the app.kubernetes.io/managed-by label with selectors on labels the operator already sets: - Service, ConfigMap, Secret, PDB, NetworkPolicy: clickhouse.com/cluster exists - StatefulSet, PVC: clickhouse.com/role in (clickhouse-server, clickhouse-keeper) - Job: clickhouse.com/role=version-probe - Pod: clickhouse.com/role in (clickhouse-server, clickhouse-keeper, version-probe) KeeperCluster's Service, PDB, NetworkPolicy and ConfigMaps were the only operator objects without clickhouse.com/cluster; they now carry it. The startup migration is reduced to adding it to those objects when they were created by an older version, using update (no new RBAC verbs). Co-Authored-By: Claude Opus 5.5 --- config/rbac/role.yaml | 19 +- dist/chart/templates/rbac/manager-role.yaml | 19 +- internal/app/app.go | 10 +- internal/app/cache.go | 201 +++++++++----------- internal/app/cache_test.go | 90 ++++----- internal/controller/clickhouse/templates.go | 2 +- internal/controller/keeper/templates.go | 22 ++- internal/controller/resourcemanager.go | 4 - internal/controller/versionprobe.go | 2 +- internal/controllerutil/labels.go | 8 - 10 files changed, 161 insertions(+), 216 deletions(-) diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 763b3ea4a..9cdf173d1 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -8,21 +8,10 @@ rules: - "" resources: - configmaps - - secrets - - services - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - persistentvolumeclaims - pods + - secrets + - services verbs: - create - delete @@ -47,7 +36,6 @@ rules: - delete - get - list - - patch - update - watch - apiGroups: @@ -65,7 +53,6 @@ rules: - delete - get - list - - patch - watch - apiGroups: - clickhouse.com @@ -112,7 +99,6 @@ rules: - delete - get - list - - patch - update - watch - apiGroups: @@ -124,6 +110,5 @@ rules: - delete - get - list - - patch - update - watch diff --git a/dist/chart/templates/rbac/manager-role.yaml b/dist/chart/templates/rbac/manager-role.yaml index 4a0d20e7e..90f92fea8 100644 --- a/dist/chart/templates/rbac/manager-role.yaml +++ b/dist/chart/templates/rbac/manager-role.yaml @@ -14,21 +14,10 @@ rules: - "" resources: - configmaps - - secrets - - services - verbs: - - create - - delete - - get - - list - - patch - - update - - watch -- apiGroups: - - "" - resources: - persistentvolumeclaims - pods + - secrets + - services verbs: - create - delete @@ -53,7 +42,6 @@ rules: - delete - get - list - - patch - update - watch - apiGroups: @@ -71,7 +59,6 @@ rules: - delete - get - list - - patch - watch - apiGroups: - clickhouse.com @@ -118,7 +105,6 @@ rules: - delete - get - list - - patch - update - watch - apiGroups: @@ -130,6 +116,5 @@ rules: - delete - get - list - - patch - update - watch diff --git a/internal/app/app.go b/internal/app/app.go index 6eab3c978..d51adcf9b 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -114,7 +114,7 @@ func New(components Components, settings Settings) (ctrl.Manager, error) { mgrOptions.Cache.ByObject = cacheByObject() mgrOptions.Client.Cache = &client.CacheOptions{DisableFor: uncachedObjects()} - if err := migrateManagedLabels(components, settings); err != nil { + if err := migrateLegacyLabels(components, settings); err != nil { return nil, err } @@ -193,8 +193,8 @@ func New(components Components, settings Settings) (ctrl.Manager, error) { return mgr, nil } -// migrateManagedLabels labels resources created by older operator versions using a direct, uncached client. -func migrateManagedLabels(components Components, settings Settings) error { +// migrateLegacyLabels labels resources created by older operator versions using a direct, uncached client. +func migrateLegacyLabels(components Components, settings Settings) error { cli, err := client.New(components.RestConfig, client.Options{Scheme: NewScheme()}) if err != nil { return fmt.Errorf("create migration client: %w", err) @@ -203,8 +203,8 @@ func migrateManagedLabels(components Components, settings Settings) error { ctx, cancel := context.WithTimeout(context.Background(), migrationTimeout) defer cancel() - if err := labelManagedResources(ctx, cli, settings.WatchNamespace, components.Logger); err != nil { - return fmt.Errorf("label existing managed resources: %w", err) + if err := labelLegacyKeeperResources(ctx, cli, settings.WatchNamespace, components.Logger); err != nil { + return fmt.Errorf("label existing KeeperCluster resources: %w", err) } return nil diff --git a/internal/app/cache.go b/internal/app/cache.go index 0815f2433..e257f7a2a 100644 --- a/internal/app/cache.go +++ b/internal/app/cache.go @@ -10,9 +10,11 @@ import ( networkingv1 "k8s.io/api/networking/v1" policyv1 "k8s.io/api/policy/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/selection" + "k8s.io/client-go/util/retry" "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" @@ -20,157 +22,142 @@ import ( "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" ) -// managedKinds are the kinds the operator creates directly and labels with controllerutil.ManagedByLabels. -var managedKinds = []schema.GroupVersionKind{ - corev1.SchemeGroupVersion.WithKind("Service"), - corev1.SchemeGroupVersion.WithKind("ConfigMap"), - corev1.SchemeGroupVersion.WithKind("Secret"), - appsv1.SchemeGroupVersion.WithKind("StatefulSet"), - batchv1.SchemeGroupVersion.WithKind("Job"), - policyv1.SchemeGroupVersion.WithKind("PodDisruptionBudget"), - networkingv1.SchemeGroupVersion.WithKind("NetworkPolicy"), -} +func mustRequirement(key string, op selection.Operator, values ...string) labels.Requirement { + req, err := labels.NewRequirement(key, op, values) + if err != nil { + panic(fmt.Sprintf("make %q requirement: %s", key, err)) + } -// managedSelector matches objects the operator created directly. -func managedSelector() labels.Selector { - return labels.SelectorFromSet(controllerutil.ManagedByLabels()) + return *req } -// workloadSelector matches Pods and PVCs created on the operator's behalf by StatefulSets and Jobs. -// They are selected by role rather than the managed-by label, so that existing replicas don't need -// a pod template change (and therefore a rolling restart) to stay visible to the operator. -func workloadSelector() labels.Selector { - req, err := labels.NewRequirement(controllerutil.LabelRoleKey, selection.In, []string{ - controllerutil.LabelClickHouseValue, - controllerutil.LabelKeeperValue, - controllerutil.LabelVersionProbe, - }) - if err != nil { - panic(fmt.Sprintf("make %q requirement: %s", controllerutil.LabelRoleKey, err)) - } +// clusterSelector matches objects labeled with the cluster they belong to. Every Service, ConfigMap, +// Secret, PodDisruptionBudget and NetworkPolicy the operator creates carries this label. +func clusterSelector() labels.Selector { + return labels.NewSelector().Add(mustRequirement(controllerutil.LabelClusterKey, selection.Exists)) +} - return labels.NewSelector().Add(*req) +// roleSelector matches objects with one of the given operator roles. +func roleSelector(roles ...string) labels.Selector { + return labels.NewSelector().Add(mustRequirement(controllerutil.LabelRoleKey, selection.In, roles...)) } -// cacheByObject restricts the informers for namespaced built-in kinds to objects owned by the operator. -// Without it, the operator caches every Pod, Service, ConfigMap, Secret, etc. in the cluster, which can -// exhaust its memory limit on large clusters. +// cacheByObject restricts the informers for namespaced built-in kinds to objects the operator manages, +// using labels the operator already sets on them. Without it, the operator caches every Pod, Service, +// ConfigMap, Secret, etc. in the cluster, which can exhaust its memory limit on large clusters. func cacheByObject() map[client.Object]cache.ByObject { - managed := cache.ByObject{Label: managedSelector()} - workload := cache.ByObject{Label: workloadSelector()} + byCluster := cache.ByObject{Label: clusterSelector()} + replicas := roleSelector(controllerutil.LabelClickHouseValue, controllerutil.LabelKeeperValue) return map[client.Object]cache.ByObject{ - &corev1.Service{}: managed, - &corev1.ConfigMap{}: managed, - &corev1.Secret{}: managed, - &appsv1.StatefulSet{}: managed, - &batchv1.Job{}: managed, - &policyv1.PodDisruptionBudget{}: managed, - &networkingv1.NetworkPolicy{}: managed, - &corev1.Pod{}: workload, - &corev1.PersistentVolumeClaim{}: workload, + &corev1.Service{}: byCluster, + &corev1.ConfigMap{}: byCluster, + &corev1.Secret{}: byCluster, + &policyv1.PodDisruptionBudget{}: byCluster, + &networkingv1.NetworkPolicy{}: byCluster, + &appsv1.StatefulSet{}: {Label: replicas}, + &corev1.PersistentVolumeClaim{}: {Label: replicas}, + &batchv1.Job{}: {Label: roleSelector(controllerutil.LabelVersionProbe)}, + &corev1.Pod{}: {Label: roleSelector( + controllerutil.LabelClickHouseValue, + controllerutil.LabelKeeperValue, + controllerutil.LabelVersionProbe, + )}, } } // uncachedObjects are read directly from the API server. Secrets may be supplied by the user -// (spec.externalSecret, or a pre-created cluster secret) and therefore lack the managed-by label. +// (spec.externalSecret, or a pre-created cluster secret) and therefore lack the cluster label. func uncachedObjects() []client.Object { return []client.Object{&corev1.Secret{}} } -type clusterOwner interface { - client.Object - SpecificName() string +// legacyKeeperKinds are the KeeperCluster-owned kinds that older operator versions created +// without the cluster label. +var legacyKeeperKinds = []schema.GroupVersionKind{ + corev1.SchemeGroupVersion.WithKind("Service"), + corev1.SchemeGroupVersion.WithKind("ConfigMap"), + policyv1.SchemeGroupVersion.WithKind("PodDisruptionBudget"), + networkingv1.SchemeGroupVersion.WithKind("NetworkPolicy"), } -// The startup migration patches labels onto existing operator-managed objects. -// +kubebuilder:rbac:groups="",resources=configmaps;services;secrets,verbs=patch -// +kubebuilder:rbac:groups=apps,resources=statefulsets,verbs=patch -// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=patch -// +kubebuilder:rbac:groups=policy,resources=poddisruptionbudgets,verbs=patch -// +kubebuilder:rbac:groups=networking.k8s.io,resources=networkpolicies,verbs=patch - -// labelManagedResources adds the managed-by label to objects created by older operator versions, -// so they remain visible through the label-filtered cache. It must complete before controllers start: -// an unlabeled object would look missing, and the operator would try to recreate it. -func labelManagedResources(ctx context.Context, cli client.Client, namespaces []string, log controllerutil.Logger) error { +// labelLegacyKeeperResources adds the cluster label to KeeperCluster-owned objects created by older +// operator versions, so they remain visible through the label-filtered cache. It must complete before +// controllers start: an unlabeled object would look missing, and the operator would try to recreate it +// (or, for the quorum ConfigMap, read an empty quorum). +func labelLegacyKeeperResources(ctx context.Context, cli client.Client, namespaces []string, log controllerutil.Logger) error { if len(namespaces) == 0 { namespaces = []string{metav1.NamespaceAll} } - var owners []clusterOwner + labeled := 0 for _, ns := range namespaces { - var chList v1.ClickHouseClusterList - if err := cli.List(ctx, &chList, client.InNamespace(ns)); err != nil { - return fmt.Errorf("list ClickHouseClusters: %w", err) - } - - for i := range chList.Items { - owners = append(owners, &chList.Items[i]) - } - - var keeperList v1.KeeperClusterList - if err := cli.List(ctx, &keeperList, client.InNamespace(ns)); err != nil { + var keepers v1.KeeperClusterList + if err := cli.List(ctx, &keepers, client.InNamespace(ns)); err != nil { return fmt.Errorf("list KeeperClusters: %w", err) } - for i := range keeperList.Items { - owners = append(owners, &keeperList.Items[i]) + for i := range keepers.Items { + count, err := labelKeeperResources(ctx, cli, &keepers.Items[i]) + if err != nil { + return err + } + + labeled += count } } - // NotEquals also matches objects without the label, and objects that inherited another - // managed-by value (e.g. "Helm") from the cluster's spec.labels. - notManaged, err := labels.NewRequirement(controllerutil.LabelManagedByKey, selection.NotEquals, - []string{controllerutil.LabelManagedByValue}) - if err != nil { - return fmt.Errorf("make %q requirement: %w", controllerutil.LabelManagedByKey, err) + if labeled > 0 { + log.Info("labeled existing KeeperCluster resources", "count", labeled, "label", controllerutil.LabelClusterKey) } - labeled := 0 - - for _, owner := range owners { - appReq, err := labels.NewRequirement(controllerutil.LabelAppKey, selection.Equals, []string{owner.SpecificName()}) - if err != nil { - return fmt.Errorf("make %q requirement: %w", controllerutil.LabelAppKey, err) - } + return nil +} - selector := labels.NewSelector().Add(*appReq, *notManaged) +func labelKeeperResources(ctx context.Context, cli client.Client, keeper *v1.KeeperCluster) (int, error) { + selector := labels.NewSelector().Add( + mustRequirement(controllerutil.LabelAppKey, selection.Equals, keeper.SpecificName()), + mustRequirement(controllerutil.LabelClusterKey, selection.DoesNotExist), + ) - for _, gvk := range managedKinds { - // Metadata-only list: no need to pull Secret data or full StatefulSet specs into memory. - var list metav1.PartialObjectMetadataList - list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + labeled := 0 - if err := cli.List(ctx, &list, client.InNamespace(owner.GetNamespace()), - client.MatchingLabelsSelector{Selector: selector}); err != nil { - return fmt.Errorf("list %s in %s: %w", gvk.Kind, owner.GetNamespace(), err) - } + for _, gvk := range legacyKeeperKinds { + var list unstructured.UnstructuredList + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) - for i := range list.Items { - obj := &list.Items[i] - if !metav1.IsControlledBy(obj, owner) { - continue - } + if err := cli.List(ctx, &list, client.InNamespace(keeper.Namespace), + client.MatchingLabelsSelector{Selector: selector}); err != nil { + return 0, fmt.Errorf("list %s in %s: %w", gvk.Kind, keeper.Namespace, err) + } - obj.SetGroupVersionKind(gvk) + for i := range list.Items { + obj := &list.Items[i] + if !metav1.IsControlledBy(obj, keeper) { + continue + } - patch := client.MergeFrom(obj.DeepCopy()) - obj.SetLabels(controllerutil.MergeMaps(obj.GetLabels(), controllerutil.ManagedByLabels())) + obj.SetGroupVersionKind(gvk) - if err := cli.Patch(ctx, obj, patch); err != nil { - return fmt.Errorf("label %s %s/%s: %w", gvk.Kind, obj.Namespace, obj.Name, err) + err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { + if err := cli.Get(ctx, client.ObjectKeyFromObject(obj), obj); err != nil { + return err //nolint:wrapcheck // wrapped below } - labeled++ + obj.SetLabels(controllerutil.MergeMaps(obj.GetLabels(), map[string]string{ + controllerutil.LabelClusterKey: keeper.Name, + })) + + return cli.Update(ctx, obj) + }) + if err != nil { + return 0, fmt.Errorf("label %s %s/%s: %w", gvk.Kind, obj.GetNamespace(), obj.GetName(), err) } - } - } - if labeled > 0 { - log.Info("labeled existing operator-managed resources", "count", labeled, "label", controllerutil.LabelManagedByKey) + labeled++ + } } - return nil + return labeled, nil } diff --git a/internal/app/cache_test.go b/internal/app/cache_test.go index bfb8e0cbd..9a049c0fd 100644 --- a/internal/app/cache_test.go +++ b/internal/app/cache_test.go @@ -6,8 +6,8 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "go.uber.org/zap" - appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" + policyv1 "k8s.io/api/policy/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" @@ -19,46 +19,40 @@ import ( ) var _ = Describe("Label-filtered cache", func() { - It("selects only operator-managed objects", func() { - Expect(managedSelector().Matches(labels.Set(controllerutil.ManagedByLabels()))).To(BeTrue()) - Expect(managedSelector().Matches(labels.Set{"app": "unrelated"})).To(BeFalse()) + It("selects objects labeled with a cluster", func() { + Expect(clusterSelector().Matches(labels.Set{controllerutil.LabelClusterKey: "any"})).To(BeTrue()) + Expect(clusterSelector().Matches(labels.Set{controllerutil.LabelAppKey: "unrelated"})).To(BeFalse()) }) - It("selects ClickHouse, Keeper and version probe pods", func() { - for _, role := range []string{ - controllerutil.LabelClickHouseValue, - controllerutil.LabelKeeperValue, - controllerutil.LabelVersionProbe, - } { - Expect(workloadSelector().Matches(labels.Set{controllerutil.LabelRoleKey: role})).To(BeTrue(), role) - } - - Expect(workloadSelector().Matches(labels.Set{"app": "unrelated"})).To(BeFalse()) + It("selects objects by operator role", func() { + selector := roleSelector(controllerutil.LabelClickHouseValue, controllerutil.LabelKeeperValue) + Expect(selector.Matches(labels.Set{controllerutil.LabelRoleKey: controllerutil.LabelClickHouseValue})).To(BeTrue()) + Expect(selector.Matches(labels.Set{controllerutil.LabelRoleKey: controllerutil.LabelKeeperValue})).To(BeTrue()) + Expect(selector.Matches(labels.Set{controllerutil.LabelRoleKey: controllerutil.LabelVersionProbe})).To(BeFalse()) + Expect(selector.Matches(labels.Set{controllerutil.LabelAppKey: "unrelated"})).To(BeFalse()) }) It("restricts every watched built-in kind", func() { - byObject := cacheByObject() - for obj, cfg := range byObject { + for obj, cfg := range cacheByObject() { Expect(cfg.Label).NotTo(BeNil(), "%T", obj) Expect(cfg.Label.Empty()).To(BeFalse(), "%T", obj) } - - Expect(byObject).To(HaveLen(len(managedKinds) + 2)) }) }) -var _ = Describe("labelManagedResources", func() { +var _ = Describe("labelLegacyKeeperResources", func() { const namespace = "default" var ( - cli client.Client - cluster *v1.ClickHouseCluster + cli client.Client + keeper *v1.KeeperCluster + logger controllerutil.Logger ) controlledBy := func(owner client.Object) []metav1.OwnerReference { return []metav1.OwnerReference{{ APIVersion: v1.GroupVersion.String(), - Kind: "ClickHouseCluster", + Kind: "KeeperCluster", Name: owner.GetName(), UID: owner.GetUID(), Controller: new(true), @@ -66,46 +60,46 @@ var _ = Describe("labelManagedResources", func() { } BeforeEach(func() { - cluster = &v1.ClickHouseCluster{ - Name: "test", Namespace: namespace, UID: "cluster-uid", + logger = controllerutil.NewLogger(zap.NewNop()) + keeper = &v1.KeeperCluster{ + Name: "test", Namespace: namespace, UID: "keeper-uid", } - appLabels := map[string]string{controllerutil.LabelAppKey: cluster.SpecificName()} + appLabels := map[string]string{controllerutil.LabelAppKey: keeper.SpecificName()} cli = fake.NewClientBuilder().WithScheme(NewScheme()).WithObjects( - cluster, + keeper, // Created by an older operator version: must be labeled. &corev1.ConfigMap{ - Name: "owned-cm", Namespace: namespace, Labels: appLabels, OwnerReferences: controlledBy(cluster)}, - // Inherited another managed-by value from the cluster's spec.labels: must be relabeled. - &appsv1.StatefulSet{ - Name: "owned-sts", Namespace: namespace, OwnerReferences: controlledBy(cluster), - Labels: controllerutil.MergeMaps(appLabels, map[string]string{controllerutil.LabelManagedByKey: "Helm"})}, + Name: "quorum", Namespace: namespace, Labels: appLabels, OwnerReferences: controlledBy(keeper)}, + &policyv1.PodDisruptionBudget{ + Name: "pdb", Namespace: namespace, Labels: appLabels, OwnerReferences: controlledBy(keeper)}, // Same app label but not controlled by the cluster: must be left alone. - &corev1.Secret{ - Name: "foreign-secret", Namespace: namespace, Labels: appLabels}, + &corev1.Service{ + Name: "foreign", Namespace: namespace, Labels: appLabels}, ).Build() }) - It("labels objects controlled by a cluster and nothing else", func(ctx context.Context) { - Expect(labelManagedResources(ctx, cli, nil, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) + It("labels objects controlled by a KeeperCluster and nothing else", func(ctx context.Context) { + Expect(labelLegacyKeeperResources(ctx, cli, nil, logger)).To(Succeed()) var cm corev1.ConfigMap - Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "owned-cm"}, &cm)).To(Succeed()) - Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelManagedByKey, controllerutil.LabelManagedByValue)) - Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelAppKey, cluster.SpecificName())) - - var sts appsv1.StatefulSet - Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "owned-sts"}, &sts)).To(Succeed()) - Expect(sts.Labels).To(HaveKeyWithValue(controllerutil.LabelManagedByKey, controllerutil.LabelManagedByValue)) - - var secret corev1.Secret - Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "foreign-secret"}, &secret)).To(Succeed()) - Expect(secret.Labels).NotTo(HaveKey(controllerutil.LabelManagedByKey)) + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "quorum"}, &cm)).To(Succeed()) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, keeper.Name)) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelAppKey, keeper.SpecificName())) + Expect(clusterSelector().Matches(labels.Set(cm.Labels))).To(BeTrue()) + + var pdb policyv1.PodDisruptionBudget + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "pdb"}, &pdb)).To(Succeed()) + Expect(pdb.Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, keeper.Name)) + + var svc corev1.Service + Expect(cli.Get(ctx, types.NamespacedName{Namespace: namespace, Name: "foreign"}, &svc)).To(Succeed()) + Expect(svc.Labels).NotTo(HaveKey(controllerutil.LabelClusterKey)) }) It("is idempotent", func(ctx context.Context) { - Expect(labelManagedResources(ctx, cli, []string{namespace}, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) - Expect(labelManagedResources(ctx, cli, []string{namespace}, controllerutil.NewLogger(zap.NewNop()))).To(Succeed()) + Expect(labelLegacyKeeperResources(ctx, cli, []string{namespace}, logger)).To(Succeed()) + Expect(labelLegacyKeeperResources(ctx, cli, []string{namespace}, logger)).To(Succeed()) }) }) diff --git a/internal/controller/clickhouse/templates.go b/internal/controller/clickhouse/templates.go index 663bd6d00..fddec93d3 100644 --- a/internal/controller/clickhouse/templates.go +++ b/internal/controller/clickhouse/templates.go @@ -132,7 +132,7 @@ func templateClusterSecrets(cr *v1.ClickHouseCluster, existing corev1.Secret) (c secret.Name = cr.SecretName() secret.Namespace = cr.Namespace - secret.Labels = controllerutil.MergeMaps(cr.Spec.Labels, controllerutil.ManagedByLabels(), map[string]string{ + secret.Labels = controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ controllerutil.LabelAppKey: cr.SpecificName(), controllerutil.LabelClusterKey: cr.Name, }) diff --git a/internal/controller/keeper/templates.go b/internal/controller/keeper/templates.go index 9f59b6c5f..f39fcdabd 100644 --- a/internal/controller/keeper/templates.go +++ b/internal/controller/keeper/templates.go @@ -66,7 +66,8 @@ func templateHeadlessService(cr *v1.KeeperCluster) *corev1.Service { Name: cr.HeadlessServiceName(), Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: cr.SpecificName(), + controllerutil.LabelAppKey: cr.SpecificName(), + controllerutil.LabelClusterKey: cr.Name, }), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: corev1.ServiceSpec{ @@ -96,7 +97,8 @@ func templatePodDisruptionBudget(cr *v1.KeeperCluster) *policyv1.PodDisruptionBu Name: cr.SpecificName(), Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: cr.SpecificName(), + controllerutil.LabelAppKey: cr.SpecificName(), + controllerutil.LabelClusterKey: cr.Name, }), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: policyv1.PodDisruptionBudgetSpec{ @@ -151,6 +153,7 @@ func templateQuorumConfig(r *keeperReconciler) (*corev1.ConfigMap, error) { Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ controllerutil.LabelAppKey: cr.SpecificName(), + controllerutil.LabelClusterKey: cr.Name, controllerutil.LabelKeeperReplicaID: controllerutil.LabelKeeperAllReplicas, }), Annotations: cr.Spec.Annotations, @@ -249,11 +252,13 @@ func templateConfigMap(cr *v1.KeeperCluster, id v1.KeeperReplicaID) (*corev1.Con } return &corev1.ConfigMap{ - Kind: "ConfigMap", - APIVersion: "v1", - Name: cr.ConfigMapNameByReplicaID(id), - Namespace: cr.Namespace, - Labels: controllerutil.MergeMaps(cr.Spec.Labels, replicaLabels(cr, id)), + Kind: "ConfigMap", + APIVersion: "v1", + Name: cr.ConfigMapNameByReplicaID(id), + Namespace: cr.Namespace, + Labels: controllerutil.MergeMaps(cr.Spec.Labels, replicaLabels(cr, id), map[string]string{ + controllerutil.LabelClusterKey: cr.Name, + }), Annotations: cr.Spec.Annotations, Data: cfg, }, nil @@ -705,7 +710,8 @@ func templateNetworkPolicy(cr *v1.KeeperCluster, clickhouseClusters []v1.ClickHo Name: app, Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: app, + controllerutil.LabelAppKey: app, + controllerutil.LabelClusterKey: cr.Name, }), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: networkingv1.NetworkPolicySpec{ diff --git a/internal/controller/resourcemanager.go b/internal/controller/resourcemanager.go index 496d8cc53..b2a4ecd48 100644 --- a/internal/controller/resourcemanager.go +++ b/internal/controller/resourcemanager.go @@ -62,8 +62,6 @@ func (rm *ResourceManager) ReconcileResource( kind := resource.GetObjectKind().GroupVersionKind().Kind log = log.With("kind", kind, "resource", resource.GetName()) - resource.SetLabels(util.MergeMaps(resource.GetLabels(), util.ManagedByLabels())) - if err := ctrlruntime.SetControllerReference(rm.owner, resource, rm.ctrl.GetScheme()); err != nil { return false, fmt.Errorf("set %s/%s Ctrl reference: %w", kind, resource.GetName(), err) } @@ -300,8 +298,6 @@ func (rm *ResourceManager) ReconcileReplicaResources( } statefulSet := input.Desired.STS - // Only the StatefulSet object itself is labeled: changing the pod template would roll every replica. - statefulSet.Labels = util.MergeMaps(statefulSet.Labels, util.ManagedByLabels()) if err = ctrlruntime.SetControllerReference(rm.owner, statefulSet, rm.ctrl.GetScheme()); err != nil { return nil, fmt.Errorf("set replica StatefulSet controller reference: %w", err) diff --git a/internal/controller/versionprobe.go b/internal/controller/versionprobe.go index d18b0228a..d46d2e500 100644 --- a/internal/controller/versionprobe.go +++ b/internal/controller/versionprobe.go @@ -371,7 +371,7 @@ func (rm *ResourceManager) buildVersionProbeJob(cfg VersionProbeConfig, revision job.Name = rm.owner.SpecificResourceName("version-probe-" + revision[:8]) // Set reserved labels after overrides to ensure they are not modified by user overrides. - job.Labels = controllerutil.MergeMaps(job.Labels, controllerutil.ManagedByLabels(), map[string]string{ + job.Labels = controllerutil.MergeMaps(job.Labels, map[string]string{ controllerutil.LabelAppKey: rm.owner.SpecificName(), controllerutil.LabelClusterKey: rm.owner.GetName(), controllerutil.LabelRoleKey: controllerutil.LabelVersionProbe, diff --git a/internal/controllerutil/labels.go b/internal/controllerutil/labels.go index 3e43f6941..623dbdfe6 100644 --- a/internal/controllerutil/labels.go +++ b/internal/controllerutil/labels.go @@ -13,7 +13,6 @@ const ( LabelAppKey = "app" LabelAppK8sKey = "app.kubernetes.io/name" LabelInstanceK8sKey = "app.kubernetes.io/instance" - LabelManagedByKey = "app.kubernetes.io/managed-by" LabelRoleKey = "clickhouse.com/role" LabelClusterKey = "clickhouse.com/cluster" @@ -29,15 +28,8 @@ const ( LabelClickHouseValue = "clickhouse-server" LabelVersionProbe = "version-probe" LabelOperatorValue = "operator" - LabelManagedByValue = "clickhouse-operator" ) -// ManagedByLabels returns the label set stamped on every object the operator creates directly. -// The operator's informer caches are restricted to objects carrying it. -func ManagedByLabels() map[string]string { - return map[string]string{LabelManagedByKey: LabelManagedByValue} -} - // DiskLabel returns the label set identifying a disk's volumeClaimTemplate/PVC by name. func DiskLabel(name string) map[string]string { return map[string]string{LabelDiskName: name} From 284ddfe3411dd2b2d2368874726ab138fcba0990 Mon Sep 17 00:00:00 2001 From: Julian Early Date: Wed, 2 Dec 2026 11:58:43 -0800 Subject: [PATCH 3/5] refactor: minimize keeper template diff with clusterLabels helper Co-Authored-By: Claude Opus 5.5 --- internal/controller/keeper/templates.go | 36 ++++++++++++------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/internal/controller/keeper/templates.go b/internal/controller/keeper/templates.go index f39fcdabd..954414f16 100644 --- a/internal/controller/keeper/templates.go +++ b/internal/controller/keeper/templates.go @@ -66,9 +66,8 @@ func templateHeadlessService(cr *v1.KeeperCluster) *corev1.Service { Name: cr.HeadlessServiceName(), Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: cr.SpecificName(), - controllerutil.LabelClusterKey: cr.Name, - }), + controllerutil.LabelAppKey: cr.SpecificName(), + }, clusterLabels(cr)), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: corev1.ServiceSpec{ Ports: ports, @@ -97,9 +96,8 @@ func templatePodDisruptionBudget(cr *v1.KeeperCluster) *policyv1.PodDisruptionBu Name: cr.SpecificName(), Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: cr.SpecificName(), - controllerutil.LabelClusterKey: cr.Name, - }), + controllerutil.LabelAppKey: cr.SpecificName(), + }, clusterLabels(cr)), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: policyv1.PodDisruptionBudgetSpec{ Selector: &metav1.LabelSelector{ @@ -153,9 +151,8 @@ func templateQuorumConfig(r *keeperReconciler) (*corev1.ConfigMap, error) { Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ controllerutil.LabelAppKey: cr.SpecificName(), - controllerutil.LabelClusterKey: cr.Name, controllerutil.LabelKeeperReplicaID: controllerutil.LabelKeeperAllReplicas, - }), + }, clusterLabels(cr)), Annotations: cr.Spec.Annotations, Data: map[string]string{ QuorumConfigFileName: string(rawConfig), @@ -252,13 +249,11 @@ func templateConfigMap(cr *v1.KeeperCluster, id v1.KeeperReplicaID) (*corev1.Con } return &corev1.ConfigMap{ - Kind: "ConfigMap", - APIVersion: "v1", - Name: cr.ConfigMapNameByReplicaID(id), - Namespace: cr.Namespace, - Labels: controllerutil.MergeMaps(cr.Spec.Labels, replicaLabels(cr, id), map[string]string{ - controllerutil.LabelClusterKey: cr.Name, - }), + Kind: "ConfigMap", + APIVersion: "v1", + Name: cr.ConfigMapNameByReplicaID(id), + Namespace: cr.Namespace, + Labels: controllerutil.MergeMaps(cr.Spec.Labels, replicaLabels(cr, id), clusterLabels(cr)), Annotations: cr.Spec.Annotations, Data: cfg, }, nil @@ -323,6 +318,12 @@ func templateStatefulSet(cr *v1.KeeperCluster, id v1.KeeperReplicaID, cfgRestart }, nil } +// clusterLabels identifies objects belonging to the cluster. Not part of replicaLabels, which is +// used as the StatefulSet selector and therefore immutable. +func clusterLabels(cr *v1.KeeperCluster) map[string]string { + return map[string]string{controllerutil.LabelClusterKey: cr.Name} +} + func replicaLabels(cr *v1.KeeperCluster, id v1.KeeperReplicaID) map[string]string { labels := id.Labels() labels[controllerutil.LabelAppKey] = cr.SpecificName() @@ -710,9 +711,8 @@ func templateNetworkPolicy(cr *v1.KeeperCluster, clickhouseClusters []v1.ClickHo Name: app, Namespace: cr.Namespace, Labels: controllerutil.MergeMaps(cr.Spec.Labels, map[string]string{ - controllerutil.LabelAppKey: app, - controllerutil.LabelClusterKey: cr.Name, - }), + controllerutil.LabelAppKey: app, + }, clusterLabels(cr)), Annotations: controllerutil.MergeMaps(cr.Spec.Annotations), Spec: networkingv1.NetworkPolicySpec{ PodSelector: metav1.LabelSelector{MatchLabels: podLabels}, From c63840a26d70019e49310bdda2758bda57ae0322 Mon Sep 17 00:00:00 2001 From: Julian Early Date: Wed, 2 Dec 2026 12:58:36 -0800 Subject: [PATCH 4/5] fix: fall back to the API when the filtered cache misses an object The label-filtered cache hides operator-managed objects that lack the selector labels, e.g. Keeper objects created by an older operator replica still leading during a rolling upgrade, after the boot-time relabeling ran. ReconcileResource then saw NotFound and Create failed with AlreadyExists, and the quorum ConfigMap read as an empty quorum. - Controllers expose an uncached APIReader (mgr.GetAPIReader()). - ReconcileResource confirms a cache miss with the API before creating. If the object exists with an up-to-date spec, it only adds the missing labels (reported as unchanged, so no reload/restart side effects); if the spec is outdated, the normal update also merges the labels. Either way the object becomes visible to the cache again. - loadQuorumReplicas confirms a cache miss with the API instead of treating it as an empty quorum. Co-Authored-By: Claude Opus 5.5 --- internal/controller/clickhouse/controller.go | 12 ++ internal/controller/keeper/controller.go | 13 ++ internal/controller/keeper/sync.go | 14 ++- internal/controller/keeper/sync_test.go | 38 ++++++ internal/controller/resourcemanager.go | 41 +++++- internal/controller/resourcemanager_test.go | 117 ++++++++++++++++++ .../controller/testutil/filteredclient.go | 31 +++++ internal/controller/versionprobe_test.go | 10 +- 8 files changed, 264 insertions(+), 12 deletions(-) create mode 100644 internal/controller/resourcemanager_test.go create mode 100644 internal/controller/testutil/filteredclient.go diff --git a/internal/controller/clickhouse/controller.go b/internal/controller/clickhouse/controller.go index 591472951..657fdaa6e 100644 --- a/internal/controller/clickhouse/controller.go +++ b/internal/controller/clickhouse/controller.go @@ -38,6 +38,8 @@ type ClusterController struct { chctrl.Dependencies chctrl.Settings + // APIReader reads directly from the API server, bypassing the label-filtered cache. + APIReader client.Reader Scheme *runtime.Scheme Recorder events.EventRecorder Webhook webhookv1.ClickHouseClusterWebhook @@ -149,6 +151,15 @@ func (cc *ClusterController) GetClient() client.Client { return cc.Client } +// GetAPIReader returns a reader that bypasses the cache, defaulting to the Client when unset. +func (cc *ClusterController) GetAPIReader() client.Reader { + if cc.APIReader == nil { + return cc.Client + } + + return cc.APIReader +} + // GetScheme returns initialized with the Cluster Scheme. func (cc *ClusterController) GetScheme() *runtime.Scheme { return cc.Scheme @@ -176,6 +187,7 @@ func SetupWithManager(mgr ctrl.Manager, deps chctrl.Dependencies, settings chctr clickhouseController := &ClusterController{ Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), Dependencies: deps, Settings: settings, Scheme: mgr.GetScheme(), diff --git a/internal/controller/keeper/controller.go b/internal/controller/keeper/controller.go index 47d89ad4c..b94f2f16d 100644 --- a/internal/controller/keeper/controller.go +++ b/internal/controller/keeper/controller.go @@ -38,6 +38,9 @@ type ClusterController struct { Scheme *runtime.Scheme Recorder events.EventRecorder Webhook webhookv1.KeeperClusterWebhook + + // APIReader reads directly from the API server, bypassing the label-filtered cache. + APIReader client.Reader } // +kubebuilder:rbac:groups=clickhouse.com,resources=keeperclusters,verbs=get;list;watch;create;update;patch;delete @@ -129,6 +132,15 @@ func (cc *ClusterController) GetClient() client.Client { return cc.Client } +// GetAPIReader returns a reader that bypasses the cache, defaulting to the Client when unset. +func (cc *ClusterController) GetAPIReader() client.Reader { + if cc.APIReader == nil { + return cc.Client + } + + return cc.APIReader +} + // GetScheme returns initialized with the Cluster Scheme. func (cc *ClusterController) GetScheme() *runtime.Scheme { return cc.Scheme @@ -170,6 +182,7 @@ func SetupWithManager(mgr ctrl.Manager, deps chctrl.Dependencies, settings chctr keeperController := &ClusterController{ Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), Dependencies: deps, Settings: settings, Scheme: mgr.GetScheme(), diff --git a/internal/controller/keeper/sync.go b/internal/controller/keeper/sync.go index 4666dfd3c..273fb159d 100644 --- a/internal/controller/keeper/sync.go +++ b/internal/controller/keeper/sync.go @@ -793,11 +793,15 @@ func (r *keeperReconciler) updateReplica(ctx context.Context, log ctrlutil.Logge func (r *keeperReconciler) loadQuorumReplicas(ctx context.Context) (map[v1.KeeperReplicaID]struct{}, error) { configMap := corev1.ConfigMap{} - err := r.GetClient().Get( - ctx, - types.NamespacedName{Namespace: r.Cluster.Namespace, Name: r.Cluster.QuorumConfigMapName()}, - &configMap, - ) + key := types.NamespacedName{Namespace: r.Cluster.Namespace, Name: r.Cluster.QuorumConfigMapName()} + + err := r.GetClient().Get(ctx, key, &configMap) + if k8serrors.IsNotFound(err) { + // A quorum ConfigMap missing the cluster label is invisible to the cache. Treating it as absent + // would mean an empty quorum, so confirm with the API. + err = r.GetAPIReader().Get(ctx, key, &configMap) + } + if err != nil { if k8serrors.IsNotFound(err) { return map[v1.KeeperReplicaID]struct{}{}, nil diff --git a/internal/controller/keeper/sync_test.go b/internal/controller/keeper/sync_test.go index ab91e811d..8d51d973e 100644 --- a/internal/controller/keeper/sync_test.go +++ b/internal/controller/keeper/sync_test.go @@ -15,6 +15,7 @@ import ( k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -25,6 +26,7 @@ import ( v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" "github.com/ClickHouse/clickhouse-operator/internal/controller" + "github.com/ClickHouse/clickhouse-operator/internal/controller/testutil" util "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" "github.com/ClickHouse/clickhouse-operator/internal/upgrade" ) @@ -337,6 +339,42 @@ func mustGet[T client.Object](ctx context.Context, c client.Client, key types.Na return result } +var _ = Describe("loadQuorumReplicas with a label-filtered cache", func() { + It("reads a quorum ConfigMap missing the cluster label from the API", func(ctx context.Context) { + _, rec, cancelEvents := setupReconciler() + defer cancelEvents() + + cc, ok := rec.Controller.(*ClusterController) + Expect(ok).To(BeTrue()) + + api := cc.Client + cc.APIReader = api + cc.Client = testutil.LabelFilteredClient{ + Client: api, + Selector: labels.SelectorFromSet(labels.Set{util.LabelClusterKey: rec.Cluster.Name}), + } + + // Created by an older operator version, without the cluster label. + Expect(api.Create(ctx, &corev1.ConfigMap{ + Name: rec.Cluster.QuorumConfigMapName(), + Namespace: rec.Cluster.Namespace, + Labels: map[string]string{util.LabelAppKey: rec.Cluster.SpecificName()}, + Data: map[string]string{QuorumConfigFileName: `keeper_server: + raft_configuration: + server: + - id: "0" + - id: "2" +`}, + })).To(Succeed()) + + replicas, err := rec.loadQuorumReplicas(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(replicas).To(HaveLen(2)) + Expect(replicas).To(HaveKey(v1.KeeperReplicaID(0))) + Expect(replicas).To(HaveKey(v1.KeeperReplicaID(2))) + }) +}) + func setupReconciler() (util.Logger, *keeperReconciler, context.CancelFunc) { scheme := runtime.NewScheme() Expect(clientgoscheme.AddToScheme(scheme)).To(Succeed()) diff --git a/internal/controller/resourcemanager.go b/internal/controller/resourcemanager.go index b2a4ecd48..97b9c5f97 100644 --- a/internal/controller/resourcemanager.go +++ b/internal/controller/resourcemanager.go @@ -27,6 +27,8 @@ import ( // Controller provides access to shared Kubernetes dependencies. type Controller interface { GetClient() client.Client + // GetAPIReader returns a reader that bypasses the label-filtered cache. + GetAPIReader() client.Reader GetScheme() *runtime.Scheme GetRecorder() events.EventRecorder } @@ -79,10 +81,18 @@ func (rm *ResourceManager) ReconcileResource( foundResource := resource.DeepCopyObject().(client.Object) //nolint:forcetypeassert // safe cast - err = rm.ctrl.GetClient().Get(ctx, types.NamespacedName{ - Namespace: resource.GetNamespace(), - Name: resource.GetName(), - }, foundResource) + key := types.NamespacedName{Namespace: resource.GetNamespace(), Name: resource.GetName()} + + // The cache only holds objects carrying the operator's selector labels. An object created without + // them (e.g. by an older operator version) is invisible to it, so confirm with the API before creating. + uncached := false + + err = rm.ctrl.GetClient().Get(ctx, key, foundResource) + if k8serrors.IsNotFound(err) { + uncached = true + err = rm.ctrl.GetAPIReader().Get(ctx, key, foundResource) + } + if err != nil { if !k8serrors.IsNotFound(err) { return false, fmt.Errorf("get %s/%s: %w", kind, resource.GetName(), err) @@ -94,8 +104,16 @@ func (rm *ResourceManager) ReconcileResource( } if util.GetSpecHashFromObject(foundResource) == resourceHash { - log.Debug("resource is up to date") - return false, nil + if !uncached || hasLabels(foundResource, resource.GetLabels()) { + log.Debug("resource is up to date") + return false, nil + } + + // Spec is current; only add the missing labels so the object becomes visible to the cache. + log.Info("resource is missing labels, relabeling") + foundResource.SetLabels(util.MergeMaps(foundResource.GetLabels(), resource.GetLabels())) + + return false, rm.Update(ctx, foundResource, action) } log.Debug("resource changed, diff: " + gcmp.Diff(foundResource, resource, diffFilter(specFields))) @@ -115,6 +133,17 @@ func (rm *ResourceManager) ReconcileResource( return true, rm.Update(ctx, foundResource, action) } +func hasLabels(obj client.Object, want map[string]string) bool { + have := obj.GetLabels() + for k, v := range want { + if have[k] != v { + return false + } + } + + return true +} + // ReconcileService reconciles a Kubernetes Service resource. func (rm *ResourceManager) ReconcileService( ctx context.Context, diff --git a/internal/controller/resourcemanager_test.go b/internal/controller/resourcemanager_test.go new file mode 100644 index 000000000..925dc7f68 --- /dev/null +++ b/internal/controller/resourcemanager_test.go @@ -0,0 +1,117 @@ +package controller + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/labels" + "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" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/log/zap" + + v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" + "github.com/ClickHouse/clickhouse-operator/internal/controller/testutil" + "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" +) + +var _ = Describe("ReconcileResource with a label-filtered cache", func() { + const namespace = "default" + + var ( + api client.Client + filtered ResourceManager + log controllerutil.Logger + ) + + desiredConfigMap := func(data string) *corev1.ConfigMap { + return &corev1.ConfigMap{ + Kind: "ConfigMap", + APIVersion: "v1", + Name: "test-config", + Namespace: namespace, + Labels: map[string]string{ + controllerutil.LabelAppKey: "test-clickhouse", + controllerutil.LabelClusterKey: "test", + }, + Data: map[string]string{"config.yaml": data}, + } + } + + // stripClusterLabel simulates an object created by an older operator version. + stripClusterLabel := func(ctx context.Context) { + var cm corev1.ConfigMap + Expect(api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: "test-config"}, &cm)).To(Succeed()) + delete(cm.Labels, controllerutil.LabelClusterKey) + Expect(api.Update(ctx, &cm)).To(Succeed()) + } + + get := func(ctx context.Context) corev1.ConfigMap { + var cm corev1.ConfigMap + Expect(api.Get(ctx, client.ObjectKey{Namespace: namespace, Name: "test-config"}, &cm)).To(Succeed()) + + return cm + } + + BeforeEach(func() { + scheme := runtime.NewScheme() + Expect(clientgoscheme.AddToScheme(scheme)).To(Succeed()) + Expect(v1.AddToScheme(scheme)).To(Succeed()) + + api = fake.NewClientBuilder().WithScheme(scheme).Build() + log = controllerutil.NewLogger(zap.NewRaw(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) + + cache := testutil.LabelFilteredClient{ + Client: api, + Selector: labels.SelectorFromSet(labels.Set{controllerutil.LabelClusterKey: "test"}), + } + owner := &v1.ClickHouseCluster{Namespace: namespace, Name: "test", UID: "test-uid"} + filtered = NewResourceManager(&fakeController{ + client: cache, reader: api, scheme: scheme, recorder: events.NewFakeRecorder(32), + }, owner) + }) + + It("creates the object when it doesn't exist", func(ctx context.Context) { + changed, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + Expect(changed).To(BeTrue()) + Expect(get(ctx).Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, "test")) + }) + + It("relabels an up-to-date object hidden from the cache without reporting a change", func(ctx context.Context) { + _, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + stripClusterLabel(ctx) + + changed, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + Expect(changed).To(BeFalse()) + + cm := get(ctx) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, "test")) + Expect(cm.Data).To(HaveKeyWithValue("config.yaml", "a")) + + // Visible to the cache again: the next reconcile is a no-op. + changed, err = filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + Expect(changed).To(BeFalse()) + }) + + It("updates and relabels an outdated object hidden from the cache", func(ctx context.Context) { + _, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + stripClusterLabel(ctx) + + changed, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("b"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + Expect(changed).To(BeTrue()) + + cm := get(ctx) + Expect(cm.Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, "test")) + Expect(cm.Data).To(HaveKeyWithValue("config.yaml", "b")) + }) +}) diff --git a/internal/controller/testutil/filteredclient.go b/internal/controller/testutil/filteredclient.go new file mode 100644 index 000000000..7148f879c --- /dev/null +++ b/internal/controller/testutil/filteredclient.go @@ -0,0 +1,31 @@ +package testutil + +import ( + "context" + + k8serrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// LabelFilteredClient mimics a client backed by a label-filtered cache: Get reports NotFound for objects +// whose labels don't match Selector, while writes go straight to the wrapped client. +type LabelFilteredClient struct { + client.Client + + Selector labels.Selector +} + +// Get returns NotFound for objects that don't match the selector. +func (c LabelFilteredClient) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { + if err := c.Client.Get(ctx, key, obj, opts...); err != nil { + return err //nolint:wrapcheck // mimics client behavior + } + + if !c.Selector.Matches(labels.Set(obj.GetLabels())) { + return k8serrors.NewNotFound(schema.GroupResource{}, key.Name) + } + + return nil +} diff --git a/internal/controller/versionprobe_test.go b/internal/controller/versionprobe_test.go index ba8e9fdf6..2b4dc0897 100644 --- a/internal/controller/versionprobe_test.go +++ b/internal/controller/versionprobe_test.go @@ -302,11 +302,19 @@ func setupProbeTest() (ResourceManager, controllerutil.Logger) { // fakeController implements the Controller interface for unit tests. type fakeController struct { client client.Client + reader client.Reader scheme *runtime.Scheme recorder events.EventRecorder } -func (f *fakeController) GetClient() client.Client { return f.client } +func (f *fakeController) GetClient() client.Client { return f.client } +func (f *fakeController) GetAPIReader() client.Reader { + if f.reader != nil { + return f.reader + } + + return f.client +} func (f *fakeController) GetScheme() *runtime.Scheme { return f.scheme } func (f *fakeController) GetRecorder() events.EventRecorder { return f.recorder } From 393a96998189a9f4e1b65af3da99d2f39c10d979 Mon Sep 17 00:00:00 2001 From: Julian Early Date: Wed, 2 Dec 2026 13:08:08 -0800 Subject: [PATCH 5/5] fix: re-read from the API when retrying a conflicting update ResourceManager.Update refreshed resourceVersion through the cached client on conflict. Objects found via the ReconcileResource API fallback lack the cache's selector labels, so that re-read returned NotFound and the relabel or spec update failed instead of retrying. Re-read through the API reader, which is also never stale. Co-Authored-By: Claude Opus 5.5 --- internal/controller/resourcemanager.go | 4 ++- internal/controller/resourcemanager_test.go | 30 ++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/internal/controller/resourcemanager.go b/internal/controller/resourcemanager.go index 97b9c5f97..b3aba13d5 100644 --- a/internal/controller/resourcemanager.go +++ b/internal/controller/resourcemanager.go @@ -198,7 +198,9 @@ func (rm *ResourceManager) Update(ctx context.Context, resource client.Object, a err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { if !first { - if err := rm.ctrl.GetClient().Get(ctx, client.ObjectKeyFromObject(fetched), fetched); err != nil { + // Read from the API: the cache may be stale on conflict, and objects found through the + // ReconcileResource fallback (missing the cache's selector labels) aren't in it at all. + if err := rm.ctrl.GetAPIReader().Get(ctx, client.ObjectKeyFromObject(fetched), fetched); err != nil { return fmt.Errorf("get %s/%s: %w", kind, resource.GetName(), err) } diff --git a/internal/controller/resourcemanager_test.go b/internal/controller/resourcemanager_test.go index 925dc7f68..a2c07a272 100644 --- a/internal/controller/resourcemanager_test.go +++ b/internal/controller/resourcemanager_test.go @@ -2,16 +2,20 @@ package controller import ( "context" + "errors" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" + k8serrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/events" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" "sigs.k8s.io/controller-runtime/pkg/log/zap" v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" @@ -26,6 +30,8 @@ var _ = Describe("ReconcileResource with a label-filtered cache", func() { api client.Client filtered ResourceManager log controllerutil.Logger + // conflicts is the number of upcoming Updates that fail with a conflict. + conflicts int ) desiredConfigMap := func(data string) *corev1.ConfigMap { @@ -62,7 +68,17 @@ var _ = Describe("ReconcileResource with a label-filtered cache", func() { Expect(clientgoscheme.AddToScheme(scheme)).To(Succeed()) Expect(v1.AddToScheme(scheme)).To(Succeed()) - api = fake.NewClientBuilder().WithScheme(scheme).Build() + conflicts = 0 + api = fake.NewClientBuilder().WithScheme(scheme).WithInterceptorFuncs(interceptor.Funcs{ + Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + if conflicts > 0 { + conflicts-- + return k8serrors.NewConflict(schema.GroupResource{Resource: "configmaps"}, obj.GetName(), errors.New("stale")) + } + + return c.Update(ctx, obj, opts...) + }, + }).Build() log = controllerutil.NewLogger(zap.NewRaw(zap.WriteTo(GinkgoWriter), zap.UseDevMode(true))) cache := testutil.LabelFilteredClient{ @@ -101,6 +117,18 @@ var _ = Describe("ReconcileResource with a label-filtered cache", func() { Expect(changed).To(BeFalse()) }) + It("retries a conflicting relabel of an object hidden from the cache", func(ctx context.Context) { + _, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + stripClusterLabel(ctx) + + conflicts = 1 + _, err = filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) + Expect(err).NotTo(HaveOccurred()) + Expect(conflicts).To(BeZero()) + Expect(get(ctx).Labels).To(HaveKeyWithValue(controllerutil.LabelClusterKey, "test")) + }) + It("updates and relabels an outdated object hidden from the cache", func(ctx context.Context) { _, err := filtered.ReconcileConfigMap(ctx, log, desiredConfigMap("a"), v1.EventActionReconciling) Expect(err).NotTo(HaveOccurred())