/
watch.go
65 lines (54 loc) · 1.46 KB
/
watch.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
// SPDX-License-Identifier: MIT
package reconcile
import (
"fmt"
"reflect"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/source"
"github.com/nukleros/operator-builder-tools/pkg/controller/predicates"
"github.com/nukleros/operator-builder-tools/pkg/controller/workload"
)
// Watch watches a resource.
func Watch(
r workload.Reconciler,
req *workload.Request,
resource client.Object,
) error {
// ignore jobs as they are ephemerial
if resource.GetObjectKind().GroupVersionKind().Kind == "job" {
if resource.GetObjectKind().GroupVersionKind().Version == "v1" {
return nil
}
}
// check if the resource is already being watched
var watched bool
if len(r.GetWatches()) > 0 {
for _, watcher := range r.GetWatches() {
if reflect.DeepEqual(
resource.GetObjectKind().GroupVersionKind(),
watcher.GetObjectKind().GroupVersionKind(),
) {
watched = true
}
}
}
// watch the resource if it current is not being watched
eventHandler := handler.EnqueueRequestForOwner(
r.GetManager().GetScheme(),
r.GetManager().GetRESTMapper(),
req.Workload,
handler.OnlyControllerOwner(),
)
if !watched {
if err := r.GetController().Watch(
source.Kind(r.GetManager().GetCache(), resource),
eventHandler,
predicates.ResourcePredicates(r, req),
); err != nil {
return fmt.Errorf("unable to watch resource, %w", err)
}
r.SetWatch(resource)
}
return nil
}