Skip to content

Commit

Permalink
restrict manager resource cache to only operator namespace
Browse files Browse the repository at this point in the history
Signed-off-by: Leela Venkaiah G <[email protected]>
  • Loading branch information
leelavg committed Dec 19, 2024
1 parent 1c8ad98 commit 37772c2
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ package main
import (
"crypto/tls"
"flag"
"fmt"
"os"
"strings"

// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
// to ensure that exec-entrypoint and run can make use of them.
Expand All @@ -29,6 +31,7 @@ import (
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
Expand Down Expand Up @@ -94,6 +97,23 @@ func main() {
TLSOpts: tlsOpts,
})

defaultNamespaces := map[string]cache.Config{}
operatorNamespace, err := getOperatorNamespace()
if err != nil {
setupLog.Error(err, "manager requires namespace to be registered for controllers to reconcile")
os.Exit(1)
}
// ensure we always cache items from operator namespace
defaultNamespaces[operatorNamespace] = cache.Config{}

watchNamespace, err := getWatchNamespace()
if err != nil {
setupLog.Error(err, "manager will only watch for resources in the operator deployed namespace")
} else {
for _, namespace := range strings.Split(watchNamespace, ",") {
defaultNamespaces[namespace] = cache.Config{}
}
}
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
Expand All @@ -116,6 +136,7 @@ func main() {
// if you are doing or is intended to do any operation such as perform cleanups
// after the manager stops then its usage might be unsafe.
// LeaderElectionReleaseOnCancel: true,
Cache: cache.Options{DefaultNamespaces: defaultNamespaces},
})
if err != nil {
setupLog.Error(err, "unable to start manager")
Expand Down Expand Up @@ -160,3 +181,25 @@ func main() {
os.Exit(1)
}
}

// getWatchNamespace returns the Namespace the operator should be watching for changes
func getWatchNamespace() (string, error) {
var watchNamespaceEnvVar = "WATCH_NAMESPACE"

ns, found := os.LookupEnv(watchNamespaceEnvVar)
if !found {
return "", fmt.Errorf("%s must be set", watchNamespaceEnvVar)
}
return ns, nil
}

// getOperatorNamespace returns the Namespace the operator is running
func getOperatorNamespace() (string, error) {
var operatorNamespaceEnvVar = "OPERATOR_NAMESPACE"

ns := os.Getenv(operatorNamespaceEnvVar)
if ns == "" {
return "", fmt.Errorf("%s must be set", operatorNamespaceEnvVar)
}
return ns, nil
}

0 comments on commit 37772c2

Please sign in to comment.