diff --git a/main.go b/main.go index bf94aaf00..b55cc740b 100644 --- a/main.go +++ b/main.go @@ -23,6 +23,7 @@ import ( datadoghqv1alpha1 "github.com/DataDog/datadog-operator/api/v1alpha1" "github.com/DataDog/datadog-operator/controllers" + "github.com/DataDog/datadog-operator/pkg/config" "github.com/DataDog/datadog-operator/pkg/controller/debug" "github.com/DataDog/datadog-operator/pkg/secrets" "github.com/DataDog/datadog-operator/pkg/version" @@ -88,14 +89,14 @@ func main() { // Dispatch CLI flags to each package secrets.SetSecretBackendCommand(secretBackendCommand) - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), config.ManagerOptionsWithNamespaces(setupLog, ctrl.Options{ Scheme: scheme, MetricsBindAddress: metricsAddr, HealthProbeBindAddress: ":8081", Port: 9443, LeaderElection: enableLeaderElection, LeaderElectionID: "datadog-operator-lock", - }) + })) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 000000000..f1aceae78 --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,56 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// This product includes software developed at Datadog (https://www.datadoghq.com/). +// Copyright 2016-2019 Datadog, Inc. + +package config + +import ( + "os" + "strings" + + "github.com/go-logr/logr" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/cache" +) + +const ( + // 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. + WatchNamespaceEnvVar = "WATCH_NAMESPACE" +) + +// GetWatchNamespaces returns the Namespaces the operator should be watching for changes +func GetWatchNamespaces() []string { + ns, found := os.LookupEnv(WatchNamespaceEnvVar) + if !found { + return nil + } + + // Add support for MultiNamespace set in WATCH_NAMESPACE (e.g ns1,ns2) + if strings.Contains(ns, ",") { + return strings.Split(ns, ",") + } + + return []string{ns} +} + +// ManagerOptionsWithNamespaces returns an updated Options with namespaces information +func ManagerOptionsWithNamespaces(logger logr.Logger, opt ctrl.Options) ctrl.Options { + namespaces := GetWatchNamespaces() + switch { + case len(namespaces) == 0: + logger.Info("Manager will watch and manage resources in all namespaces") + case len(namespaces) == 1: + logger.Info("Manager will be watching namespace", namespaces[0]) + opt.Namespace = namespaces[0] + case len(namespaces) > 1: + // configure cluster-scoped with MultiNamespacedCacheBuilder + logger.Info("Manager will be watching multiple namespaces", namespaces) + opt.Namespace = "" + opt.NewCache = cache.MultiNamespacedCacheBuilder(namespaces) + } + + return opt +}