forked from keycloak/keycloak-operator
/
controller_utils.go
77 lines (64 loc) · 2.44 KB
/
controller_utils.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package common
import (
"context"
"fmt"
"github.com/keycloak/keycloak-realm-operator/pkg/apis/keycloak/v1alpha1"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/source"
)
// These kinds are not provided by the openshift api
const (
RouteKind = "Route"
SecretKind = "Secret"
PodDisruptionBudgetKind = "PodDisruptionBudget"
OpenShiftAPIServerKind = "OpenShiftAPIServer"
)
func WatchSecondaryResource(c controller.Controller, controllerName string, resourceKind string, objectTypetoWatch runtime.Object, cr runtime.Object) error {
stateManager := GetStateManager()
stateFieldName := GetStateFieldName(controllerName, resourceKind)
// Avoid watching non-existing resources and watch duplication
watchExists, _ := stateManager.GetState(stateFieldName).(bool)
keyExists, _ := stateManager.GetState(resourceKind).(bool)
if !keyExists || watchExists {
return nil
}
// Set up the actual watch
err := c.Watch(&source.Kind{Type: objectTypetoWatch}, &handler.EnqueueRequestForOwner{
IsController: true,
OwnerType: cr,
})
// Retry on error
if err != nil {
log.Error(err, "error creating watch")
stateManager.SetState(stateFieldName, false)
return err
}
stateManager.SetState(stateFieldName, true)
log.Info(fmt.Sprintf("Watch created for '%s' resource in '%s'", resourceKind, controllerName))
return nil
}
func GetStateFieldName(controllerName string, kind string) string {
return controllerName + "-watch-" + kind
}
// Try to get a list of keycloak instances that match the selector specified on the realm
func GetMatchingKeycloaks(ctx context.Context, c client.Client, labelSelector *v1.LabelSelector) (v1alpha1.ExternalKeycloakList, error) {
var list v1alpha1.ExternalKeycloakList
opts := []client.ListOption{
client.MatchingLabels(labelSelector.MatchLabels),
}
err := c.List(ctx, &list, opts...)
return list, err
}
// Try to get a list of keycloak instances that match the selector specified on the realm
func GetMatchingRealms(ctx context.Context, c client.Client, labelSelector *v1.LabelSelector) (v1alpha1.KeycloakRealmList, error) {
var list v1alpha1.KeycloakRealmList
opts := []client.ListOption{
client.MatchingLabels(labelSelector.MatchLabels),
}
err := c.List(ctx, &list, opts...)
return list, err
}