@@ -19,6 +19,7 @@ package main
1919import (
2020 "crypto/tls"
2121 "flag"
22+ "fmt"
2223 "os"
2324
2425 // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
@@ -29,12 +30,15 @@ import (
2930 utilruntime "k8s.io/apimachinery/pkg/util/runtime"
3031 clientgoscheme "k8s.io/client-go/kubernetes/scheme"
3132 ctrl "sigs.k8s.io/controller-runtime"
33+ "sigs.k8s.io/controller-runtime/pkg/cache"
3234 "sigs.k8s.io/controller-runtime/pkg/healthz"
3335 "sigs.k8s.io/controller-runtime/pkg/log/zap"
3436 "sigs.k8s.io/controller-runtime/pkg/metrics/filters"
3537 metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
3638 "sigs.k8s.io/controller-runtime/pkg/webhook"
3739
40+ operatorsv1alpha1 "github.com/operator-framework/api/pkg/operators/v1alpha1"
41+
3842 apiv1beta1 "github.com/openstack-lightspeed/operator/api/v1beta1"
3943 "github.com/openstack-lightspeed/operator/internal/controller"
4044 // +kubebuilder:scaffold:imports
4852func init () {
4953 utilruntime .Must (clientgoscheme .AddToScheme (scheme ))
5054
55+ utilruntime .Must (operatorsv1alpha1 .AddToScheme (scheme ))
56+
5157 utilruntime .Must (apiv1beta1 .AddToScheme (scheme ))
5258 // +kubebuilder:scaffold:scheme
5359}
@@ -120,13 +126,23 @@ func main() {
120126 metricsServerOptions .FilterProvider = filters .WithAuthenticationAndAuthorization
121127 }
122128
129+ watchNamespace , err := getWatchNamespace ()
130+ if err != nil {
131+ setupLog .Error (err , "unable to get WatchNamespace, " +
132+ "the manager will watch and manage resources in all namespaces" )
133+ os .Exit (1 )
134+ }
135+
123136 mgr , err := ctrl .NewManager (ctrl .GetConfigOrDie (), ctrl.Options {
124137 Scheme : scheme ,
125138 Metrics : metricsServerOptions ,
126139 WebhookServer : webhookServer ,
127140 HealthProbeBindAddress : probeAddr ,
128141 LeaderElection : enableLeaderElection ,
129142 LeaderElectionID : "c83b0a4f.lightspeed.openstack.org" ,
143+ Cache : cache.Options {
144+ DefaultNamespaces : map [string ]cache.Config {watchNamespace : {}},
145+ },
130146 // LeaderElectionReleaseOnCancel defines if the leader should step down voluntarily
131147 // when the Manager ends. This requires the binary to immediately end when the
132148 // Manager is stopped, otherwise, this setting is unsafe. Setting this significantly
@@ -171,3 +187,17 @@ func main() {
171187 os .Exit (1 )
172188 }
173189}
190+
191+ // getWatchNamespace returns the Namespace the operator should be watching for changes
192+ func getWatchNamespace () (string , error ) {
193+ // WatchNamespaceEnvVar is the constant for env variable WATCH_NAMESPACE
194+ // which specifies the Namespace to watch.
195+ // An empty value means the operator is running with cluster scope.
196+ var watchNamespaceEnvVar = "WATCH_NAMESPACE"
197+
198+ ns , found := os .LookupEnv (watchNamespaceEnvVar )
199+ if ! found {
200+ return "" , fmt .Errorf ("%s must be set" , watchNamespaceEnvVar )
201+ }
202+ return ns , nil
203+ }
0 commit comments