-
Notifications
You must be signed in to change notification settings - Fork 891
/
Copy pathroot.go
379 lines (317 loc) · 10.3 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package cmd
import (
"math"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/containrrr/watchtower/internal/actions"
"github.com/containrrr/watchtower/internal/flags"
"github.com/containrrr/watchtower/internal/meta"
"github.com/containrrr/watchtower/pkg/api"
apiMetrics "github.com/containrrr/watchtower/pkg/api/metrics"
"github.com/containrrr/watchtower/pkg/api/update"
"github.com/containrrr/watchtower/pkg/container"
"github.com/containrrr/watchtower/pkg/filters"
"github.com/containrrr/watchtower/pkg/metrics"
"github.com/containrrr/watchtower/pkg/notifications"
t "github.com/containrrr/watchtower/pkg/types"
"github.com/robfig/cron"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var (
client container.Client
scheduleSpec string
cleanup bool
noRestart bool
monitorOnly bool
enableLabel bool
notifier t.Notifier
timeout time.Duration
lifecycleHooks bool
rollingRestart bool
scope string
)
var rootCmd = NewRootCommand()
// NewRootCommand creates the root command for watchtower
func NewRootCommand() *cobra.Command {
return &cobra.Command{
Use: "watchtower",
Short: "Automatically updates running Docker containers",
Long: `
Watchtower automatically updates running Docker containers whenever a new image is released.
More information available at https://github.com/containrrr/watchtower/.
`,
Run: Run,
PreRun: PreRun,
Args: cobra.ArbitraryArgs,
}
}
func init() {
flags.SetDefaults()
flags.RegisterDockerFlags(rootCmd)
flags.RegisterSystemFlags(rootCmd)
flags.RegisterNotificationFlags(rootCmd)
}
// Execute the root func and exit in case of errors
func Execute() {
rootCmd.AddCommand(notifyUpgradeCommand)
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
// PreRun is a lifecycle hook that runs before the command is executed.
func PreRun(cmd *cobra.Command, _ []string) {
f := cmd.PersistentFlags()
flags.ProcessFlagAliases(f)
if enabled, _ := f.GetBool("no-color"); enabled {
log.SetFormatter(&log.TextFormatter{
DisableColors: true,
})
} else {
// enable logrus built-in support for https://bixense.com/clicolors/
log.SetFormatter(&log.TextFormatter{
EnvironmentOverrideColors: true,
})
}
rawLogLevel, _ := f.GetString(`log-level`)
if logLevel, err := log.ParseLevel(rawLogLevel); err != nil {
log.Fatalf("Invalid log level: %s", err.Error())
} else {
log.SetLevel(logLevel)
}
scheduleSpec, _ = f.GetString("schedule")
flags.GetSecretsFromFiles(cmd)
cleanup, noRestart, monitorOnly, timeout = flags.ReadFlags(cmd)
if 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")
if scope != "" {
log.Debugf(`Using scope %q`, scope)
}
// configure environment vars for client
err := flags.EnvConfig(cmd)
if err != nil {
log.Fatal(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")
warnOnHeadPullFailed, _ := f.GetString("warn-on-head-failure")
if monitorOnly && 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(container.ClientOptions{
PullImages: !noPull,
IncludeStopped: includeStopped,
ReviveStopped: reviveStopped,
RemoveVolumes: removeVolumes,
IncludeRestarting: includeRestarting,
WarnOnHeadFailed: container.WarningStrategy(warnOnHeadPullFailed),
})
notifier = notifications.NewNotifier(cmd)
notifier.AddLogHook()
}
// Run is the main execution flow of the command
func Run(c *cobra.Command, names []string) {
filter, filterDesc := filters.BuildFilter(names, enableLabel, scope)
runOnce, _ := c.PersistentFlags().GetBool("run-once")
enableUpdateAPI, _ := c.PersistentFlags().GetBool("http-api-update")
enableMetricsAPI, _ := c.PersistentFlags().GetBool("http-api-metrics")
unblockHTTPAPI, _ := c.PersistentFlags().GetBool("http-api-periodic-polls")
apiToken, _ := c.PersistentFlags().GetString("http-api-token")
if rollingRestart && monitorOnly {
log.Fatal("Rolling restarts is not compatible with the global monitor only flag")
}
awaitDockerClient()
if err := actions.CheckForSanity(client, filter, rollingRestart); err != nil {
logNotifyExit(err)
}
if runOnce {
writeStartupMessage(c, time.Time{}, filterDesc)
runUpdatesWithNotifications(filter)
notifier.Close()
os.Exit(0)
return
}
if err := actions.CheckForMultipleWatchtowerInstances(client, cleanup, scope); err != nil {
logNotifyExit(err)
}
// The lock is shared between the scheduler and the HTTP API. It only allows one update to run at a time.
updateLock := make(chan bool, 1)
updateLock <- true
httpAPI := api.New(apiToken)
if enableUpdateAPI {
updateHandler := update.New(func(images []string) { runUpdatesWithNotifications(filters.FilterByImage(images, filter)) }, updateLock)
httpAPI.RegisterFunc(updateHandler.Path, updateHandler.Handle)
// If polling isn't enabled the scheduler is never started and
// we need to trigger the startup messages manually.
if !unblockHTTPAPI {
writeStartupMessage(c, time.Time{}, filterDesc)
}
}
if enableMetricsAPI {
metricsHandler := apiMetrics.New()
httpAPI.RegisterHandler(metricsHandler.Path, metricsHandler.Handle)
}
if err := httpAPI.Start(enableUpdateAPI && !unblockHTTPAPI); err != nil && err != http.ErrServerClosed {
log.Error("failed to start API", err)
}
if err := runUpgradesOnSchedule(c, filter, filterDesc, updateLock); err != nil {
log.Error(err)
}
os.Exit(1)
}
func logNotifyExit(err error) {
log.Error(err)
notifier.Close()
os.Exit(1)
}
func awaitDockerClient() {
log.Debug("Sleeping for a second to ensure the docker api client has been properly initialized.")
time.Sleep(1 * time.Second)
}
func formatDuration(d time.Duration) string {
sb := strings.Builder{}
hours := int64(d.Hours())
minutes := int64(math.Mod(d.Minutes(), 60))
seconds := int64(math.Mod(d.Seconds(), 60))
if hours == 1 {
sb.WriteString("1 hour")
} else if hours != 0 {
sb.WriteString(strconv.FormatInt(hours, 10))
sb.WriteString(" hours")
}
if hours != 0 && (seconds != 0 || minutes != 0) {
sb.WriteString(", ")
}
if minutes == 1 {
sb.WriteString("1 minute")
} else if minutes != 0 {
sb.WriteString(strconv.FormatInt(minutes, 10))
sb.WriteString(" minutes")
}
if minutes != 0 && (seconds != 0) {
sb.WriteString(", ")
}
if seconds == 1 {
sb.WriteString("1 second")
} else if seconds != 0 || (hours == 0 && minutes == 0) {
sb.WriteString(strconv.FormatInt(seconds, 10))
sb.WriteString(" seconds")
}
return sb.String()
}
func writeStartupMessage(c *cobra.Command, sched time.Time, filtering string) {
noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message")
enableUpdateAPI, _ := c.PersistentFlags().GetBool("http-api-update")
var startupLog *log.Entry
if noStartupMessage {
startupLog = notifications.LocalLog
} else {
startupLog = log.NewEntry(log.StandardLogger())
// Batch up startup messages to send them as a single notification
notifier.StartNotification()
}
startupLog.Info("Watchtower ", meta.Version)
notifierNames := notifier.GetNames()
if len(notifierNames) > 0 {
startupLog.Info("Using notifications: " + strings.Join(notifierNames, ", "))
} else {
startupLog.Info("Using no notifications")
}
startupLog.Info(filtering)
if !sched.IsZero() {
until := formatDuration(time.Until(sched))
startupLog.Info("Scheduling first run: " + sched.Format("2006-01-02 15:04:05 -0700 MST"))
startupLog.Info("Note that the first check will be performed in " + until)
} else if runOnce, _ := c.PersistentFlags().GetBool("run-once"); runOnce {
startupLog.Info("Running a one time update.")
} else {
startupLog.Info("Periodic runs are not enabled.")
}
if enableUpdateAPI {
// TODO: make listen port configurable
startupLog.Info("The HTTP API is enabled at :8080.")
}
if !noStartupMessage {
// Send the queued up startup messages, not including the trace warning below (to make sure it's noticed)
notifier.SendNotification(nil)
}
if log.IsLevelEnabled(log.TraceLevel) {
startupLog.Warn("Trace level enabled: log will include sensitive information as credentials and tokens")
}
}
func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter, filtering string, lock chan bool) error {
if lock == nil {
lock = make(chan bool, 1)
lock <- true
}
scheduler := cron.New()
err := scheduler.AddFunc(
scheduleSpec,
func() {
select {
case v := <-lock:
defer func() { lock <- v }()
metric := runUpdatesWithNotifications(filter)
metrics.RegisterScan(metric)
default:
// Update was skipped
metrics.RegisterScan(nil)
log.Debug("Skipped another update already running.")
}
nextRuns := scheduler.Entries()
if len(nextRuns) > 0 {
log.Debug("Scheduled next run: " + nextRuns[0].Next.String())
}
})
if err != nil {
return err
}
writeStartupMessage(c, scheduler.Entries()[0].Schedule.Next(time.Now()), filtering)
scheduler.Start()
// Graceful shut-down on SIGINT/SIGTERM
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
signal.Notify(interrupt, syscall.SIGTERM)
<-interrupt
scheduler.Stop()
log.Info("Waiting for running update to be finished...")
<-lock
return nil
}
func runUpdatesWithNotifications(filter t.Filter) *metrics.Metric {
notifier.StartNotification()
updateParams := t.UpdateParams{
Filter: filter,
Cleanup: cleanup,
NoRestart: noRestart,
Timeout: timeout,
MonitorOnly: monitorOnly,
LifecycleHooks: lifecycleHooks,
RollingRestart: rollingRestart,
}
result, err := actions.Update(client, updateParams)
if err != nil {
log.Error(err)
}
notifier.SendNotification(result)
metricResults := metrics.NewMetric(result)
notifications.LocalLog.WithFields(log.Fields{
"Scanned": metricResults.Scanned,
"Updated": metricResults.Updated,
"Failed": metricResults.Failed,
}).Info("Session done")
return metricResults
}