From c12e4a353deecda196ac79fb646a652074114c03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Nussbaumer?= Date: Thu, 30 Dec 2021 10:41:00 +0100 Subject: [PATCH] chore: refactoring --- cmd/kubelet-csr-approver/main.go | 118 +--------------- internal/cmd/cmd.go | 130 ++++++++++++++++++ .../controller}/csr_controller.go | 0 .../controller}/csr_controller_test.go | 0 .../controller}/provider_specific_checks.go | 0 .../controller}/regex_ip_checks.go | 0 .../controller}/testenv_setup_test.go | 3 +- {controller => internal/controller}/utils.go | 0 8 files changed, 135 insertions(+), 116 deletions(-) create mode 100644 internal/cmd/cmd.go rename {controller => internal/controller}/csr_controller.go (100%) rename {controller => internal/controller}/csr_controller_test.go (100%) rename {controller => internal/controller}/provider_specific_checks.go (100%) rename {controller => internal/controller}/regex_ip_checks.go (100%) rename {controller => internal/controller}/testenv_setup_test.go (98%) rename {controller => internal/controller}/utils.go (100%) diff --git a/cmd/kubelet-csr-approver/main.go b/cmd/kubelet-csr-approver/main.go index 742ad31..e5f5810 100644 --- a/cmd/kubelet-csr-approver/main.go +++ b/cmd/kubelet-csr-approver/main.go @@ -1,124 +1,12 @@ package main import ( - "flag" - "fmt" - "net" "os" - "regexp" - "strconv" - "go.uber.org/zap/zapcore" - clientset "k8s.io/client-go/kubernetes" - - _ "k8s.io/client-go/plugin/pkg/client/auth" //TODO: remove when used in-cluster - - "github.com/go-logr/zapr" - "github.com/postfinance/flash" - ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/healthz" - - "github.com/postfinance/kubelet-csr-approver/controller" -) - -// ProviderRegexEnvvarName holds the name of the env variable containing the provider-spefic regex -const ProviderRegexEnvvarName string = "PROVIDER_REGEX" - -// MaxExpirationSecEnvVarName holds the name of the env variable defining the maximum seconds a CSR can request -const MaxExpirationSecEnvVarName string = "MAX_EXPIRATION_SEC" - -//nolint:gochecknoglobals //this vars are set on build by goreleaser -var ( - commit = "12345678" - ref = "refs/refname" + "github.com/postfinance/kubelet-csr-approver/internal/cmd" ) func main() { - flashLogger := flash.New() - - var metricsAddr, probeAddr string - - var logLevel int - - flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") - flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") - flag.IntVar(&logLevel, "level", 0, "level ranges from -5 (Fatal) to 10 (Verbose)") - flag.Parse() - - if logLevel < -5 || logLevel > 10 { - flashLogger.Fatal(fmt.Errorf("log level should be between -5 and 10 (included)")) - } - - logLevel *= -1 // we inverse the level for the logging behavior between zap and logr.Logger to match - flashLogger.SetLevel(zapcore.Level(logLevel)) - z := zapr.NewLogger(flashLogger.Desugar()) - - z.V(0).Info("Kubelet-CSR-Approver controller starting.", "commit", commit, "ref", ref) - - var regexEnvVar string - if regexEnvVar = os.Getenv(ProviderRegexEnvvarName); regexEnvVar == "" { - err := fmt.Errorf("the provider-spefic regex must be specified in the %s env variable", ProviderRegexEnvvarName) - z.Error(err, ProviderRegexEnvvarName+" not set") - os.Exit(1) - } - - providerRegexp := regexp.MustCompile(regexEnvVar) - maxExpirationSecEnvVar := os.Getenv(MaxExpirationSecEnvVarName) - - var maxExpirationSeconds int32 = 367 * 24 * 3600 - - if maxExpirationSecEnvVar != "" { - parsedMaxSec, err := strconv.ParseInt(maxExpirationSecEnvVar, 10, 32) - parsedMaxSecInt32 := int32(parsedMaxSec) - - if err != nil { - z.Error(err, "could not parse the MAX_EXPIRATION_SEC env var") - os.Exit(1) - } - - if parsedMaxSecInt32 > maxExpirationSeconds { - err := fmt.Errorf("the maximum expiration seconds env variable cannot be greater than 367 days (= %d seconds)", maxExpirationSeconds) - z.Error(err, "reduce the maxExpirationSec value") - os.Exit(1) - } - - maxExpirationSeconds = parsedMaxSecInt32 - } - - ctrl.SetLogger(z) - mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ - MetricsBindAddress: metricsAddr, - HealthProbeBindAddress: probeAddr, - }) - - if err != nil { - z.Error(err, "unable to start manager") - os.Exit(1) - } - - csrController := controller.CertificateSigningRequestReconciler{ - ClientSet: clientset.NewForConfigOrDie(mgr.GetConfig()), - Client: mgr.GetClient(), - Scheme: mgr.GetScheme(), - ProviderRegexp: providerRegexp.MatchString, - MaxExpirationSeconds: maxExpirationSeconds, - Resolver: net.DefaultResolver, - } - - if err = csrController.SetupWithManager(mgr); err != nil { - z.Error(err, "unable to create controller", "controller", "CertificateSigningRequest") - os.Exit(1) - } - - if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { - z.Error(err, "unable to set up health check") - os.Exit(1) - } - - z.V(1).Info("starting controller-runtime manager") - - if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { - z.Error(err, "problem running manager") - os.Exit(1) - } + code := cmd.Run() + os.Exit(code) } diff --git a/internal/cmd/cmd.go b/internal/cmd/cmd.go new file mode 100644 index 0000000..9223d78 --- /dev/null +++ b/internal/cmd/cmd.go @@ -0,0 +1,130 @@ +// Package cmd - command line initialization +package cmd + +import ( + "flag" + "fmt" + "net" + "os" + "regexp" + "strconv" + + "go.uber.org/zap/zapcore" + clientset "k8s.io/client-go/kubernetes" + + _ "k8s.io/client-go/plugin/pkg/client/auth" //TODO: remove when used in-cluster + + "github.com/go-logr/zapr" + "github.com/postfinance/flash" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/healthz" + + "github.com/postfinance/kubelet-csr-approver/internal/controller" +) + +// ProviderRegexEnvvarName holds the name of the env variable containing the provider-spefic regex +const ProviderRegexEnvvarName string = "PROVIDER_REGEX" + +// MaxExpirationSecEnvVarName holds the name of the env variable defining the maximum seconds a CSR can request +const MaxExpirationSecEnvVarName string = "MAX_EXPIRATION_SEC" + +//nolint:gochecknoglobals //this vars are set on build by goreleaser +var ( + commit = "12345678" + ref = "refs/refname" +) + +// Run encapsulates all settings related to kubelet-csr-approver +func Run() int { + flashLogger := flash.New() + + var metricsAddr, probeAddr string + + var logLevel int + + flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") + flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") + flag.IntVar(&logLevel, "level", 0, "level ranges from -5 (Fatal) to 10 (Verbose)") + flag.Parse() + + if logLevel < -5 || logLevel > 10 { + flashLogger.Fatal(fmt.Errorf("log level should be between -5 and 10 (included)")) + } + + logLevel *= -1 // we inverse the level for the logging behavior between zap and logr.Logger to match + flashLogger.SetLevel(zapcore.Level(logLevel)) + z := zapr.NewLogger(flashLogger.Desugar()) + + z.V(0).Info("Kubelet-CSR-Approver controller starting.", "commit", commit, "ref", ref) + + var regexEnvVar string + if regexEnvVar = os.Getenv(ProviderRegexEnvvarName); regexEnvVar == "" { + err := fmt.Errorf("the provider-spefic regex must be specified in the %s env variable", ProviderRegexEnvvarName) + z.Error(err, ProviderRegexEnvvarName+" not set") + + return 1 + } + + providerRegexp := regexp.MustCompile(regexEnvVar) + maxExpirationSecEnvVar := os.Getenv(MaxExpirationSecEnvVarName) + + var maxExpirationSeconds int32 = 367 * 24 * 3600 + + if maxExpirationSecEnvVar != "" { + parsedMaxSec, err := strconv.ParseInt(maxExpirationSecEnvVar, 10, 32) + parsedMaxSecInt32 := int32(parsedMaxSec) + + if err != nil { + z.Error(err, "could not parse the MAX_EXPIRATION_SEC env var") + return 1 + } + + if parsedMaxSecInt32 > maxExpirationSeconds { + err := fmt.Errorf("the maximum expiration seconds env variable cannot be greater than 367 days (= %d seconds)", maxExpirationSeconds) + z.Error(err, "reduce the maxExpirationSec value") + + return 1 + } + + maxExpirationSeconds = parsedMaxSecInt32 + } + + ctrl.SetLogger(z) + mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{ + MetricsBindAddress: metricsAddr, + HealthProbeBindAddress: probeAddr, + }) + + if err != nil { + z.Error(err, "unable to start manager") + return 1 + } + + csrController := controller.CertificateSigningRequestReconciler{ + ClientSet: clientset.NewForConfigOrDie(mgr.GetConfig()), + Client: mgr.GetClient(), + Scheme: mgr.GetScheme(), + ProviderRegexp: providerRegexp.MatchString, + MaxExpirationSeconds: maxExpirationSeconds, + Resolver: net.DefaultResolver, + } + + if err = csrController.SetupWithManager(mgr); err != nil { + z.Error(err, "unable to create controller", "controller", "CertificateSigningRequest") + return 1 + } + + if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { + z.Error(err, "unable to set up health check") + return 1 + } + + z.V(1).Info("starting controller-runtime manager") + + if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { + z.Error(err, "problem running manager") + return 1 + } + + return 0 +} diff --git a/controller/csr_controller.go b/internal/controller/csr_controller.go similarity index 100% rename from controller/csr_controller.go rename to internal/controller/csr_controller.go diff --git a/controller/csr_controller_test.go b/internal/controller/csr_controller_test.go similarity index 100% rename from controller/csr_controller_test.go rename to internal/controller/csr_controller_test.go diff --git a/controller/provider_specific_checks.go b/internal/controller/provider_specific_checks.go similarity index 100% rename from controller/provider_specific_checks.go rename to internal/controller/provider_specific_checks.go diff --git a/controller/regex_ip_checks.go b/internal/controller/regex_ip_checks.go similarity index 100% rename from controller/regex_ip_checks.go rename to internal/controller/regex_ip_checks.go diff --git a/controller/testenv_setup_test.go b/internal/controller/testenv_setup_test.go similarity index 98% rename from controller/testenv_setup_test.go rename to internal/controller/testenv_setup_test.go index 8ab4623..35e0fdf 100644 --- a/controller/testenv_setup_test.go +++ b/internal/controller/testenv_setup_test.go @@ -32,7 +32,8 @@ import ( "log" mockdns "github.com/foxcpp/go-mockdns" - "github.com/postfinance/kubelet-csr-approver/controller" + "github.com/postfinance/kubelet-csr-approver/internal/controller" + "github.com/thanhpk/randstr" certificates_v1 "k8s.io/api/certificates/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/controller/utils.go b/internal/controller/utils.go similarity index 100% rename from controller/utils.go rename to internal/controller/utils.go