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

@ -10,6 +10,7 @@ import (
"github.com/containrrr/watchtower/pkg/registry"
"github.com/containrrr/watchtower/pkg/registry/digest"
"github.com/containrrr/watchtower/internal/flags"
t "github.com/containrrr/watchtower/pkg/types"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
@ -41,7 +42,7 @@ type Client interface {
// * DOCKER_HOST the docker-engine host to send api requests to
// * DOCKER_TLS_VERIFY whether to verify tls certificates
// * DOCKER_API_VERSION the minimum docker api version to work with
func NewClient(pullImages bool, includeStopped bool, reviveStopped bool, removeVolumes bool, includeRestarting bool) Client {
func NewClient(config *flags.WatchConfig) Client {
cli, err := sdkClient.NewClientWithOpts(sdkClient.FromEnv)
if err != nil {
@ -50,11 +51,11 @@ func NewClient(pullImages bool, includeStopped bool, reviveStopped bool, removeV
return dockerClient{
api: cli,
pullImages: pullImages,
removeVolumes: removeVolumes,
includeStopped: includeStopped,
reviveStopped: reviveStopped,
includeRestarting: includeRestarting,
pullImages: !config.NoPull,
removeVolumes: config.RemoveVolumes,
includeStopped: config.IncludeStopped,
reviveStopped: config.ReviveStopped,
includeRestarting: config.IncludeRestarting,
}
}

View file

@ -4,6 +4,7 @@ import (
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"net/smtp"
"os"
"strings"
@ -33,18 +34,17 @@ type emailTypeNotifier struct {
delay time.Duration
}
func newEmailNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
func newEmailNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
from, _ := flags.GetString("notification-email-from")
to, _ := flags.GetString("notification-email-to")
server, _ := flags.GetString("notification-email-server")
user, _ := flags.GetString("notification-email-server-user")
password, _ := flags.GetString("notification-email-server-password")
port, _ := flags.GetInt("notification-email-server-port")
tlsSkipVerify, _ := flags.GetBool("notification-email-server-tls-skip-verify")
delay, _ := flags.GetInt("notification-email-delay")
subjecttag, _ := flags.GetString("notification-email-subjecttag")
from := viper.GetString("notification-email-from")
to := viper.GetString("notification-email-to")
server := viper.GetString("notification-email-server")
user := viper.GetString("notification-email-server-user")
password := viper.GetString("notification-email-server-password")
port := viper.GetInt("notification-email-server-port")
tlsSkipVerify := viper.GetBool("notification-email-server-tls-skip-verify")
delay := viper.GetInt("notification-email-delay")
subjecttag := viper.GetString("notification-email-subjecttag")
n := &emailTypeNotifier{
From: from,
@ -81,13 +81,13 @@ func (e *emailTypeNotifier) buildMessage(entries []*log.Entry) []byte {
// We don't use fields in watchtower, so don't bother sending them.
}
t := time.Now()
now := time.Now()
header := make(map[string]string)
header["From"] = e.From
header["To"] = e.To
header["Subject"] = emailSubject
header["Date"] = t.Format(time.RFC1123Z)
header["Date"] = now.Format(time.RFC1123Z)
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"

View file

@ -5,6 +5,7 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"github.com/spf13/viper"
"net/http"
"strings"
@ -24,10 +25,10 @@ type gotifyTypeNotifier struct {
logLevels []log.Level
}
func newGotifyNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
func newGotifyNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := viper.Sub(".")
gotifyURL, _ := flags.GetString("notification-gotify-url")
gotifyURL := flags.GetString("notification-gotify-url")
if len(gotifyURL) < 1 {
log.Fatal("Required argument --notification-gotify-url(cli) or WATCHTOWER_NOTIFICATION_GOTIFY_URL(env) is empty.")
} else if !(strings.HasPrefix(gotifyURL, "http://") || strings.HasPrefix(gotifyURL, "https://")) {
@ -36,12 +37,12 @@ func newGotifyNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifi
log.Warn("Using an HTTP url for Gotify is insecure")
}
gotifyToken, _ := flags.GetString("notification-gotify-token")
gotifyToken := flags.GetString("notification-gotify-token")
if len(gotifyToken) < 1 {
log.Fatal("Required argument --notification-gotify-token(cli) or WATCHTOWER_NOTIFICATION_GOTIFY_TOKEN(env) is empty.")
}
gotifyInsecureSkipVerify, _ := flags.GetBool("notification-gotify-tls-skip-verify")
gotifyInsecureSkipVerify := flags.GetBool("notification-gotify-tls-skip-verify")
n := &gotifyTypeNotifier{
gotifyURL: gotifyURL,

View file

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"net/http"
t "github.com/containrrr/watchtower/pkg/types"
@ -22,16 +23,14 @@ type msTeamsTypeNotifier struct {
data bool
}
func newMsTeamsNotifier(cmd *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
func newMsTeamsNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := cmd.PersistentFlags()
webHookURL, _ := flags.GetString("notification-msteams-hook")
webHookURL := viper.GetString("notification-msteams-hook")
if len(webHookURL) <= 0 {
log.Fatal("Required argument --notification-msteams-hook(cli) or WATCHTOWER_NOTIFICATION_MSTEAMS_HOOK_URL(env) is empty.")
}
withData, _ := flags.GetBool("notification-msteams-data")
withData := viper.GetBool("notification-msteams-data")
n := &msTeamsTypeNotifier{
levels: acceptedLogLevels,
webHookURL: webHookURL,
@ -85,19 +84,19 @@ func (n *msTeamsTypeNotifier) Fire(entry *log.Entry) error {
jsonBody, err := json.Marshal(webHookBody)
if err != nil {
fmt.Println("Failed to build JSON body for MSTeams notificattion: ", err)
fmt.Println("Failed to build JSON body for MSTeams notification: ", err)
return
}
resp, err := http.Post(n.webHookURL, "application/json", bytes.NewBuffer([]byte(jsonBody)))
resp, err := http.Post(n.webHookURL, "application/json", bytes.NewBuffer(jsonBody))
if err != nil {
fmt.Println("Failed to send MSTeams notificattion: ", err)
fmt.Println("Failed to send MSTeams notification: ", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
fmt.Println("Failed to send MSTeams notificattion. HTTP RESPONSE STATUS: ", resp.StatusCode)
fmt.Println("Failed to send MSTeams notification. HTTP RESPONSE STATUS: ", resp.StatusCode)
if resp.Body != nil {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err == nil {

View file

@ -5,6 +5,7 @@ import (
"github.com/johntdyer/slackrus"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Notifier can send log output as notification to admins, with optional batching.
@ -16,9 +17,7 @@ type Notifier struct {
func NewNotifier(c *cobra.Command) *Notifier {
n := &Notifier{}
f := c.PersistentFlags()
level, _ := f.GetString("notifications-level")
level := viper.GetString("notifications-level")
logLevel, err := log.ParseLevel(level)
if err != nil {
log.Fatalf("Notifications invalid log level: %s", err.Error())
@ -27,7 +26,7 @@ func NewNotifier(c *cobra.Command) *Notifier {
acceptedLogLevels := slackrus.LevelThreshold(logLevel)
// Parse types and create notifiers.
types, err := f.GetStringSlice("notifications")
types := viper.GetStringSlice("notifications")
if err != nil {
log.WithField("could not read notifications argument", log.Fields{"Error": err}).Fatal()
}

View file

@ -4,6 +4,7 @@ import (
"bytes"
"fmt"
"github.com/containrrr/shoutrrr/pkg/types"
"github.com/spf13/viper"
"strings"
"text/template"
@ -34,9 +35,8 @@ type shoutrrrTypeNotifier struct {
}
func newShoutrrrNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
urls, _ := flags.GetStringArray("notification-url")
urls := viper.GetStringSlice("notification-url")
r, err := shoutrrr.CreateSender(urls...)
if err != nil {
log.Fatalf("Failed to initialize Shoutrrr notifications: %s\n", err.Error())
@ -126,12 +126,11 @@ func (e *shoutrrrTypeNotifier) Fire(entry *log.Entry) error {
return nil
}
func getShoutrrrTemplate(c *cobra.Command) *template.Template {
func getShoutrrrTemplate(_ *cobra.Command) *template.Template {
var tpl *template.Template
var err error
flags := c.PersistentFlags()
tplString, err := flags.GetString("notification-template")
tplString := viper.GetString("notification-template")
funcs := template.FuncMap{
"ToUpper": strings.ToUpper,
@ -141,7 +140,7 @@ func getShoutrrrTemplate(c *cobra.Command) *template.Template {
// If we succeed in getting a non-empty template configuration
// try to parse the template string.
if tplString != "" && err == nil {
if tplString != "" {
tpl, err = template.New("").Funcs(funcs).Parse(tplString)
}

View file

@ -32,6 +32,7 @@ func TestShoutrrrDefaultTemplate(t *testing.T) {
func TestShoutrrrTemplate(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{range .}}{{.Level}}: {{.Message}}{{println}}{{end}}"})
require.NoError(t, err)
@ -55,6 +56,7 @@ func TestShoutrrrTemplate(t *testing.T) {
func TestShoutrrrStringFunctions(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{range .}}{{.Level | printf \"%v\" | ToUpper }}: {{.Message | ToLower }} {{.Message | Title }}{{println}}{{end}}"})
require.NoError(t, err)
@ -77,8 +79,8 @@ func TestShoutrrrStringFunctions(t *testing.T) {
func TestShoutrrrInvalidTemplateUsesTemplate(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{"})
require.NoError(t, err)
@ -108,7 +110,7 @@ type blockingRouter struct {
sent chan bool
}
func (b blockingRouter) Send(message string, params *types.Params) []error {
func (b blockingRouter) Send(_ string, _ *types.Params) []error {
_ = <-b.unlock
b.sent <- true
return nil

View file

@ -5,6 +5,7 @@ import (
"github.com/johntdyer/slackrus"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
@ -15,14 +16,13 @@ type slackTypeNotifier struct {
slackrus.SlackrusHook
}
func newSlackNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
func newSlackNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
hookURL, _ := flags.GetString("notification-slack-hook-url")
userName, _ := flags.GetString("notification-slack-identifier")
channel, _ := flags.GetString("notification-slack-channel")
emoji, _ := flags.GetString("notification-slack-icon-emoji")
iconURL, _ := flags.GetString("notification-slack-icon-url")
hookURL := viper.GetString("notification-slack-hook-url")
userName := viper.GetString("notification-slack-identifier")
channel := viper.GetString("notification-slack-channel")
emoji := viper.GetString("notification-slack-icon-emoji")
iconURL := viper.GetString("notification-slack-icon-url")
n := &slackTypeNotifier{
SlackrusHook: slackrus.SlackrusHook{