1
0
mirror of https://github.com/containrrr/watchtower.git synced 2024-12-12 09:04:17 +02:00

feat: include additional info in startup (#809)

This commit is contained in:
nils måsén 2021-03-28 21:04:11 +02:00 committed by GitHub
parent 5e17ef6014
commit 9fa2fd82a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 185 additions and 55 deletions

5
build.sh Normal file
View File

@ -0,0 +1,5 @@
#!/bin/bash
VERSION=$(git describe)
echo "Building $VERSION..."
go build -o watchtower -ldflags "-X github.com/containrrr/watchtower/cmd.version=$VERSION"

View File

@ -1,14 +1,15 @@
package cmd package cmd
import ( import (
metrics2 "github.com/containrrr/watchtower/pkg/metrics" "math"
"os" "os"
"os/signal" "os/signal"
"strconv" "strconv"
"strings"
"syscall" "syscall"
"time" "time"
"github.com/containrrr/watchtower/pkg/api/metrics" apiMetrics "github.com/containrrr/watchtower/pkg/api/metrics"
"github.com/containrrr/watchtower/pkg/api/update" "github.com/containrrr/watchtower/pkg/api/update"
"github.com/containrrr/watchtower/internal/actions" "github.com/containrrr/watchtower/internal/actions"
@ -16,6 +17,7 @@ import (
"github.com/containrrr/watchtower/pkg/api" "github.com/containrrr/watchtower/pkg/api"
"github.com/containrrr/watchtower/pkg/container" "github.com/containrrr/watchtower/pkg/container"
"github.com/containrrr/watchtower/pkg/filters" "github.com/containrrr/watchtower/pkg/filters"
"github.com/containrrr/watchtower/pkg/metrics"
"github.com/containrrr/watchtower/pkg/notifications" "github.com/containrrr/watchtower/pkg/notifications"
t "github.com/containrrr/watchtower/pkg/types" t "github.com/containrrr/watchtower/pkg/types"
"github.com/robfig/cron" "github.com/robfig/cron"
@ -36,6 +38,8 @@ var (
lifecycleHooks bool lifecycleHooks bool
rollingRestart bool rollingRestart bool
scope string scope string
// Set on build using ldflags
version = "v0.0.0-unknown"
) )
var rootCmd = NewRootCommand() var rootCmd = NewRootCommand()
@ -69,7 +73,7 @@ func Execute() {
} }
// PreRun is a lifecycle hook that runs before the command is executed. // PreRun is a lifecycle hook that runs before the command is executed.
func PreRun(cmd *cobra.Command, args []string) { func PreRun(cmd *cobra.Command, _ []string) {
f := cmd.PersistentFlags() f := cmd.PersistentFlags()
if enabled, _ := f.GetBool("no-color"); enabled { if enabled, _ := f.GetBool("no-color"); enabled {
@ -146,7 +150,7 @@ func PreRun(cmd *cobra.Command, args []string) {
// Run is the main execution flow of the command // Run is the main execution flow of the command
func Run(c *cobra.Command, names []string) { func Run(c *cobra.Command, names []string) {
filter := filters.BuildFilter(names, enableLabel, scope) filter, filterDesc := filters.BuildFilter(names, enableLabel, scope)
runOnce, _ := c.PersistentFlags().GetBool("run-once") runOnce, _ := c.PersistentFlags().GetBool("run-once")
enableUpdateAPI, _ := c.PersistentFlags().GetBool("http-api-update") enableUpdateAPI, _ := c.PersistentFlags().GetBool("http-api-update")
enableMetricsAPI, _ := c.PersistentFlags().GetBool("http-api-metrics") enableMetricsAPI, _ := c.PersistentFlags().GetBool("http-api-metrics")
@ -154,9 +158,7 @@ func Run(c *cobra.Command, names []string) {
apiToken, _ := c.PersistentFlags().GetString("http-api-token") apiToken, _ := c.PersistentFlags().GetString("http-api-token")
if runOnce { if runOnce {
if noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message"); !noStartupMessage { writeStartupMessage(c, time.Time{}, filterDesc)
log.Info("Running a one time update.")
}
runUpdatesWithNotifications(filter) runUpdatesWithNotifications(filter)
notifier.Close() notifier.Close()
os.Exit(0) os.Exit(0)
@ -175,39 +177,99 @@ func Run(c *cobra.Command, names []string) {
} }
if enableMetricsAPI { if enableMetricsAPI {
metricsHandler := metrics.New() metricsHandler := apiMetrics.New()
httpAPI.RegisterHandler(metricsHandler.Path, metricsHandler.Handle) httpAPI.RegisterHandler(metricsHandler.Path, metricsHandler.Handle)
} }
httpAPI.Start(enableUpdateAPI) if err := httpAPI.Start(enableUpdateAPI); err != nil {
log.Error("failed to start API", err)
}
if err := runUpgradesOnSchedule(c, filter); err != nil { if err := runUpgradesOnSchedule(c, filter, filterDesc); err != nil {
log.Error(err) log.Error(err)
} }
os.Exit(1) os.Exit(1)
} }
func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error { 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) {
if noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message"); !noStartupMessage {
schedMessage := "Running a one time update."
if !sched.IsZero() {
until := formatDuration(time.Until(sched))
schedMessage = "Scheduling first run: " + sched.Format("2006-01-02 15:04:05 -0700 MST") +
"\nNote that the first check will be performed in " + until
}
notifs := "Using no notifications"
notifList := notifier.String()
if len(notifList) > 0 {
notifs = "Using notifications: " + notifList
}
log.Info("Watchtower ", version, "\n", notifs, "\n", filtering, "\n", schedMessage)
}
}
func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter, filtering string) error {
tryLockSem := make(chan bool, 1) tryLockSem := make(chan bool, 1)
tryLockSem <- true tryLockSem <- true
cron := cron.New() scheduler := cron.New()
err := cron.AddFunc( err := scheduler.AddFunc(
scheduleSpec, scheduleSpec,
func() { func() {
select { select {
case v := <-tryLockSem: case v := <-tryLockSem:
defer func() { tryLockSem <- v }() defer func() { tryLockSem <- v }()
metric := runUpdatesWithNotifications(filter) metric := runUpdatesWithNotifications(filter)
metrics2.RegisterScan(metric) metrics.RegisterScan(metric)
default: default:
// Update was skipped // Update was skipped
metrics2.RegisterScan(nil) metrics.RegisterScan(nil)
log.Debug("Skipped another update already running.") log.Debug("Skipped another update already running.")
} }
nextRuns := cron.Entries() nextRuns := scheduler.Entries()
if len(nextRuns) > 0 { if len(nextRuns) > 0 {
log.Debug("Scheduled next run: " + nextRuns[0].Next.String()) log.Debug("Scheduled next run: " + nextRuns[0].Next.String())
} }
@ -217,11 +279,9 @@ func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
return err return err
} }
if noStartupMessage, _ := c.PersistentFlags().GetBool("no-startup-message"); !noStartupMessage { writeStartupMessage(c, scheduler.Entries()[0].Schedule.Next(time.Now()), filtering)
log.Info("Starting Watchtower and scheduling first run: " + cron.Entries()[0].Schedule.Next(time.Now()).String())
}
cron.Start() scheduler.Start()
// Graceful shut-down on SIGINT/SIGTERM // Graceful shut-down on SIGINT/SIGTERM
interrupt := make(chan os.Signal, 1) interrupt := make(chan os.Signal, 1)
@ -229,14 +289,13 @@ func runUpgradesOnSchedule(c *cobra.Command, filter t.Filter) error {
signal.Notify(interrupt, syscall.SIGTERM) signal.Notify(interrupt, syscall.SIGTERM)
<-interrupt <-interrupt
cron.Stop() scheduler.Stop()
log.Info("Waiting for running update to be finished...") log.Info("Waiting for running update to be finished...")
<-tryLockSem <-tryLockSem
return nil return nil
} }
func runUpdatesWithNotifications(filter t.Filter) *metrics2.Metric { func runUpdatesWithNotifications(filter t.Filter) *metrics.Metric {
notifier.StartNotification() notifier.StartNotification()
updateParams := t.UpdateParams{ updateParams := t.UpdateParams{
Filter: filter, Filter: filter,
@ -247,10 +306,10 @@ func runUpdatesWithNotifications(filter t.Filter) *metrics2.Metric {
LifecycleHooks: lifecycleHooks, LifecycleHooks: lifecycleHooks,
RollingRestart: rollingRestart, RollingRestart: rollingRestart,
} }
metrics, err := actions.Update(client, updateParams) metricResults, err := actions.Update(client, updateParams)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
} }
notifier.SendNotification() notifier.SendNotification()
return metrics return metricResults
} }

View File

@ -1,6 +1,9 @@
package filters package filters
import t "github.com/containrrr/watchtower/pkg/types" import (
t "github.com/containrrr/watchtower/pkg/types"
"strings"
)
// WatchtowerContainersFilter filters only watchtower containers // WatchtowerContainersFilter filters only watchtower containers
func WatchtowerContainersFilter(c t.FilterableContainer) bool { return c.IsWatchtower() } func WatchtowerContainersFilter(c t.FilterableContainer) bool { return c.IsWatchtower() }
@ -68,19 +71,45 @@ func FilterByScope(scope string, baseFilter t.Filter) t.Filter {
} }
// BuildFilter creates the needed filter of containers // BuildFilter creates the needed filter of containers
func BuildFilter(names []string, enableLabel bool, scope string) t.Filter { func BuildFilter(names []string, enableLabel bool, scope string) (t.Filter, string) {
sb := strings.Builder{}
filter := NoFilter filter := NoFilter
filter = FilterByNames(names, filter) filter = FilterByNames(names, filter)
if len(names) > 0 {
sb.WriteString("with name \"")
for i, n := range names {
sb.WriteString(n)
if i < len(names)-1 {
sb.WriteString(`" or "`)
}
}
sb.WriteString(`", `)
}
if enableLabel { if enableLabel {
// If label filtering is enabled, containers should only be considered // If label filtering is enabled, containers should only be considered
// if the label is specifically set. // if the label is specifically set.
filter = FilterByEnableLabel(filter) filter = FilterByEnableLabel(filter)
sb.WriteString("using enable label, ")
} }
if scope != "" { if scope != "" {
// If a scope has been defined, containers should only be considered // If a scope has been defined, containers should only be considered
// if the scope is specifically set. // if the scope is specifically set.
filter = FilterByScope(scope, filter) filter = FilterByScope(scope, filter)
sb.WriteString(`in scope "`)
sb.WriteString(scope)
sb.WriteString(`", `)
} }
filter = FilterByDisabledLabel(filter) filter = FilterByDisabledLabel(filter)
return filter
filterDesc := "Checking all containers (except explicitly disabled with label)"
if sb.Len() > 0 {
filterDesc = "Only checking containers " + sb.String()
// Remove the last ", "
filterDesc = filterDesc[:len(filterDesc)-2]
}
return filter, filterDesc
} }

View File

@ -114,7 +114,8 @@ func TestBuildFilter(t *testing.T) {
var names []string var names []string
names = append(names, "test") names = append(names, "test")
filter := BuildFilter(names, false, "") filter, desc := BuildFilter(names, false, "")
assert.Contains(t, desc, "test")
container := new(mocks.FilterableContainer) container := new(mocks.FilterableContainer)
container.On("Name").Return("Invalid") container.On("Name").Return("Invalid")
@ -150,7 +151,8 @@ func TestBuildFilterEnableLabel(t *testing.T) {
var names []string var names []string
names = append(names, "test") names = append(names, "test")
filter := BuildFilter(names, true, "") filter, desc := BuildFilter(names, true, "")
assert.Contains(t, desc, "using enable label")
container := new(mocks.FilterableContainer) container := new(mocks.FilterableContainer)
container.On("Enabled").Return(false, false) container.On("Enabled").Return(false, false)

View File

@ -6,6 +6,7 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"os" "os"
"strings"
) )
// Notifier can send log output as notification to admins, with optional batching. // Notifier can send log output as notification to admins, with optional batching.
@ -42,6 +43,26 @@ func NewNotifier(c *cobra.Command) *Notifier {
return n return n
} }
func (n *Notifier) String() string {
if len(n.types) < 1 {
return ""
}
sb := strings.Builder{}
for _, notif := range n.types {
for _, name := range notif.GetNames() {
sb.WriteString(name)
sb.WriteString(", ")
}
}
names := sb.String()
// remove the last separator
names = names[:len(names)-2]
return names
}
// getNotificationTypes produces an array of notifiers from a list of types // getNotificationTypes produces an array of notifiers from a list of types
func (n *Notifier) getNotificationTypes(cmd *cobra.Command, levels []log.Level, types []string) []ty.Notifier { func (n *Notifier) getNotificationTypes(cmd *cobra.Command, levels []log.Level, types []string) []ty.Notifier {
output := make([]ty.Notifier, 0) output := make([]ty.Notifier, 0)

View File

@ -33,16 +33,29 @@ type shoutrrrTypeNotifier struct {
done chan bool done chan bool
} }
func (n *shoutrrrTypeNotifier) GetNames() []string {
names := make([]string, len(n.Urls))
for i, u := range n.Urls {
schemeEnd := strings.Index(u, ":")
if schemeEnd <= 0 {
names[i] = "invalid"
continue
}
names[i] = u[:schemeEnd]
}
return names
}
func newShoutrrrNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier { func newShoutrrrNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags() flags := c.PersistentFlags()
urls, _ := flags.GetStringArray("notification-url") urls, _ := flags.GetStringArray("notification-url")
template := getShoutrrrTemplate(c) tpl := getShoutrrrTemplate(c)
return createSender(urls, acceptedLogLevels, template) return createSender(urls, acceptedLogLevels, tpl)
} }
func newShoutrrrNotifierFromURL(c *cobra.Command, url string, levels []log.Level) t.Notifier { func newShoutrrrNotifierFromURL(c *cobra.Command, url string, levels []log.Level) t.Notifier {
template := getShoutrrrTemplate(c) tpl := getShoutrrrTemplate(c)
return createSender([]string{url}, levels, template) return createSender([]string{url}, levels, tpl)
} }
func createSender(urls []string, levels []log.Level, template *template.Template) t.Notifier { func createSender(urls []string, levels []log.Level, template *template.Template) t.Notifier {
@ -83,54 +96,54 @@ func sendNotifications(n *shoutrrrTypeNotifier) {
n.done <- true n.done <- true
} }
func (e *shoutrrrTypeNotifier) buildMessage(entries []*log.Entry) string { func (n *shoutrrrTypeNotifier) buildMessage(entries []*log.Entry) string {
var body bytes.Buffer var body bytes.Buffer
if err := e.template.Execute(&body, entries); err != nil { if err := n.template.Execute(&body, entries); err != nil {
fmt.Printf("Failed to execute Shoutrrrr template: %s\n", err.Error()) fmt.Printf("Failed to execute Shoutrrrr template: %s\n", err.Error())
} }
return body.String() return body.String()
} }
func (e *shoutrrrTypeNotifier) sendEntries(entries []*log.Entry) { func (n *shoutrrrTypeNotifier) sendEntries(entries []*log.Entry) {
msg := e.buildMessage(entries) msg := n.buildMessage(entries)
e.messages <- msg n.messages <- msg
} }
func (e *shoutrrrTypeNotifier) StartNotification() { func (n *shoutrrrTypeNotifier) StartNotification() {
if e.entries == nil { if n.entries == nil {
e.entries = make([]*log.Entry, 0, 10) n.entries = make([]*log.Entry, 0, 10)
} }
} }
func (e *shoutrrrTypeNotifier) SendNotification() { func (n *shoutrrrTypeNotifier) SendNotification() {
if e.entries == nil || len(e.entries) <= 0 { if n.entries == nil || len(n.entries) <= 0 {
return return
} }
e.sendEntries(e.entries) n.sendEntries(n.entries)
e.entries = nil n.entries = nil
} }
func (e *shoutrrrTypeNotifier) Close() { func (n *shoutrrrTypeNotifier) Close() {
close(e.messages) close(n.messages)
// Use fmt so it doesn't trigger another notification. // Use fmt so it doesn't trigger another notification.
fmt.Println("Waiting for the notification goroutine to finish") fmt.Println("Waiting for the notification goroutine to finish")
_ = <-e.done _ = <-n.done
} }
func (e *shoutrrrTypeNotifier) Levels() []log.Level { func (n *shoutrrrTypeNotifier) Levels() []log.Level {
return e.logLevels return n.logLevels
} }
func (e *shoutrrrTypeNotifier) Fire(entry *log.Entry) error { func (n *shoutrrrTypeNotifier) Fire(entry *log.Entry) error {
if e.entries != nil { if n.entries != nil {
e.entries = append(e.entries, entry) n.entries = append(n.entries, entry)
} else { } else {
// Log output generated outside a cycle is sent immediately. // Log output generated outside a cycle is sent immediately.
e.sendEntries([]*log.Entry{entry}) n.sendEntries([]*log.Entry{entry})
} }
return nil return nil
} }

View File

@ -4,5 +4,6 @@ package types
type Notifier interface { type Notifier interface {
StartNotification() StartNotification()
SendNotification() SendNotification()
GetNames() []string
Close() Close()
} }