-
Notifications
You must be signed in to change notification settings - Fork 103
/
shared.go
85 lines (71 loc) · 2.57 KB
/
shared.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
78
79
80
81
82
83
84
85
package shared
import (
"fmt"
"os"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetWatchNamespace returns the Namespace the operator should be watching for changes
// Note: the marketplace-operator YAML manifest deployed by the CVO specifies the
// $WATCH_NAMESPACE as an environment variable using the downward API.
// Source: https://sdk.operatorframework.io/docs/building-operators/golang/operator-scope/
func GetWatchNamespace() (string, error) {
// WatchNamespaceEnvVar is the constant for env variable WATCH_NAMESPACE
// which specifies the Namespace to watch.
// An empty value means the operator is running with cluster scope.
var watchNamespaceEnvVar = "WATCH_NAMESPACE"
ns, found := os.LookupEnv(watchNamespaceEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", watchNamespaceEnvVar)
}
return ns, nil
}
// EnsureFinalizer ensures that the object's finalizer is included
// in the ObjectMeta Finalizers slice. If it already exists, no state change occurs.
// If it doesn't, the finalizer is appended to the slice.
func EnsureFinalizer(objectMeta *metav1.ObjectMeta, expectedFinalizer string) {
// First check if the finalizer is already included in the object.
for _, finalizer := range objectMeta.Finalizers {
if finalizer == expectedFinalizer {
return
}
}
// If it doesn't exist, append the finalizer to the object meta.
objectMeta.Finalizers = append(objectMeta.Finalizers, expectedFinalizer)
return
}
// RemoveFinalizer removes the finalizer from the object's ObjectMeta.
func RemoveFinalizer(objectMeta *metav1.ObjectMeta, deletingFinalizer string) {
outFinalizers := make([]string, 0)
for _, finalizer := range objectMeta.Finalizers {
if finalizer == deletingFinalizer {
continue
}
outFinalizers = append(outFinalizers, finalizer)
}
objectMeta.Finalizers = outFinalizers
return
}
// HasFinalizer checks to see if the finalizer exists in the object's ObjectMeta.
func HasFinalizer(objectMeta *metav1.ObjectMeta, expectedFinalizer string) bool {
finalizerExists := false
for _, finalizer := range objectMeta.Finalizers {
if finalizer == expectedFinalizer {
finalizerExists = true
break
}
}
return finalizerExists
}
// IsObjectInOtherNamespace returns true if the namespace is not the watched
// namespace of the operator. An false, error will be returned if there was an
// error getting the watched namespace.
func IsObjectInOtherNamespace(namespace string) (bool, error) {
watchNamespace, err := GetWatchNamespace()
if err != nil {
return false, err
}
if namespace != watchNamespace {
return true, nil
}
return false, nil
}