Skip to content

Commit

Permalink
refactor: Move scope helper functions out of main
Browse files Browse the repository at this point in the history
refactor: only call GetConfigOrDie once
  • Loading branch information
Baarsgaard committed Jan 21, 2025
1 parent 8bdd140 commit 2cce9ca
Showing 1 changed file with 65 additions and 60 deletions.
125 changes: 65 additions & 60 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
uberzap "go.uber.org/zap"
"go.uber.org/zap/zapcore"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
"sigs.k8s.io/controller-runtime/pkg/webhook"

"k8s.io/apimachinery/pkg/fields"
Expand All @@ -38,6 +37,7 @@ import (

routev1 "github.com/openshift/api/route/v1"
discovery2 "k8s.io/client-go/discovery"
"k8s.io/client-go/rest"

// 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 Down Expand Up @@ -106,6 +106,19 @@ func main() {
watchNamespace, _ := os.LookupEnv(watchNamespaceEnvVar)
watchNamespaceSelector, _ := os.LookupEnv(watchNamespaceEnvSelector)

// Fetch k8s api credentials and detect platform
restConfig := ctrl.GetConfigOrDie()
autodetect, err := autodetect.New(restConfig)
if err != nil {
setupLog.Error(err, "failed to setup auto-detect routine")
os.Exit(1)
}
isOpenShift, err := autodetect.IsOpenshift()
if err != nil {
setupLog.Error(err, "unable to detect the platform")
os.Exit(1)
}

controllerOptions := ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
Expand All @@ -120,50 +133,6 @@ func main() {
PprofBindAddress: pprofAddr,
}

getNamespaceConfig := func(namespaces string) map[string]cache.Config {
defaultNamespaces := map[string]cache.Config{}
for _, v := range strings.Split(namespaces, ",") {
// Generate a mapping of namespaces to label/field selectors, set to Everything() to enable matching all
// instances in all namespaces from watchNamespace to be controlled by the operator
// this is the default behavior of the operator on v5, if you require finer grained control over this
// please file an issue in the grafana-operator/grafana-operator GH project
defaultNamespaces[v] = cache.Config{
LabelSelector: labels.Everything(), // Match any labels
FieldSelector: fields.Everything(), // Match any fields
Transform: nil,
UnsafeDisableDeepCopy: nil,
}
}
return defaultNamespaces
}
getNamespaceConfigSelector := func(selector string) map[string]cache.Config {
cl, err := client.New(config.GetConfigOrDie(), client.Options{})
if err != nil {
setupLog.Error(err, "Failed to get watch namespaces")
}
nsList := &corev1.NamespaceList{}
listOpts := []client.ListOption{
client.MatchingLabels(map[string]string{strings.Split(selector, ":")[0]: strings.Split(selector, ":")[1]}),
}
err = cl.List(context.Background(), nsList, listOpts...)
if err != nil {
setupLog.Error(err, "Failed to get watch namespaces")
}
defaultNamespaces := map[string]cache.Config{}
for _, v := range nsList.Items {
// Generate a mapping of namespaces to label/field selectors, set to Everything() to enable matching all
// instances in all namespaces from watchNamespace to be controlled by the operator
// this is the default behavior of the operator on v5, if you require finer grained control over this
// please file an issue in the grafana-operator/grafana-operator GH project
defaultNamespaces[v.Name] = cache.Config{
LabelSelector: labels.Everything(), // Match any labels
FieldSelector: fields.Everything(), // Match any fields
Transform: nil,
UnsafeDisableDeepCopy: nil,
}
}
return defaultNamespaces
}
switch {
case strings.Contains(watchNamespace, ","):
// multi namespace scoped
Expand All @@ -175,7 +144,7 @@ func main() {
setupLog.Info("operator running in namespace scoped mode", "namespace", watchNamespace)
case strings.Contains(watchNamespaceSelector, ":"):
// namespace scoped
controllerOptions.Cache.DefaultNamespaces = getNamespaceConfigSelector(watchNamespaceSelector)
controllerOptions.Cache.DefaultNamespaces = getNamespaceConfigSelector(watchNamespaceSelector, restConfig)
setupLog.Info("operator running in namespace scoped mode using namespace selector", "namespace", watchNamespace)

case watchNamespace == "" && watchNamespaceSelector == "":
Expand All @@ -186,29 +155,17 @@ func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGPIPE)
defer stop()

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), controllerOptions)
mgr, err := ctrl.NewManager(restConfig, controllerOptions)
if err != nil {
setupLog.Error(err, "unable to create new manager")
os.Exit(1) //nolint
}

restConfig := ctrl.GetConfigOrDie()
autodetect, err := autodetect.New(restConfig)
if err != nil {
setupLog.Error(err, "failed to setup auto-detect routine")
os.Exit(1)
}
isOpenShift, err := autodetect.IsOpenshift()
if err != nil {
setupLog.Error(err, "unable to detect the platform")
os.Exit(1)
}

if err = (&controllers.GrafanaReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
IsOpenShift: isOpenShift,
Discovery: discovery2.NewDiscoveryClientForConfigOrDie(ctrl.GetConfigOrDie()),
Discovery: discovery2.NewDiscoveryClientForConfigOrDie(restConfig),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Grafana")
os.Exit(1)
Expand Down Expand Up @@ -282,3 +239,51 @@ func main() {
<-ctx.Done()
setupLog.Info("SIGTERM request gotten, shutting down operator")
}

func getNamespaceConfig(namespaces string) map[string]cache.Config {
defaultNamespaces := map[string]cache.Config{}
for _, v := range strings.Split(namespaces, ",") {
// Generate a mapping of namespaces to label/field selectors, set to Everything() to enable matching all
// instances in all namespaces from watchNamespace to be controlled by the operator
// this is the default behavior of the operator on v5, if you require finer grained control over this
// please file an issue in the grafana-operator/grafana-operator GH project
defaultNamespaces[v] = cache.Config{
LabelSelector: labels.Everything(), // Match any labels
FieldSelector: fields.Everything(), // Match any fields
Transform: nil,
UnsafeDisableDeepCopy: nil,
}
}
return defaultNamespaces
}

func getNamespaceConfigSelector(selector string, restConfig *rest.Config) map[string]cache.Config {
cl, err := client.New(restConfig, client.Options{})
if err != nil {
setupLog.Error(err, "Failed to get watch namespaces")
}

nsList := &corev1.NamespaceList{}
listOpts := []client.ListOption{
client.MatchingLabels(map[string]string{strings.Split(selector, ":")[0]: strings.Split(selector, ":")[1]}),
}
err = cl.List(context.Background(), nsList, listOpts...)
if err != nil {
setupLog.Error(err, "Failed to get watch namespaces")
}

defaultNamespaces := map[string]cache.Config{}
for _, v := range nsList.Items {
// Generate a mapping of namespaces to label/field selectors, set to Everything() to enable matching all
// instances in all namespaces from watchNamespace to be controlled by the operator
// this is the default behavior of the operator on v5, if you require finer grained control over this
// please file an issue in the grafana-operator/grafana-operator GH project
defaultNamespaces[v.Name] = cache.Config{
LabelSelector: labels.Everything(), // Match any labels
FieldSelector: fields.Everything(), // Match any fields
Transform: nil,
UnsafeDisableDeepCopy: nil,
}
}
return defaultNamespaces
}

0 comments on commit 2cce9ca

Please sign in to comment.