-
Notifications
You must be signed in to change notification settings - Fork 2
/
cache.go
62 lines (56 loc) · 1.36 KB
/
cache.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"context"
"errors"
"fmt"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
)
func BuildAndStartCache(ctx context.Context, cfg *rest.Config) (cache.Cache, error) {
s := runtime.NewScheme()
if err := corev1.AddToScheme(s); err != nil {
return nil, err
}
if err := rbacv1.AddToScheme(s); err != nil {
return nil, err
}
oo := []client.Object{
&corev1.Namespace{},
&rbacv1.RoleBinding{},
&rbacv1.ClusterRole{},
&rbacv1.ClusterRoleBinding{},
&rbacv1.Role{},
}
c, err := cache.New(cfg, cache.Options{
Scheme: s,
ByObject: map[client.Object]cache.ByObject{
&corev1.Namespace{}: {},
&rbacv1.RoleBinding{}: {},
&rbacv1.ClusterRole{}: {},
&rbacv1.ClusterRoleBinding{}: {},
&rbacv1.Role{}: {},
},
})
if err != nil {
return nil, err
}
for _, o := range oo {
_, err := c.GetInformer(ctx, o)
if err != nil {
return nil, fmt.Errorf("error starting cache: getting informer for %s: %w", o.GetObjectKind().GroupVersionKind().String(), err)
}
}
go func() {
if err := c.Start(ctx); err != nil {
panic(err)
}
}()
if !c.WaitForCacheSync(ctx) {
return nil, errors.New("error starting the cache")
}
return c, nil
}