Repository navigation
fix: limit kube loading to filter based on labels #419
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
hiporox
wants to merge
6
commits into
ClickHouse:main
Choose a base branch
from
chalk-ai:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+609
−20
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
823a294
fix: restrict informer caches to operator-managed objects
hiporox bcda37a
fix: filter caches on existing labels instead of a new managed-by label
hiporox 284ddfe
refactor: minimize keeper template diff with clusterLabels helper
hiporox d9f1cd7
Merge pull request #1 from chalk-ai/fix/label-filtered-cache
hiporox c63840a
fix: fall back to the API when the filtered cache misses an object
hiporox 393a969
fix: re-read from the API when retrying a conflicting update
hiporox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| 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/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" | ||
|
|
||
| v1 "github.com/ClickHouse/clickhouse-operator/api/v1alpha1" | ||
| "github.com/ClickHouse/clickhouse-operator/internal/controllerutil" | ||
| ) | ||
|
|
||
| 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)) | ||
| } | ||
|
|
||
| return *req | ||
| } | ||
|
|
||
| // 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)) | ||
| } | ||
|
|
||
| // 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 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 { | ||
| byCluster := cache.ByObject{Label: clusterSelector()} | ||
| replicas := roleSelector(controllerutil.LabelClickHouseValue, controllerutil.LabelKeeperValue) | ||
|
|
||
| return map[client.Object]cache.ByObject{ | ||
| &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, | ||
| )}, | ||
| } | ||
| } | ||
|
Comment on lines
+52
to
+67
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's use a single |
||
|
|
||
| // 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 cluster label. | ||
| func uncachedObjects() []client.Object { | ||
| return []client.Object{&corev1.Secret{}} | ||
| } | ||
|
|
||
| // 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"), | ||
| } | ||
|
|
||
| // 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} | ||
| } | ||
|
|
||
| labeled := 0 | ||
|
|
||
| for _, ns := range namespaces { | ||
| 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 keepers.Items { | ||
| count, err := labelKeeperResources(ctx, cli, &keepers.Items[i]) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| labeled += count | ||
| } | ||
| } | ||
|
|
||
| if labeled > 0 { | ||
| log.Info("labeled existing KeeperCluster resources", "count", labeled, "label", controllerutil.LabelClusterKey) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| 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), | ||
| ) | ||
|
|
||
| labeled := 0 | ||
|
|
||
| for _, gvk := range legacyKeeperKinds { | ||
| var list unstructured.UnstructuredList | ||
| list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) | ||
|
|
||
| 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) | ||
| } | ||
|
|
||
| for i := range list.Items { | ||
| obj := &list.Items[i] | ||
| if !metav1.IsControlledBy(obj, keeper) { | ||
| continue | ||
| } | ||
|
|
||
| obj.SetGroupVersionKind(gvk) | ||
|
|
||
| err := retry.RetryOnConflict(retry.DefaultBackoff, func() error { | ||
| if err := cli.Get(ctx, client.ObjectKeyFromObject(obj), obj); err != nil { | ||
| return err //nolint:wrapcheck // wrapped below | ||
| } | ||
|
|
||
| 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) | ||
| } | ||
|
|
||
| labeled++ | ||
| } | ||
| } | ||
|
|
||
| return labeled, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| package app | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| . "github.com/onsi/ginkgo/v2" | ||
| . "github.com/onsi/gomega" | ||
| "go.uber.org/zap" | ||
| 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" | ||
| "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 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 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() { | ||
| for obj, cfg := range cacheByObject() { | ||
| Expect(cfg.Label).NotTo(BeNil(), "%T", obj) | ||
| Expect(cfg.Label.Empty()).To(BeFalse(), "%T", obj) | ||
| } | ||
| }) | ||
| }) | ||
|
|
||
| var _ = Describe("labelLegacyKeeperResources", func() { | ||
| const namespace = "default" | ||
|
|
||
| var ( | ||
| cli client.Client | ||
| keeper *v1.KeeperCluster | ||
| logger controllerutil.Logger | ||
| ) | ||
|
|
||
| controlledBy := func(owner client.Object) []metav1.OwnerReference { | ||
| return []metav1.OwnerReference{{ | ||
| APIVersion: v1.GroupVersion.String(), | ||
| Kind: "KeeperCluster", | ||
| Name: owner.GetName(), | ||
| UID: owner.GetUID(), | ||
| Controller: new(true), | ||
| }} | ||
| } | ||
|
|
||
| BeforeEach(func() { | ||
| logger = controllerutil.NewLogger(zap.NewNop()) | ||
| keeper = &v1.KeeperCluster{ | ||
| Name: "test", Namespace: namespace, UID: "keeper-uid", | ||
| } | ||
|
|
||
| appLabels := map[string]string{controllerutil.LabelAppKey: keeper.SpecificName()} | ||
|
|
||
| cli = fake.NewClientBuilder().WithScheme(NewScheme()).WithObjects( | ||
| keeper, | ||
| // Created by an older operator version: must be labeled. | ||
| &corev1.ConfigMap{ | ||
| 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.Service{ | ||
| Name: "foreign", Namespace: namespace, Labels: appLabels}, | ||
| ).Build() | ||
| }) | ||
|
|
||
| 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: "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(labelLegacyKeeperResources(ctx, cli, []string{namespace}, logger)).To(Succeed()) | ||
| Expect(labelLegacyKeeperResources(ctx, cli, []string{namespace}, logger)).To(Succeed()) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.