refactor: migrate reloader command to use new config package

This commit is contained in:
TheiLLeniumStudios
2025-12-28 08:47:51 +01:00
parent b9a7b8997c
commit dce45a454a
3 changed files with 118 additions and 52 deletions
+85 -29
View File
@@ -2,13 +2,12 @@ package cmd
import (
"context"
"errors"
"fmt"
"net/http"
_ "net/http/pprof"
"os"
"strings"
"github.com/stakater/Reloader/internal/pkg/config"
"github.com/stakater/Reloader/internal/pkg/constants"
"github.com/stakater/Reloader/internal/pkg/leadership"
@@ -24,8 +23,15 @@ import (
"github.com/stakater/Reloader/pkg/kube"
)
// cfg holds the configuration for this reloader instance.
// It is populated by flag parsing and used throughout the application.
var cfg *config.Config
// NewReloaderCommand starts the reloader controller
func NewReloaderCommand() *cobra.Command {
// Create config with defaults
cfg = config.NewDefault()
cmd := &cobra.Command{
Use: "reloader",
Short: "A watcher for your Kubernetes cluster",
@@ -33,29 +39,29 @@ func NewReloaderCommand() *cobra.Command {
Run: startReloader,
}
// options
util.ConfigureReloaderFlags(cmd)
// Bind flags to the new config package
config.BindFlags(cmd.PersistentFlags(), cfg)
return cmd
}
func validateFlags(*cobra.Command, []string) error {
// Ensure the reload strategy is one of the following...
var validReloadStrategy bool
valid := []string{constants.EnvVarsReloadStrategy, constants.AnnotationsReloadStrategy}
for _, s := range valid {
if s == options.ReloadStrategy {
validReloadStrategy = true
}
// Apply post-parse flag processing (converts string flags to proper types)
if err := config.ApplyFlags(cfg); err != nil {
return fmt.Errorf("applying flags: %w", err)
}
if !validReloadStrategy {
err := fmt.Sprintf("%s must be one of: %s", constants.ReloadStrategyFlag, strings.Join(valid, ", "))
return errors.New(err)
// Validate the configuration
if err := cfg.Validate(); err != nil {
return fmt.Errorf("validating config: %w", err)
}
// Sync new config to old options package for backward compatibility
// This bridge allows existing code to keep working during migration
syncConfigToOptions(cfg)
// Validate that HA options are correct
if options.EnableHA {
if cfg.EnableHA {
if err := validateHAEnvs(); err != nil {
return err
}
@@ -64,6 +70,58 @@ func validateFlags(*cobra.Command, []string) error {
return nil
}
// syncConfigToOptions bridges the new Config struct to the old options package.
// This allows existing code to continue working during the migration period.
// TODO: Remove this once all code is migrated to use Config directly.
func syncConfigToOptions(cfg *config.Config) {
options.AutoReloadAll = cfg.AutoReloadAll
options.ConfigmapUpdateOnChangeAnnotation = cfg.Annotations.ConfigmapReload
options.SecretUpdateOnChangeAnnotation = cfg.Annotations.SecretReload
options.ReloaderAutoAnnotation = cfg.Annotations.Auto
options.ConfigmapReloaderAutoAnnotation = cfg.Annotations.ConfigmapAuto
options.SecretReloaderAutoAnnotation = cfg.Annotations.SecretAuto
options.IgnoreResourceAnnotation = cfg.Annotations.Ignore
options.ConfigmapExcludeReloaderAnnotation = cfg.Annotations.ConfigmapExclude
options.SecretExcludeReloaderAnnotation = cfg.Annotations.SecretExclude
options.AutoSearchAnnotation = cfg.Annotations.Search
options.SearchMatchAnnotation = cfg.Annotations.Match
options.RolloutStrategyAnnotation = cfg.Annotations.RolloutStrategy
options.PauseDeploymentAnnotation = cfg.Annotations.PausePeriod
options.PauseDeploymentTimeAnnotation = cfg.Annotations.PausedAt
options.LogFormat = cfg.LogFormat
options.LogLevel = cfg.LogLevel
options.WebhookUrl = cfg.WebhookURL
options.ResourcesToIgnore = cfg.IgnoredResources
options.WorkloadTypesToIgnore = cfg.IgnoredWorkloads
options.NamespacesToIgnore = cfg.IgnoredNamespaces
options.NamespaceSelectors = cfg.NamespaceSelectorStrings
options.ResourceSelectors = cfg.ResourceSelectorStrings
options.EnableHA = cfg.EnableHA
options.SyncAfterRestart = cfg.SyncAfterRestart
options.EnablePProf = cfg.EnablePProf
options.PProfAddr = cfg.PProfAddr
// Convert ReloadStrategy to string for old options
options.ReloadStrategy = string(cfg.ReloadStrategy)
// Convert bool flags to string for old options (IsArgoRollouts, ReloadOnCreate, ReloadOnDelete)
if cfg.ArgoRolloutsEnabled {
options.IsArgoRollouts = "true"
} else {
options.IsArgoRollouts = "false"
}
if cfg.ReloadOnCreate {
options.ReloadOnCreate = "true"
} else {
options.ReloadOnCreate = "false"
}
if cfg.ReloadOnDelete {
options.ReloadOnDelete = "true"
} else {
options.ReloadOnDelete = "false"
}
}
func configureLogging(logFormat, logLevel string) error {
switch logFormat {
case "json":
@@ -104,7 +162,7 @@ func getHAEnvs() (string, string) {
func startReloader(cmd *cobra.Command, args []string) {
common.GetCommandLineOptions()
err := configureLogging(options.LogFormat, options.LogLevel)
err := configureLogging(cfg.LogFormat, cfg.LogLevel)
if err != nil {
logrus.Warn(err)
}
@@ -124,12 +182,10 @@ func startReloader(cmd *cobra.Command, args []string) {
logrus.Fatal(err)
}
ignoredResourcesList, err := util.GetIgnoredResourcesList()
if err != nil {
logrus.Fatal(err)
}
// Use config's IgnoredResources (already validated and normalized to lowercase)
ignoredResourcesList := util.List(cfg.IgnoredResources)
ignoredNamespacesList := options.NamespacesToIgnore
ignoredNamespacesList := cfg.IgnoredNamespaces
namespaceLabelSelector := ""
if isGlobal {
@@ -152,7 +208,7 @@ func startReloader(cmd *cobra.Command, args []string) {
logrus.Warnf("resource-label-selector is set, will only detect changes on resources with these labels: %s.", resourceLabelSelector)
}
if options.WebhookUrl != "" {
if cfg.WebhookURL != "" {
logrus.Warnf("webhook-url is set, will only send webhook, no resources will be reloaded")
}
@@ -171,8 +227,8 @@ func startReloader(cmd *cobra.Command, args []string) {
controllers = append(controllers, c)
// If HA is enabled we only run the controller when
if options.EnableHA {
// If HA is enabled we only run the controller when we're the leader
if cfg.EnableHA {
continue
}
// Now let's start the controller
@@ -183,7 +239,7 @@ func startReloader(cmd *cobra.Command, args []string) {
}
// Run leadership election
if options.EnableHA {
if cfg.EnableHA {
podName, podNamespace := getHAEnvs()
lock := leadership.GetNewLock(clientset.CoordinationV1(), constants.LockName, podName, podNamespace)
ctx, cancel := context.WithCancel(context.Background())
@@ -193,17 +249,17 @@ func startReloader(cmd *cobra.Command, args []string) {
common.PublishMetaInfoConfigmap(clientset)
if options.EnablePProf {
if cfg.EnablePProf {
go startPProfServer()
}
leadership.SetupLivenessEndpoint()
logrus.Fatal(http.ListenAndServe(constants.DefaultHttpListenAddr, nil))
logrus.Fatal(http.ListenAndServe(cfg.MetricsAddr, nil))
}
func startPProfServer() {
logrus.Infof("Starting pprof server on %s", options.PProfAddr)
if err := http.ListenAndServe(options.PProfAddr, nil); err != nil {
logrus.Infof("Starting pprof server on %s", cfg.PProfAddr)
if err := http.ListenAndServe(cfg.PProfAddr, nil); err != nil {
logrus.Errorf("Failed to start pprof server: %v", err)
}
}
+4
View File
@@ -71,6 +71,10 @@ type Config struct {
NamespaceSelectors []labels.Selector
ResourceSelectors []labels.Selector
// Raw selector strings (for backward compatibility with old code)
NamespaceSelectorStrings []string
ResourceSelectorStrings []string
// Logging configuration
LogFormat string // "json" or "" for default
LogLevel string // trace, debug, info, warning, error, fatal, panic
+29 -23
View File
@@ -32,8 +32,8 @@ func BindFlags(fs *pflag.FlagSet, cfg *Config) {
fs.StringVar((*string)(&cfg.ReloadStrategy), "reload-strategy", string(cfg.ReloadStrategy),
"Strategy for triggering workload restart: 'env-vars' (default, GitOps friendly) or 'annotations'")
// Argo Rollouts
fs.StringVar(&fv.isArgoRollouts, "is-argo-rollouts", "false",
// Argo Rollouts (note: capital A in Argo for backward compatibility)
fs.StringVar(&fv.isArgoRollouts, "is-Argo-Rollouts", "false",
"Enable Argo Rollouts support (true/false)")
// Event watching
@@ -54,11 +54,11 @@ func BindFlags(fs *pflag.FlagSet, cfg *Config) {
fs.StringVar(&cfg.WebhookURL, "webhook-url", cfg.WebhookURL,
"URL to send notification instead of triggering reload")
// Filtering - resources
// Filtering - resources (use StringVar not StringSliceVar for simpler parsing)
fs.StringVar(&fv.ignoredResources, "resources-to-ignore", "",
"Comma-separated list of configmap/secret names to ignore (case-insensitive)")
fs.StringVar(&fv.ignoredWorkloads, "workload-types-to-ignore", "",
"Comma-separated list of workload types to ignore (Deployment, DaemonSet, StatefulSet)")
"Comma-separated list of resources to ignore (valid options: 'configMaps' or 'secrets')")
fs.StringVar(&fv.ignoredWorkloads, "ignored-workload-types", "",
"Comma-separated list of workload types to ignore (valid options: 'jobs', 'cronjobs', or both)")
fs.StringVar(&fv.ignoredNamespaces, "namespaces-to-ignore", "",
"Comma-separated list of namespaces to ignore")
@@ -84,23 +84,25 @@ func BindFlags(fs *pflag.FlagSet, cfg *Config) {
fs.StringVar(&cfg.PProfAddr, "pprof-addr", cfg.PProfAddr,
"Address for pprof server")
// Annotation customization
// Annotation customization (flag names match v1 for backward compatibility)
fs.StringVar(&cfg.Annotations.Auto, "auto-annotation", cfg.Annotations.Auto,
"Custom annotation for auto-reload")
"Annotation to detect changes in secrets/configmaps")
fs.StringVar(&cfg.Annotations.ConfigmapAuto, "configmap-auto-annotation", cfg.Annotations.ConfigmapAuto,
"Custom annotation for configmap auto-reload")
"Annotation to detect changes in configmaps")
fs.StringVar(&cfg.Annotations.SecretAuto, "secret-auto-annotation", cfg.Annotations.SecretAuto,
"Custom annotation for secret auto-reload")
fs.StringVar(&cfg.Annotations.ConfigmapReload, "configmap-reload-annotation", cfg.Annotations.ConfigmapReload,
"Custom annotation for configmap reload")
fs.StringVar(&cfg.Annotations.SecretReload, "secret-reload-annotation", cfg.Annotations.SecretReload,
"Custom annotation for secret reload")
fs.StringVar(&cfg.Annotations.Ignore, "ignore-annotation", cfg.Annotations.Ignore,
"Custom annotation for ignoring resources")
fs.StringVar(&cfg.Annotations.Search, "search-annotation", cfg.Annotations.Search,
"Custom annotation for search-based matching")
fs.StringVar(&cfg.Annotations.Match, "match-annotation", cfg.Annotations.Match,
"Custom annotation for match-based matching")
"Annotation to detect changes in secrets")
fs.StringVar(&cfg.Annotations.ConfigmapReload, "configmap-annotation", cfg.Annotations.ConfigmapReload,
"Annotation to detect changes in configmaps, specified by name")
fs.StringVar(&cfg.Annotations.SecretReload, "secret-annotation", cfg.Annotations.SecretReload,
"Annotation to detect changes in secrets, specified by name")
fs.StringVar(&cfg.Annotations.Search, "auto-search-annotation", cfg.Annotations.Search,
"Annotation to detect changes in configmaps or secrets tagged with special match annotation")
fs.StringVar(&cfg.Annotations.Match, "search-match-annotation", cfg.Annotations.Match,
"Annotation to mark secrets or configmaps to match the search")
fs.StringVar(&cfg.Annotations.PausePeriod, "pause-deployment-annotation", cfg.Annotations.PausePeriod,
"Annotation to define the time period to pause a deployment after a configmap/secret change")
fs.StringVar(&cfg.Annotations.PausedAt, "pause-deployment-time-annotation", cfg.Annotations.PausedAt,
"Annotation to indicate when a deployment was paused by Reloader")
// Watched namespace (for single-namespace mode)
fs.StringVar(&cfg.WatchedNamespace, "watch-namespace", cfg.WatchedNamespace,
@@ -120,13 +122,17 @@ func ApplyFlags(cfg *Config) error {
cfg.IgnoredWorkloads = splitAndTrim(fv.ignoredWorkloads)
cfg.IgnoredNamespaces = splitAndTrim(fv.ignoredNamespaces)
// Parse selectors
// Store raw selector strings (for backward compatibility)
cfg.NamespaceSelectorStrings = splitAndTrim(fv.namespaceSelectors)
cfg.ResourceSelectorStrings = splitAndTrim(fv.resourceSelectors)
// Parse selectors into labels.Selector
var err error
cfg.NamespaceSelectors, err = ParseSelectors(splitAndTrim(fv.namespaceSelectors))
cfg.NamespaceSelectors, err = ParseSelectors(cfg.NamespaceSelectorStrings)
if err != nil {
return err
}
cfg.ResourceSelectors, err = ParseSelectors(splitAndTrim(fv.resourceSelectors))
cfg.ResourceSelectors, err = ParseSelectors(cfg.ResourceSelectorStrings)
if err != nil {
return err
}