Skip to content

Commit 127907d

Browse files
committed
providers/namespace: fix indexes
Signed-off-by: Dr. Stefan Schimanski <stefan.schimanski@gmail.com>
1 parent 8f61ed2 commit 127907d

File tree

4 files changed

+20
-110
lines changed

4 files changed

+20
-110
lines changed

examples/namespace/main.go

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,15 @@ import (
2323

2424
flag "github.com/spf13/pflag"
2525
"golang.org/x/sync/errgroup"
26-
apierrors "k8s.io/apimachinery/pkg/api/errors"
2726

2827
corev1 "k8s.io/api/core/v1"
28+
apierrors "k8s.io/apimachinery/pkg/api/errors"
2929
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
3030
"k8s.io/apimachinery/pkg/util/runtime"
3131
"k8s.io/client-go/rest"
3232
"k8s.io/klog/v2"
3333

3434
ctrl "sigs.k8s.io/controller-runtime"
35-
"sigs.k8s.io/controller-runtime/pkg/cache"
3635
"sigs.k8s.io/controller-runtime/pkg/client"
3736
"sigs.k8s.io/controller-runtime/pkg/cluster"
3837
"sigs.k8s.io/controller-runtime/pkg/envtest"
@@ -103,17 +102,16 @@ func main() {
103102
runtime.Must(client.IgnoreAlreadyExists(cli.Create(ctx, &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "island"}})))
104103
runtime.Must(client.IgnoreAlreadyExists(cli.Create(ctx, &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: "island", Name: "bird"}})))
105104

106-
cl, err := cluster.New(cfg, namespace.WithClusterNameIndex())
105+
cl, err := cluster.New(cfg)
106+
if err != nil {
107+
entryLog.Error(err, "failed to create cluster")
108+
os.Exit(1)
109+
}
107110
provider := namespace.New(cl)
108111

109112
// Setup a cluster-aware Manager, with the provider to lookup clusters.
110113
entryLog.Info("Setting up cluster-aware manager")
111-
mgr, err := mcmanager.New(cfg, provider, manager.Options{
112-
NewCache: func(config *rest.Config, opts cache.Options) (cache.Cache, error) {
113-
// wrap cache to turn IndexField calls into cluster-scoped indexes.
114-
return &namespace.NamespaceScopeableCache{Cache: cl.GetCache()}, nil
115-
},
116-
})
114+
mgr, err := mcmanager.New(cfg, provider, manager.Options{})
117115
if err != nil {
118116
entryLog.Error(err, "unable to set up overall controller manager")
119117
os.Exit(1)

providers/namespace/cache.go

Lines changed: 8 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ package namespace
1919
import (
2020
"context"
2121
"errors"
22-
"fmt"
2322
"time"
2423

2524
corev1 "k8s.io/api/core/v1"
@@ -33,13 +32,6 @@ import (
3332
"sigs.k8s.io/controller-runtime/pkg/client"
3433
)
3534

36-
const (
37-
// ClusterNameIndex indexes object by cluster and name.
38-
ClusterNameIndex = "cluster/name"
39-
// ClusterIndex indexes object by cluster.
40-
ClusterIndex = "cluster"
41-
)
42-
4335
var _ cache.Cache = &NamespacedCache{}
4436

4537
// NamespacedCache is a cache that operates on a specific namespace.
@@ -68,26 +60,16 @@ func (c *NamespacedCache) List(ctx context.Context, list client.ObjectList, opts
6860
o.ApplyToList(&listOpts)
6961
}
7062

71-
switch {
72-
case listOpts.FieldSelector != nil:
73-
reqs := listOpts.FieldSelector.Requirements()
74-
flds := make(map[string]string, len(reqs))
75-
for i := range reqs {
76-
flds[fmt.Sprintf("cluster/%s", reqs[i].Field)] = fmt.Sprintf("%s/%s", c.clusterName, reqs[i].Value)
77-
}
78-
opts = append(opts, client.MatchingFields(flds))
79-
case listOpts.Namespace != "":
80-
opts = append(opts, client.MatchingFields(map[string]string{ClusterIndex: c.clusterName}))
81-
if c.clusterName == "*" {
82-
listOpts.Namespace = ""
83-
} else if listOpts.Namespace == corev1.NamespaceDefault {
84-
listOpts.Namespace = c.clusterName
85-
}
86-
default:
87-
opts = append(opts, client.MatchingFields(map[string]string{ClusterIndex: c.clusterName}))
63+
if listOpts.Namespace != "" && listOpts.Namespace != corev1.NamespaceDefault {
64+
return nil
8865
}
8966

90-
if err := c.Cache.List(ctx, list, opts...); err != nil {
67+
ns := c.clusterName
68+
if ns == "*" {
69+
ns = ""
70+
}
71+
72+
if err := c.Cache.List(ctx, list, append(opts, client.InNamespace(ns))...); err != nil {
9173
return err
9274
}
9375

@@ -201,26 +183,3 @@ func (i *ScopedInformer) AddEventHandlerWithResyncPeriod(handler toolscache.Reso
201183
func (i *ScopedInformer) AddIndexers(indexers toolscache.Indexers) error {
202184
return errors.New("indexes cannot be added to scoped informers")
203185
}
204-
205-
// NamespaceScopeableCache is a cache that indexes objects by namespace.
206-
type NamespaceScopeableCache struct { //nolint:revive // Stuttering here is fine.
207-
cache.Cache
208-
}
209-
210-
// IndexField adds an index for the given object kind.
211-
func (f *NamespaceScopeableCache) IndexField(ctx context.Context, obj client.Object, field string, extractValue client.IndexerFunc) error {
212-
return f.Cache.IndexField(ctx, obj, "cluster/"+field, func(obj client.Object) []string {
213-
keys := extractValue(obj)
214-
withCluster := make([]string, len(keys)*2)
215-
for i, key := range keys {
216-
withCluster[i] = fmt.Sprintf("%s/%s", obj.GetNamespace(), key)
217-
withCluster[i+len(keys)] = fmt.Sprintf("*/%s", key)
218-
}
219-
return withCluster
220-
})
221-
}
222-
223-
// Start starts the cache.
224-
func (f *NamespaceScopeableCache) Start(ctx context.Context) error {
225-
return nil // no-op as this is shared
226-
}

providers/namespace/cluster.go

Lines changed: 0 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -18,50 +18,14 @@ package namespace
1818

1919
import (
2020
"context"
21-
"fmt"
22-
"time"
2321

24-
apiruntime "k8s.io/apimachinery/pkg/runtime"
25-
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
26-
toolscache "k8s.io/client-go/tools/cache"
2722
"k8s.io/client-go/tools/record"
2823

2924
"sigs.k8s.io/controller-runtime/pkg/cache"
3025
"sigs.k8s.io/controller-runtime/pkg/client"
3126
"sigs.k8s.io/controller-runtime/pkg/cluster"
3227
)
3328

34-
// WithClusterNameIndex adds indexers for cluster name and namespace.
35-
func WithClusterNameIndex() cluster.Option {
36-
return func(options *cluster.Options) {
37-
old := options.Cache.NewInformer
38-
options.Cache.NewInformer = func(watcher toolscache.ListerWatcher, object apiruntime.Object, duration time.Duration, indexers toolscache.Indexers) toolscache.SharedIndexInformer {
39-
var inf toolscache.SharedIndexInformer
40-
if old != nil {
41-
inf = old(watcher, object, duration, indexers)
42-
} else {
43-
inf = toolscache.NewSharedIndexInformer(watcher, object, duration, indexers)
44-
}
45-
if err := inf.AddIndexers(toolscache.Indexers{
46-
ClusterNameIndex: func(obj any) ([]string, error) {
47-
o := obj.(client.Object)
48-
return []string{
49-
fmt.Sprintf("%s/%s", o.GetNamespace(), o.GetName()),
50-
fmt.Sprintf("%s/%s", "*", o.GetName()),
51-
}, nil
52-
},
53-
ClusterIndex: func(obj any) ([]string, error) {
54-
o := obj.(client.Object)
55-
return []string{o.GetNamespace()}, nil
56-
},
57-
}); err != nil {
58-
utilruntime.HandleError(fmt.Errorf("unable to add cluster name indexers: %w", err))
59-
}
60-
return inf
61-
}
62-
}
63-
}
64-
6529
// NamespacedCluster is a cluster that operates on a specific namespace.
6630
type NamespacedCluster struct {
6731
clusterName string

providers/namespace/provider_test.go

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@ package namespace
1919
import (
2020
"context"
2121
"errors"
22+
"strconv"
2223

2324
"golang.org/x/sync/errgroup"
2425

2526
corev1 "k8s.io/api/core/v1"
2627
apierrors "k8s.io/apimachinery/pkg/api/errors"
2728
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
28-
"k8s.io/apimachinery/pkg/labels"
2929
"k8s.io/apimachinery/pkg/util/runtime"
30-
"k8s.io/client-go/rest"
30+
"k8s.io/apimachinery/pkg/util/sets"
31+
"k8s.io/client-go/util/retry"
3132

3233
ctrl "sigs.k8s.io/controller-runtime"
33-
"sigs.k8s.io/controller-runtime/pkg/cache"
3434
"sigs.k8s.io/controller-runtime/pkg/client"
3535
"sigs.k8s.io/controller-runtime/pkg/cluster"
3636
"sigs.k8s.io/controller-runtime/pkg/log"
@@ -61,25 +61,14 @@ var _ = Describe("Provider Namespace", Ordered, func() {
6161

6262
By("Setting up the provider against the host cluster", func() {
6363
var err error
64-
cl, err = cluster.New(cfg, WithClusterNameIndex(), func(options *cluster.Options) {
65-
options.Cache.ByObject = map[client.Object]cache.ByObject{
66-
&corev1.ConfigMap{}: {
67-
Label: labels.Set{"type": "animal"}.AsSelector(),
68-
},
69-
}
70-
})
64+
cl, err = cluster.New(cfg)
7165
Expect(err).NotTo(HaveOccurred())
7266
provider = New(cl)
7367
})
7468

7569
By("Setting up the cluster-aware manager, with the provider to lookup clusters", func() {
7670
var err error
77-
mgr, err = mcmanager.New(cfg, provider, manager.Options{
78-
NewCache: func(config *rest.Config, opts cache.Options) (cache.Cache, error) {
79-
// wrap cache to turn IndexField calls into cluster-scoped indexes.
80-
return &NamespaceScopeableCache{Cache: cl.GetCache()}, nil
81-
},
82-
})
71+
mgr, err = mcmanager.New(cfg, provider, manager.Options{})
8372
Expect(err).NotTo(HaveOccurred())
8473
})
8574

0 commit comments

Comments
 (0)