feat(config): swap viper and cobra for config (#684)

This commit is contained in:
nils måsén 2020-12-21 15:17:45 +01:00 committed by GitHub
parent cbe9ab87fa
commit ff8cb884a0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 229 additions and 255 deletions

View file

@ -1,9 +1,10 @@
package cmd
import (
"fmt"
"github.com/spf13/viper"
"os"
"os/signal"
"strconv"
"syscall"
"time"
@ -21,17 +22,9 @@ import (
)
var (
client container.Client
scheduleSpec string
cleanup bool
noRestart bool
monitorOnly bool
enableLabel bool
notifier *notifications.Notifier
timeout time.Duration
lifecycleHooks bool
rollingRestart bool
scope string
client container.Client
notifier *notifications.Notifier
c flags.WatchConfig
)
var rootCmd = &cobra.Command{
@ -46,10 +39,11 @@ More information available at https://github.com/containrrr/watchtower/.
}
func init() {
flags.SetDefaults()
flags.RegisterDockerFlags(rootCmd)
flags.RegisterSystemFlags(rootCmd)
flags.RegisterNotificationFlags(rootCmd)
flags.SetEnvBindings()
flags.BindViperFlags(rootCmd)
}
// Execute the root func and exit in case of errors
@ -60,10 +54,10 @@ func Execute() {
}
// PreRun is a lifecycle hook that runs before the command is executed.
func PreRun(cmd *cobra.Command, args []string) {
f := cmd.PersistentFlags()
func PreRun(cmd *cobra.Command, _ []string) {
if enabled, _ := f.GetBool("no-color"); enabled {
// First apply all the settings that affect the output
if viper.GetBool("no-color") {
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
})
@ -74,75 +68,55 @@ func PreRun(cmd *cobra.Command, args []string) {
})
}
if enabled, _ := f.GetBool("debug"); enabled {
if viper.GetBool("debug") {
log.SetLevel(log.DebugLevel)
}
if enabled, _ := f.GetBool("trace"); enabled {
if viper.GetBool("trace") {
log.SetLevel(log.TraceLevel)
}
pollingSet := f.Changed("interval")
schedule, _ := f.GetString("schedule")
cronLen := len(schedule)
interval := viper.GetInt("interval")
if pollingSet && cronLen > 0 {
log.Fatal("Only schedule or interval can be defined, not both.")
} else if cronLen > 0 {
scheduleSpec, _ = f.GetString("schedule")
} else {
interval, _ := f.GetInt("interval")
scheduleSpec = "@every " + strconv.Itoa(interval) + "s"
// If empty, set schedule using interval helper value
if viper.GetString("schedule") == "" {
viper.Set("schedule", fmt.Sprintf("@every %ds", interval))
} else if interval != flags.DefaultInterval {
log.Fatal("only schedule or interval can be defined, not both")
}
flags.GetSecretsFromFiles(cmd)
cleanup, noRestart, monitorOnly, timeout = flags.ReadFlags(cmd)
// Then load the rest of the settings
err := viper.Unmarshal(&c)
if err != nil {
log.Fatalf("unable to decode into struct, %v", err)
}
if timeout < 0 {
flags.GetSecretsFromFiles()
if c.Timeout <= 0 {
log.Fatal("Please specify a positive value for timeout value.")
}
enableLabel, _ = f.GetBool("label-enable")
lifecycleHooks, _ = f.GetBool("enable-lifecycle-hooks")
rollingRestart, _ = f.GetBool("rolling-restart")
scope, _ = f.GetString("scope")
log.Debugf("Using scope %v", c.Scope)
log.Debug(scope)
// configure environment vars for client
err := flags.EnvConfig(cmd)
if err != nil {
log.Fatal(err)
if err = flags.EnvConfig(); err != nil {
log.Fatalf("failed to setup environment variables: %v", err)
}
noPull, _ := f.GetBool("no-pull")
includeStopped, _ := f.GetBool("include-stopped")
includeRestarting, _ := f.GetBool("include-restarting")
reviveStopped, _ := f.GetBool("revive-stopped")
removeVolumes, _ := f.GetBool("remove-volumes")
if monitorOnly && noPull {
if c.MonitorOnly && c.NoPull {
log.Warn("Using `WATCHTOWER_NO_PULL` and `WATCHTOWER_MONITOR_ONLY` simultaneously might lead to no action being taken at all. If this is intentional, you may safely ignore this message.")
}
client = container.NewClient(
!noPull,
includeStopped,
reviveStopped,
removeVolumes,
includeRestarting,
)
client = container.NewClient(&c)
notifier = notifications.NewNotifier(cmd)
}
// Run is the main execution flow of the command
func Run(c *cobra.Command, names []string) {
filter := filters.BuildFilter(names, enableLabel, scope)
runOnce, _ := c.PersistentFlags().GetBool("run-once")
httpAPI, _ := c.PersistentFlags().GetBool("http-api")
func Run(_ *cobra.Command, names []string) {
filter := filters.BuildFilter(names, c.EnableLabel, c.Scope)
if runOnce {
if noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message"); !noStartupMessage {
if c.RunOnce {
if !c.NoStartupMessage {
log.Info("Running a one time update.")
}
runUpdatesWithNotifications(filter)
@ -151,14 +125,12 @@ func Run(c *cobra.Command, names []string) {
return
}
if err := actions.CheckForMultipleWatchtowerInstances(client, cleanup, scope); err != nil {
if err := actions.CheckForMultipleWatchtowerInstances(client, c.Cleanup, c.Scope); err != nil {
log.Fatal(err)
}
if httpAPI {
apiToken, _ := c.PersistentFlags().GetString("http-api-token")
if err := api.SetupHTTPUpdates(apiToken, func() { runUpdatesWithNotifications(filter) }); err != nil {
if c.HTTPAPI {
if err := api.SetupHTTPUpdates(c.HTTPAPIToken, func() { runUpdatesWithNotifications(filter) }); err != nil {
log.Fatal(err)
os.Exit(1)
}
@ -166,20 +138,20 @@ func Run(c *cobra.Command, names []string) {
api.WaitForHTTPUpdates()
}
if err := runUpgradesOnSchedule(c, filter); err != nil {
if err := runUpgradesOnSchedule(filter); err != nil {
log.Error(err)
}
os.Exit(1)
}
func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
func runUpgradesOnSchedule(filter t.Filter) error {
tryLockSem := make(chan bool, 1)
tryLockSem <- true
cron := cron.New()
err := cron.AddFunc(
scheduleSpec,
runner := cron.New()
err := runner.AddFunc(
viper.GetString("schedule"),
func() {
select {
case v := <-tryLockSem:
@ -189,7 +161,7 @@ func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
log.Debug("Skipped another update already running.")
}
nextRuns := cron.Entries()
nextRuns := runner.Entries()
if len(nextRuns) > 0 {
log.Debug("Scheduled next run: " + nextRuns[0].Next.String())
}
@ -199,11 +171,11 @@ func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
return err
}
if noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message"); !noStartupMessage {
log.Info("Starting Watchtower and scheduling first run: " + cron.Entries()[0].Schedule.Next(time.Now()).String())
if !viper.GetBool("no-startup-message") {
log.Info("Starting Watchtower and scheduling first run: " + runner.Entries()[0].Schedule.Next(time.Now()).String())
}
cron.Start()
runner.Start()
// Graceful shut-down on SIGINT/SIGTERM
interrupt := make(chan os.Signal, 1)
@ -211,7 +183,7 @@ func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
signal.Notify(interrupt, syscall.SIGTERM)
<-interrupt
cron.Stop()
runner.Stop()
log.Info("Waiting for running update to be finished...")
<-tryLockSem
return nil
@ -221,12 +193,12 @@ func runUpdatesWithNotifications(filter t.Filter) {
notifier.StartNotification()
updateParams := t.UpdateParams{
Filter: filter,
Cleanup: cleanup,
NoRestart: noRestart,
Timeout: timeout,
MonitorOnly: monitorOnly,
LifecycleHooks: lifecycleHooks,
RollingRestart: rollingRestart,
Cleanup: c.Cleanup,
NoRestart: c.NoRestart,
Timeout: c.Timeout,
MonitorOnly: c.MonitorOnly,
LifecycleHooks: c.LifecycleHooks,
RollingRestart: c.RollingRestart,
}
err := actions.Update(client, updateParams)
if err != nil {