1
0
mirror of https://github.com/containrrr/watchtower.git synced 2025-03-03 15:32:37 +02:00

98 lines
2.4 KiB
Go
Raw Normal View History

package notifications
import (
ty "github.com/containrrr/watchtower/pkg/types"
"github.com/johntdyer/slackrus"
log "github.com/sirupsen/logrus"
2019-06-22 22:04:36 +02:00
"github.com/spf13/cobra"
)
2017-10-29 23:45:01 -07:00
// Notifier can send log output as notification to admins, with optional batching.
type Notifier struct {
types []ty.Notifier
}
2017-10-29 23:45:01 -07:00
// NewNotifier creates and returns a new Notifier, using global configuration.
2019-06-22 22:04:36 +02:00
func NewNotifier(c *cobra.Command) *Notifier {
n := &Notifier{}
f := c.PersistentFlags()
level, _ := f.GetString("notifications-level")
2019-06-22 22:04:36 +02:00
logLevel, err := log.ParseLevel(level)
if err != nil {
log.Fatalf("Notifications invalid log level: %s", err.Error())
}
acceptedLogLevels := slackrus.LevelThreshold(logLevel)
// Parse types and create notifiers.
types, err := f.GetStringSlice("notifications")
2019-12-27 12:05:56 +01:00
if err != nil {
2020-04-24 13:45:24 +02:00
log.WithField("could not read notifications argument", log.Fields{"Error": err}).Fatal()
2019-12-27 12:05:56 +01:00
}
n.types = n.GetNotificationTypes(c, acceptedLogLevels, types)
return n
}
// 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 {
output := make([]ty.Notifier, 0)
for _, t := range types {
if t == shoutrrrType {
output = append(output, newShoutrrrNotifier(cmd, levels))
continue
}
var legacyNotifier ty.ConvertableNotifier
switch t {
case emailType:
legacyNotifier = newEmailNotifier(cmd, []log.Level{})
2017-11-27 12:04:08 +01:00
case slackType:
legacyNotifier = newSlackNotifier(cmd, []log.Level{})
case msTeamsType:
legacyNotifier = newMsTeamsNotifier(cmd, levels)
case gotifyType:
legacyNotifier = newGotifyNotifier(cmd, []log.Level{})
default:
log.Fatalf("Unknown notification type %q", t)
}
notifier := newShoutrrrNotifierFromURL(
cmd,
legacyNotifier.GetURL(),
levels,
)
output = append(output, notifier)
}
return output
}
2017-10-29 23:45:01 -07:00
// StartNotification starts a log batch. Notifications will be accumulated after this point and only sent when SendNotification() is called.
func (n *Notifier) StartNotification() {
for _, t := range n.types {
t.StartNotification()
}
}
2017-10-29 23:45:01 -07:00
// SendNotification sends any notifications accumulated since StartNotification() was called.
func (n *Notifier) SendNotification() {
for _, t := range n.types {
t.SendNotification()
}
}
// Close closes all notifiers.
func (n *Notifier) Close() {
for _, t := range n.types {
t.Close()
}
}