Skip to content

Commit

Permalink
feat(config): swap viper and cobra for config (#684)
Browse files Browse the repository at this point in the history
  • Loading branch information
piksel authored Dec 21, 2020
1 parent cbe9ab8 commit ff8cb88
Show file tree
Hide file tree
Showing 12 changed files with 229 additions and 255 deletions.
136 changes: 54 additions & 82 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package cmd

import (
"fmt"
"github.com/spf13/viper"
"os"
"os/signal"
"strconv"
"syscall"
"time"

Expand All @@ -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{
Expand All @@ -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
Expand All @@ -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,
})
Expand All @@ -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.Debug(scope)
log.Debugf("Using scope %v", c.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)
Expand All @@ -151,35 +125,33 @@ 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)
}

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:
Expand All @@ -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())
}
Expand All @@ -199,19 +171,19 @@ 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)
signal.Notify(interrupt, os.Interrupt)
signal.Notify(interrupt, syscall.SIGTERM)

<-interrupt
cron.Stop()
runner.Stop()
log.Info("Waiting for running update to be finished...")
<-tryLockSem
return nil
Expand All @@ -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 {
Expand Down
31 changes: 31 additions & 0 deletions internal/flags/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package flags

import (
"time"
)

// WatchConfig is the global watchtower configuration created from flags and environment variables
type WatchConfig struct {
Interval int
Schedule string
NoPull bool `mapstructure:"no-pull"`
NoRestart bool `mapstructure:"no-restart"`
NoStartupMessage bool `mapstructure:"no-startup-message"`
Cleanup bool
RemoveVolumes bool `mapstructure:"remove-volumes"`
EnableLabel bool `mapstructure:"label-enable"`
Debug bool
Trace bool
MonitorOnly bool `mapstructure:"monitor-only"`
RunOnce bool `mapstructure:"run-once"`
IncludeStopped bool `mapstructure:"include-stopped"`
IncludeRestarting bool `mapstructure:"include-restarting"`
ReviveStopped bool `mapstructure:"revive-stopped"`
LifecycleHooks bool `mapstructure:"enable-lifecycle-hooks"`
RollingRestart bool `mapstructure:"rolling-restart"`
HTTPAPI bool `mapstructure:"http-api"`
HTTPAPIToken string `mapstructure:"http-api-token"`
Timeout time.Duration `mapstructure:"stop-timeout"`
Scope string
NoColor bool `mapstructure:"no-color"`
}
Loading

0 comments on commit ff8cb88

Please sign in to comment.