From a6d10bd5bc3f651e0ca04d47b981ed66e85a09a6 Mon Sep 17 00:00:00 2001 From: Matthias Loibl Date: Fri, 25 Mar 2022 17:59:51 +0100 Subject: [PATCH] Update golangci-lint and fix complaints (#2853) * Copy latest golangci-lint files from Prometheus Signed-off-by: Matthias Loibl * Use grafana/regexp over stdlib regexp Signed-off-by: Matthias Loibl * Fix typos in comments Signed-off-by: Matthias Loibl * Fix goimports complains in import sorting Signed-off-by: Matthias Loibl * gofumpt all Go files Signed-off-by: Matthias Loibl * Update naming to comply with revive linter Signed-off-by: Matthias Loibl * config: Fix error messages to be lower case Signed-off-by: Matthias Loibl * test/cli: Fix error messages to be lower case Signed-off-by: Matthias Loibl * .golangci.yaml: Remove obsolete space Signed-off-by: Matthias Loibl * config: Fix expected victorOps error Signed-off-by: Matthias Loibl * Use stdlib regexp Signed-off-by: Matthias Loibl * Clean up Go modules Signed-off-by: Matthias Loibl --- .golangci.yml | 49 +++++++++++++++++++++++- api/api.go | 11 +++--- api/v1/api.go | 8 ++-- api/v1/api_test.go | 11 +++--- api/v2/api.go | 20 +++++----- api/v2/api_test.go | 16 ++++---- api/v2/compat.go | 3 +- cli/alert_add.go | 5 +-- cli/alert_query.go | 3 +- cli/check_config.go | 3 +- cli/format/format.go | 8 ++-- cli/format/sort.go | 3 +- cli/root.go | 6 +-- cli/routing.go | 4 +- cli/silence_add.go | 3 +- cli/silence_expire.go | 3 +- cli/silence_update.go | 6 +-- cli/template_render.go | 3 +- cli/test_routing.go | 7 ++-- cli/test_routing_test.go | 8 ++-- cluster/channel.go | 3 +- cluster/channel_test.go | 2 +- cluster/cluster.go | 7 ++-- cluster/cluster_test.go | 16 ++++---- cluster/connection_pool.go | 2 +- cluster/delegate.go | 3 +- cluster/tls_connection.go | 1 - cluster/tls_transport.go | 2 +- cluster/tls_transport_test.go | 20 +++++----- cmd/alertmanager/main.go | 5 +-- cmd/alertmanager/main_test.go | 6 +-- config/config.go | 2 +- config/config_test.go | 26 +++---------- config/coordinator.go | 2 +- config/notifiers.go | 9 ++--- config/notifiers_test.go | 34 ++++++++-------- dispatch/dispatch_test.go | 12 +++--- inhibit/inhibit_test.go | 15 ++++---- nflog/nflog.go | 3 +- nflog/nflogpb/set_test.go | 4 +- notify/email/email_test.go | 4 +- notify/notify_test.go | 10 ++--- notify/opsgenie/opsgenie.go | 16 ++++---- notify/opsgenie/opsgenie_test.go | 4 +- notify/pagerduty/pagerduty_test.go | 6 +-- notify/pushover/pushover_test.go | 2 +- notify/slack/slack.go | 13 +++---- notify/slack/slack_test.go | 4 +- notify/sns/sns.go | 8 ++-- notify/telegram/telegram.go | 12 +++--- notify/telegram/telegram_test.go | 4 +- notify/test/test.go | 4 +- notify/util.go | 6 +-- notify/victorops/victorops.go | 1 - notify/victorops/victorops_test.go | 18 ++++----- notify/wechat/wechat_test.go | 6 +-- pkg/labels/parse_test.go | 1 - provider/mem/mem_test.go | 3 +- provider/provider.go | 6 +-- scripts/errcheck_excludes.txt | 9 +++++ silence/silence.go | 5 ++- silence/silence_test.go | 30 +++++++-------- store/store.go | 9 ++--- store/store_test.go | 3 +- test/cli/acceptance.go | 6 +-- test/cli/acceptance/cli_test.go | 3 +- test/cli/mock.go | 1 - test/with_api_v1/acceptance/send_test.go | 2 +- test/with_api_v2/acceptance/api_test.go | 5 ++- test/with_api_v2/mock.go | 1 - timeinterval/timeinterval.go | 11 ++++-- timeinterval/timeinterval_test.go | 2 +- types/types.go | 11 +++--- types/types_test.go | 1 - 74 files changed, 306 insertions(+), 275 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 527f9822..168b1e5e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,11 +1,58 @@ ---- run: deadline: 5m + skip-files: + # Skip autogenerated files. + - ^.*\.(pb|y)\.go$ + +output: + sort-results: true + +linters: + enable: + - depguard + - gofumpt + - goimports + - revive + - misspell + issues: exclude-rules: - path: _test.go linters: - errcheck + linters-settings: + depguard: + list-type: blacklist + include-go-root: true + packages-with-error-message: + - sync/atomic: "Use go.uber.org/atomic instead of sync/atomic" + - github.com/stretchr/testify/assert: "Use github.com/stretchr/testify/require instead of github.com/stretchr/testify/assert" + - github.com/go-kit/kit/log: "Use github.com/go-kit/log instead of github.com/go-kit/kit/log" errcheck: exclude: scripts/errcheck_excludes.txt + goimports: + local-prefixes: github.com/prometheus/alertmanager + gofumpt: + extra-rules: true + revive: + rules: + - name: exported + arguments: ["disableStutteringCheck"] + - name: blank-imports + - name: context-as-argument + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: package-comments + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf diff --git a/api/api.go b/api/api.go index f50ebee1..59bfb76d 100644 --- a/api/api.go +++ b/api/api.go @@ -20,6 +20,11 @@ import ( "runtime" "time" + "github.com/go-kit/log" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/common/model" + "github.com/prometheus/common/route" + apiv1 "github.com/prometheus/alertmanager/api/v1" apiv2 "github.com/prometheus/alertmanager/api/v2" "github.com/prometheus/alertmanager/cluster" @@ -28,11 +33,6 @@ import ( "github.com/prometheus/alertmanager/provider" "github.com/prometheus/alertmanager/silence" "github.com/prometheus/alertmanager/types" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/common/model" - "github.com/prometheus/common/route" - - "github.com/go-kit/log" ) // API represents all APIs of Alertmanager. @@ -128,7 +128,6 @@ func New(opts Options) (*API, error) { log.With(l, "version", "v2"), opts.Registry, ) - if err != nil { return nil, err } diff --git a/api/v1/api.go b/api/v1/api.go index 29789867..39018a75 100644 --- a/api/v1/api.go +++ b/api/v1/api.go @@ -171,7 +171,7 @@ func (api *API) receivers(w http.ResponseWriter, req *http.Request) { func (api *API) status(w http.ResponseWriter, req *http.Request) { api.mtx.RLock() - var status = struct { + status := struct { ConfigYAML string `json:"configYAML"` ConfigJSON *config.Config `json:"configJSON"` VersionInfo map[string]string `json:"versionInfo"` @@ -618,13 +618,13 @@ func (api *API) listSilences(w http.ResponseWriter, r *http.Request) { } } - sort.Slice(active, func(i int, j int) bool { + sort.Slice(active, func(i, j int) bool { return active[i].EndsAt.Before(active[j].EndsAt) }) - sort.Slice(pending, func(i int, j int) bool { + sort.Slice(pending, func(i, j int) bool { return pending[i].StartsAt.Before(pending[j].EndsAt) }) - sort.Slice(expired, func(i int, j int) bool { + sort.Slice(expired, func(i, j int) bool { return expired[i].EndsAt.After(expired[j].EndsAt) }) diff --git a/api/v1/api_test.go b/api/v1/api_test.go index d8c4483d..434ec51e 100644 --- a/api/v1/api_test.go +++ b/api/v1/api_test.go @@ -62,6 +62,7 @@ func (f *fakeAlerts) Get(model.Fingerprint) (*types.Alert, error) { return nil, func (f *fakeAlerts) Put(alerts ...*types.Alert) error { return f.err } + func (f *fakeAlerts) GetPending() provider.AlertIterator { ch := make(chan *types.Alert) done := make(chan struct{}) @@ -158,31 +159,31 @@ func TestAddAlerts(t *testing.T) { func TestListAlerts(t *testing.T) { now := time.Now() alerts := []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{"state": "active", "alertname": "alert1"}, StartsAt: now.Add(-time.Minute), }, }, - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{"state": "unprocessed", "alertname": "alert2"}, StartsAt: now.Add(-time.Minute), }, }, - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{"state": "suppressed", "silenced_by": "abc", "alertname": "alert3"}, StartsAt: now.Add(-time.Minute), }, }, - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{"state": "suppressed", "inhibited_by": "abc", "alertname": "alert4"}, StartsAt: now.Add(-time.Minute), }, }, - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{"alertname": "alert5"}, StartsAt: now.Add(-2 * time.Minute), diff --git a/api/v2/api.go b/api/v2/api.go index da4797dc..b21b36cd 100644 --- a/api/v2/api.go +++ b/api/v2/api.go @@ -73,9 +73,11 @@ type API struct { Handler http.Handler } -type groupsFn func(func(*dispatch.Route) bool, func(*types.Alert, time.Time) bool) (dispatch.AlertGroups, map[prometheus_model.Fingerprint][]string) -type getAlertStatusFn func(prometheus_model.Fingerprint) types.AlertStatus -type setAlertStatusFn func(prometheus_model.LabelSet) +type ( + groupsFn func(func(*dispatch.Route) bool, func(*types.Alert, time.Time) bool) (dispatch.AlertGroups, map[prometheus_model.Fingerprint][]string) + getAlertStatusFn func(prometheus_model.Fingerprint) types.AlertStatus + setAlertStatusFn func(prometheus_model.LabelSet) +) // NewAPI returns a new Alertmanager API v2 func NewAPI( @@ -524,13 +526,11 @@ func (api *API) getSilencesHandler(params silence_ops.GetSilencesParams) middlew return silence_ops.NewGetSilencesOK().WithPayload(sils) } -var ( - silenceStateOrder = map[types.SilenceState]int{ - types.SilenceStateActive: 1, - types.SilenceStatePending: 2, - types.SilenceStateExpired: 3, - } -) +var silenceStateOrder = map[types.SilenceState]int{ + types.SilenceStateActive: 1, + types.SilenceStatePending: 2, + types.SilenceStateExpired: 3, +} // SortSilences sorts first according to the state "active, pending, expired" // then by end time or start time depending on the state. diff --git a/api/v2/api_test.go b/api/v2/api_test.go index 2527c96d..8f0c80a9 100644 --- a/api/v2/api_test.go +++ b/api/v2/api_test.go @@ -72,7 +72,7 @@ func TestGetStatusHandlerWithNilPeer(t *testing.T) { } } -func assertEqualStrings(t *testing.T, expected string, actual string) { +func assertEqualStrings(t *testing.T, expected, actual string) { if expected != actual { t.Fatal("expected: ", expected, ", actual: ", actual) } @@ -90,10 +90,9 @@ func newSilences(t *testing.T) *silence.Silences { return silences } -func gettableSilence(id string, state string, - updatedAt string, start string, end string, +func gettableSilence(id, state string, + updatedAt, start, end string, ) *open_api_models.GettableSilence { - updAt, err := strfmt.ParseDateTime(updatedAt) if err != nil { panic(err) @@ -122,7 +121,6 @@ func gettableSilence(id string, state string, } func TestGetSilencesHandler(t *testing.T) { - updateTime := "2019-01-01T12:00:00+00:00" silences := []*open_api_models.GettableSilence{ gettableSilence("silence-6-expired", "expired", updateTime, @@ -313,7 +311,7 @@ func TestPostSilencesHandler(t *testing.T) { } } -func createSilenceMatcher(name string, pattern string, matcherType silencepb.Matcher_Type) *silencepb.Matcher { +func createSilenceMatcher(name, pattern string, matcherType silencepb.Matcher_Type) *silencepb.Matcher { return &silencepb.Matcher{ Name: name, Pattern: pattern, @@ -321,7 +319,7 @@ func createSilenceMatcher(name string, pattern string, matcherType silencepb.Mat } } -func createLabelMatcher(name string, value string, matchType labels.MatchType) *labels.Matcher { +func createLabelMatcher(name, value string, matchType labels.MatchType) *labels.Matcher { matcher, _ := labels.NewMatcher(matchType, name, value) return matcher } @@ -453,8 +451,8 @@ func TestAlertToOpenAPIAlert(t *testing.T) { UpdatedAt: convertDateTime(updated), Fingerprint: &fp, Receivers: []*open_api_models.Receiver{ - &open_api_models.Receiver{Name: &receivers[0]}, - &open_api_models.Receiver{Name: &receivers[1]}, + {Name: &receivers[0]}, + {Name: &receivers[1]}, }, }, openAPIAlert) } diff --git a/api/v2/compat.go b/api/v2/compat.go index 6b948c2f..112bfc4f 100644 --- a/api/v2/compat.go +++ b/api/v2/compat.go @@ -18,10 +18,11 @@ import ( "time" "github.com/go-openapi/strfmt" + prometheus_model "github.com/prometheus/common/model" + open_api_models "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/silence/silencepb" "github.com/prometheus/alertmanager/types" - prometheus_model "github.com/prometheus/common/model" ) // GettableSilenceFromProto converts *silencepb.Silence to open_api_models.GettableSilence. diff --git a/cli/alert_add.go b/cli/alert_add.go index 7ef874f9..aa5b633d 100644 --- a/cli/alert_add.go +++ b/cli/alert_add.go @@ -15,14 +15,14 @@ package cli import ( "context" - "fmt" "time" "github.com/go-openapi/strfmt" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/api/v2/client/alert" "github.com/prometheus/alertmanager/api/v2/models" - kingpin "gopkg.in/alecthomas/kingpin.v2" ) type alertAddCmd struct { @@ -70,7 +70,6 @@ func configureAddAlertCmd(cc *kingpin.CmdClause) { } func (a *alertAddCmd) addAlert(ctx context.Context, _ *kingpin.ParseContext) error { - if len(a.labels) > 0 { // Allow the alertname label to be defined implicitly as the first argument rather // than explicitly as a key=value pair. diff --git a/cli/alert_query.go b/cli/alert_query.go index 850bfcaf..83fd7474 100644 --- a/cli/alert_query.go +++ b/cli/alert_query.go @@ -18,7 +18,7 @@ import ( "errors" "fmt" - kingpin "gopkg.in/alecthomas/kingpin.v2" + "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/alertmanager/api/v2/client/alert" "github.com/prometheus/alertmanager/cli/format" @@ -102,7 +102,6 @@ func (a *alertQueryCmd) queryAlerts(ctx context.Context, _ *kingpin.ParseContext amclient := NewAlertmanagerClient(alertmanagerURL) getOk, err := amclient.Alert.GetAlerts(alertParams) - if err != nil { return err } diff --git a/cli/check_config.go b/cli/check_config.go index 515a8193..00dca985 100644 --- a/cli/check_config.go +++ b/cli/check_config.go @@ -17,9 +17,10 @@ import ( "fmt" "os" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/config" "github.com/prometheus/alertmanager/template" - "gopkg.in/alecthomas/kingpin.v2" ) // TODO: This can just be a type that is []string, doesn't have to be a struct diff --git a/cli/format/format.go b/cli/format/format.go index d0cf9d57..efda7baa 100644 --- a/cli/format/format.go +++ b/cli/format/format.go @@ -17,18 +17,16 @@ import ( "io" "time" - kingpin "gopkg.in/alecthomas/kingpin.v2" - "github.com/go-openapi/strfmt" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/pkg/labels" ) const DefaultDateFormat = "2006-01-02 15:04:05 MST" -var ( - dateFormat *string -) +var dateFormat *string func InitFormatFlags(app *kingpin.Application) { dateFormat = app.Flag("date.format", "Format of date output").Default(DefaultDateFormat).String() diff --git a/cli/format/sort.go b/cli/format/sort.go index 3c0f3bdf..7179fa0c 100644 --- a/cli/format/sort.go +++ b/cli/format/sort.go @@ -49,7 +49,6 @@ func (s ByAddress) Less(i, j int) bool { p1, _ := strconv.Atoi(port1) p2, _ := strconv.Atoi(port2) return p1 < p2 - } else { - return bytes.Compare(net.ParseIP(ip1), net.ParseIP(ip2)) < 0 } + return bytes.Compare(net.ParseIP(ip1), net.ParseIP(ip2)) < 0 } diff --git a/cli/root.go b/cli/root.go index 95b35103..b3b1d512 100644 --- a/cli/root.go +++ b/cli/root.go @@ -24,7 +24,7 @@ import ( promconfig "github.com/prometheus/common/config" "github.com/prometheus/common/version" "golang.org/x/mod/semver" - kingpin "gopkg.in/alecthomas/kingpin.v2" + "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/alertmanager/api/v2/client" "github.com/prometheus/alertmanager/cli/config" @@ -127,9 +127,7 @@ func NewAlertmanagerClient(amURL *url.URL) *client.Alertmanager { // Execute is the main function for the amtool command func Execute() { - var ( - app = kingpin.New("amtool", helpRoot).UsageWriter(os.Stdout) - ) + app := kingpin.New("amtool", helpRoot).UsageWriter(os.Stdout) format.InitFormatFlags(app) diff --git a/cli/routing.go b/cli/routing.go index aa526d3f..00e90da1 100644 --- a/cli/routing.go +++ b/cli/routing.go @@ -19,10 +19,10 @@ import ( "fmt" "github.com/xlab/treeprint" + "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/dispatch" - kingpin "gopkg.in/alecthomas/kingpin.v2" ) type routingShow struct { @@ -75,7 +75,7 @@ func (c *routingShow) routingShowAction(ctx context.Context, _ *kingpin.ParseCon return nil } -func getRouteTreeSlug(route *dispatch.Route, showContinue bool, showReceiver bool) string { +func getRouteTreeSlug(route *dispatch.Route, showContinue, showReceiver bool) string { var branchSlug bytes.Buffer if route.Matchers.Len() == 0 { branchSlug.WriteString("default-route") diff --git a/cli/silence_add.go b/cli/silence_add.go index 30d4b535..5d42158d 100644 --- a/cli/silence_add.go +++ b/cli/silence_add.go @@ -22,7 +22,7 @@ import ( "github.com/go-openapi/strfmt" "github.com/prometheus/common/model" - kingpin "gopkg.in/alecthomas/kingpin.v2" + "gopkg.in/alecthomas/kingpin.v2" "github.com/prometheus/alertmanager/api/v2/client/silence" "github.com/prometheus/alertmanager/api/v2/models" @@ -83,7 +83,6 @@ func configureSilenceAddCmd(cc *kingpin.CmdClause) { addCmd.Flag("comment", "A comment to help describe the silence").Short('c').StringVar(&c.comment) addCmd.Arg("matcher-groups", "Query filter").StringsVar(&c.matchers) addCmd.Action(execWithTimeout(c.add)) - } func (c *silenceAddCmd) add(ctx context.Context, _ *kingpin.ParseContext) error { diff --git a/cli/silence_expire.go b/cli/silence_expire.go index 5bd65c9f..d2e73579 100644 --- a/cli/silence_expire.go +++ b/cli/silence_expire.go @@ -18,8 +18,9 @@ import ( "errors" "github.com/go-openapi/strfmt" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/api/v2/client/silence" - kingpin "gopkg.in/alecthomas/kingpin.v2" ) type silenceExpireCmd struct { diff --git a/cli/silence_update.go b/cli/silence_update.go index 99251c3b..1ab29e37 100644 --- a/cli/silence_update.go +++ b/cli/silence_update.go @@ -19,13 +19,13 @@ import ( "fmt" "time" - kingpin "gopkg.in/alecthomas/kingpin.v2" - "github.com/go-openapi/strfmt" + "github.com/prometheus/common/model" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/api/v2/client/silence" "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/cli/format" - "github.com/prometheus/common/model" ) type silenceUpdateCmd struct { diff --git a/cli/template_render.go b/cli/template_render.go index ded97ba4..c58d922a 100644 --- a/cli/template_render.go +++ b/cli/template_render.go @@ -21,8 +21,9 @@ import ( "os" "time" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/template" - kingpin "gopkg.in/alecthomas/kingpin.v2" ) var defaultData = template.Data{ diff --git a/cli/test_routing.go b/cli/test_routing.go index 3d0216dd..4206bfb7 100644 --- a/cli/test_routing.go +++ b/cli/test_routing.go @@ -19,10 +19,11 @@ import ( "os" "strings" + "github.com/xlab/treeprint" + "gopkg.in/alecthomas/kingpin.v2" + "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/dispatch" - "github.com/xlab/treeprint" - kingpin "gopkg.in/alecthomas/kingpin.v2" ) const routingTestHelp = `Test alert routing @@ -40,7 +41,7 @@ Example: ` func configureRoutingTestCmd(cc *kingpin.CmdClause, c *routingShow) { - var routingTestCmd = cc.Command("test", routingTestHelp) + routingTestCmd := cc.Command("test", routingTestHelp) routingTestCmd.Flag("verify.receivers", "Checks if specified receivers matches resolved receivers. The command fails if the labelset does not route to the specified receivers.").StringVar(&c.expectedReceivers) routingTestCmd.Flag("tree", "Prints out matching routes tree.").BoolVar(&c.debugTree) diff --git a/cli/test_routing_test.go b/cli/test_routing_test.go index deb813c9..104d3a36 100644 --- a/cli/test_routing_test.go +++ b/cli/test_routing_test.go @@ -43,10 +43,10 @@ func checkResolvedReceivers(mainRoute *dispatch.Route, ls models.LabelSet, expec func TestRoutingTest(t *testing.T) { tests := []*routingTestDefinition{ - &routingTestDefinition{configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "1"}, expectedReceivers: []string{"test1"}}, - &routingTestDefinition{configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "2"}, expectedReceivers: []string{"test1", "test2"}}, - &routingTestDefinition{configFile: "testdata/conf.routing-reverted.yml", alert: models.LabelSet{"test": "2"}, expectedReceivers: []string{"test2", "test1"}}, - &routingTestDefinition{configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "volovina"}, expectedReceivers: []string{"default"}}, + {configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "1"}, expectedReceivers: []string{"test1"}}, + {configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "2"}, expectedReceivers: []string{"test1", "test2"}}, + {configFile: "testdata/conf.routing-reverted.yml", alert: models.LabelSet{"test": "2"}, expectedReceivers: []string{"test2", "test1"}}, + {configFile: "testdata/conf.routing.yml", alert: models.LabelSet{"test": "volovina"}, expectedReceivers: []string{"default"}}, } for _, test := range tests { diff --git a/cluster/channel.go b/cluster/channel.go index f4ea4dc0..ba0b834c 100644 --- a/cluster/channel.go +++ b/cluster/channel.go @@ -21,8 +21,9 @@ import ( "github.com/go-kit/log/level" "github.com/gogo/protobuf/proto" "github.com/hashicorp/memberlist" - "github.com/prometheus/alertmanager/cluster/clusterpb" "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/alertmanager/cluster/clusterpb" ) // Channel allows clients to send messages for a specific state type that will be diff --git a/cluster/channel_test.go b/cluster/channel_test.go index 362648b9..7464b11a 100644 --- a/cluster/channel_test.go +++ b/cluster/channel_test.go @@ -45,7 +45,7 @@ func TestOversizedMessagesGossiped(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) c := newChannel( func(_ []byte) {}, - func() []*memberlist.Node { return []*memberlist.Node{&memberlist.Node{}} }, + func() []*memberlist.Node { return []*memberlist.Node{{}} }, func(_ *memberlist.Node, _ []byte) error { sent = true; cancel(); return nil }, ) diff --git a/cluster/cluster.go b/cluster/cluster.go index 6de11c53..ba7fdb9e 100644 --- a/cluster/cluster.go +++ b/cluster/cluster.go @@ -119,7 +119,7 @@ func (s PeerStatus) String() string { const ( DefaultPushPullInterval = 60 * time.Second DefaultGossipInterval = 200 * time.Millisecond - DefaultTcpTimeout = 10 * time.Second + DefaultTCPTimeout = 10 * time.Second DefaultProbeTimeout = 500 * time.Millisecond DefaultProbeInterval = 1 * time.Second DefaultReconnectInterval = 10 * time.Second @@ -254,7 +254,8 @@ func Create( func (p *Peer) Join( reconnectInterval time.Duration, - reconnectTimeout time.Duration) error { + reconnectTimeout time.Duration, +) error { n, err := p.mlist.Join(p.resolvedPeers) if err != nil { level.Warn(p.logger).Log("msg", "failed to join cluster", "err", err) @@ -784,7 +785,7 @@ func resolvePeers(ctx context.Context, peers []string, myAddress string, res *ne return resolvedPeers, nil } -func removeMyAddr(ips []net.IPAddr, targetPort string, myAddr string) []net.IPAddr { +func removeMyAddr(ips []net.IPAddr, targetPort, myAddr string) []net.IPAddr { var result []net.IPAddr for _, ip := range ips { diff --git a/cluster/cluster_test.go b/cluster/cluster_test.go index 56269896..87c31d13 100644 --- a/cluster/cluster_test.go +++ b/cluster/cluster_test.go @@ -49,7 +49,7 @@ func testJoinLeave(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -83,7 +83,7 @@ func testJoinLeave(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -118,7 +118,7 @@ func testReconnect(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -143,7 +143,7 @@ func testReconnect(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -183,7 +183,7 @@ func testRemoveFailedPeers(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -234,7 +234,7 @@ func testInitiallyFailingPeers(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, nil, @@ -281,7 +281,7 @@ func testTLSConnection(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, tlsTransportConfig1, @@ -312,7 +312,7 @@ func testTLSConnection(t *testing.T) { true, DefaultPushPullInterval, DefaultGossipInterval, - DefaultTcpTimeout, + DefaultTCPTimeout, DefaultProbeTimeout, DefaultProbeInterval, tlsTransportConfig2, diff --git a/cluster/connection_pool.go b/cluster/connection_pool.go index 03014323..bd6695aa 100644 --- a/cluster/connection_pool.go +++ b/cluster/connection_pool.go @@ -33,7 +33,7 @@ type connectionPool struct { func newConnectionPool(tlsClientCfg *tls.Config) (*connectionPool, error) { cache, err := lru.NewWithEvict( - capacity, func(_ interface{}, value interface{}) { + capacity, func(_, value interface{}) { conn, ok := value.(*tlsConn) if ok { _ = conn.Close() diff --git a/cluster/delegate.go b/cluster/delegate.go index 50addcde..9957f69b 100644 --- a/cluster/delegate.go +++ b/cluster/delegate.go @@ -20,8 +20,9 @@ import ( "github.com/go-kit/log/level" "github.com/gogo/protobuf/proto" "github.com/hashicorp/memberlist" - "github.com/prometheus/alertmanager/cluster/clusterpb" "github.com/prometheus/client_golang/prometheus" + + "github.com/prometheus/alertmanager/cluster/clusterpb" ) const ( diff --git a/cluster/tls_connection.go b/cluster/tls_connection.go index f5a3326f..21ffc959 100644 --- a/cluster/tls_connection.go +++ b/cluster/tls_connection.go @@ -66,7 +66,6 @@ func (conn *tlsConn) Write(b []byte) (int, error) { conn.mtx.Lock() defer conn.mtx.Unlock() n, err := conn.connection.Write(b) - if err != nil { conn.live = false } diff --git a/cluster/tls_transport.go b/cluster/tls_transport.go index ca8d04c2..16fbe251 100644 --- a/cluster/tls_transport.go +++ b/cluster/tls_transport.go @@ -194,7 +194,7 @@ func (t *TLSTransport) Shutdown() error { // from the pool, and writes to it. It also returns a timestamp of when // the packet was written. func (t *TLSTransport) WriteTo(b []byte, addr string) (time.Time, error) { - conn, err := t.connPool.borrowConnection(addr, DefaultTcpTimeout) + conn, err := t.connPool.borrowConnection(addr, DefaultTCPTimeout) if err != nil { t.writeErrs.WithLabelValues("packet").Inc() return time.Now(), errors.Wrap(err, "failed to dial") diff --git a/cluster/tls_transport_test.go b/cluster/tls_transport_test.go index 3b4aca30..3c3a11cb 100644 --- a/cluster/tls_transport_test.go +++ b/cluster/tls_transport_test.go @@ -66,23 +66,23 @@ func TestFinalAdvertiseAddr(t *testing.T) { testCases := []struct { bindAddr string bindPort int - inputIp string + inputIP string inputPort int - expectedIp string + expectedIP string expectedPort int expectedError string }{ - {bindAddr: localhost, bindPort: 9094, inputIp: "10.0.0.5", inputPort: 54231, expectedIp: "10.0.0.5", expectedPort: 54231}, - {bindAddr: localhost, bindPort: 9093, inputIp: "invalid", inputPort: 54231, expectedError: "failed to parse advertise address \"invalid\""}, - {bindAddr: "0.0.0.0", bindPort: 0, inputIp: "", inputPort: 0, expectedIp: "random"}, - {bindAddr: localhost, bindPort: 0, inputIp: "", inputPort: 0, expectedIp: localhost}, - {bindAddr: localhost, bindPort: 9095, inputIp: "", inputPort: 0, expectedIp: localhost, expectedPort: 9095}, + {bindAddr: localhost, bindPort: 9094, inputIP: "10.0.0.5", inputPort: 54231, expectedIP: "10.0.0.5", expectedPort: 54231}, + {bindAddr: localhost, bindPort: 9093, inputIP: "invalid", inputPort: 54231, expectedError: "failed to parse advertise address \"invalid\""}, + {bindAddr: "0.0.0.0", bindPort: 0, inputIP: "", inputPort: 0, expectedIP: "random"}, + {bindAddr: localhost, bindPort: 0, inputIP: "", inputPort: 0, expectedIP: localhost}, + {bindAddr: localhost, bindPort: 9095, inputIP: "", inputPort: 0, expectedIP: localhost, expectedPort: 9095}, } for _, tc := range testCases { tlsConf := mustTLSTransportConfig("testdata/tls_config_node1.yml") transport, err := NewTLSTransport(context2.Background(), logger, nil, tc.bindAddr, tc.bindPort, tlsConf) require.Nil(t, err) - ip, port, err := transport.FinalAdvertiseAddr(tc.inputIp, tc.inputPort) + ip, port, err := transport.FinalAdvertiseAddr(tc.inputIP, tc.inputPort) if len(tc.expectedError) > 0 { require.Equal(t, tc.expectedError, err.Error()) } else { @@ -93,10 +93,10 @@ func TestFinalAdvertiseAddr(t *testing.T) { } else { require.Equal(t, tc.expectedPort, port) } - if tc.expectedIp == "random" { + if tc.expectedIP == "random" { require.NotNil(t, ip) } else { - require.Equal(t, tc.expectedIp, ip.String()) + require.Equal(t, tc.expectedIP, ip.String()) } } transport.Shutdown() diff --git a/cmd/alertmanager/main.go b/cmd/alertmanager/main.go index 6920c46f..876996f9 100644 --- a/cmd/alertmanager/main.go +++ b/cmd/alertmanager/main.go @@ -210,7 +210,7 @@ func run() int { peerTimeout = kingpin.Flag("cluster.peer-timeout", "Time to wait between peers to send notifications.").Default("15s").Duration() gossipInterval = kingpin.Flag("cluster.gossip-interval", "Interval between sending gossip messages. By lowering this value (more frequent) gossip messages are propagated across the cluster more quickly at the expense of increased bandwidth.").Default(cluster.DefaultGossipInterval.String()).Duration() pushPullInterval = kingpin.Flag("cluster.pushpull-interval", "Interval for gossip state syncs. Setting this interval lower (more frequent) will increase convergence speeds across larger clusters at the expense of increased bandwidth usage.").Default(cluster.DefaultPushPullInterval.String()).Duration() - tcpTimeout = kingpin.Flag("cluster.tcp-timeout", "Timeout for establishing a stream connection with a remote node for a full state sync, and for stream read and write operations.").Default(cluster.DefaultTcpTimeout.String()).Duration() + tcpTimeout = kingpin.Flag("cluster.tcp-timeout", "Timeout for establishing a stream connection with a remote node for a full state sync, and for stream read and write operations.").Default(cluster.DefaultTCPTimeout.String()).Duration() probeTimeout = kingpin.Flag("cluster.probe-timeout", "Timeout to wait for an ack from a probed node before assuming it is unhealthy. This should be set to 99-percentile of RTT (round-trip time) on your network.").Default(cluster.DefaultProbeTimeout.String()).Duration() probeInterval = kingpin.Flag("cluster.probe-interval", "Interval between random node probes. Setting this lower (more frequent) will cause the cluster to detect failed nodes more quickly at the expense of increased bandwidth usage.").Default(cluster.DefaultProbeInterval.String()).Duration() settleTimeout = kingpin.Flag("cluster.settle-timeout", "Maximum time to wait for cluster connections to settle before evaluating notifications.").Default(cluster.DefaultPushPullInterval.String()).Duration() @@ -232,7 +232,7 @@ func run() int { level.Info(logger).Log("msg", "Starting Alertmanager", "version", version.Info()) level.Info(logger).Log("build_context", version.BuildContext()) - err := os.MkdirAll(*dataDir, 0777) + err := os.MkdirAll(*dataDir, 0o777) if err != nil { level.Error(logger).Log("msg", "Unable to create data directory", "err", err) return 1 @@ -372,7 +372,6 @@ func run() int { Registry: prometheus.DefaultRegisterer, GroupFunc: groupFn, }) - if err != nil { level.Error(logger).Log("err", errors.Wrap(err, "failed to create API")) return 1 diff --git a/cmd/alertmanager/main_test.go b/cmd/alertmanager/main_test.go index fd62c8a4..ff3460a2 100644 --- a/cmd/alertmanager/main_test.go +++ b/cmd/alertmanager/main_test.go @@ -39,10 +39,10 @@ func TestBuildReceiverIntegrations(t *testing.T) { receiver: &config.Receiver{ Name: "foo", WebhookConfigs: []*config.WebhookConfig{ - &config.WebhookConfig{ + { HTTPConfig: &commoncfg.HTTPClientConfig{}, }, - &config.WebhookConfig{ + { HTTPConfig: &commoncfg.HTTPClientConfig{}, NotifierConfig: config.NotifierConfig{ VSendResolved: true, @@ -59,7 +59,7 @@ func TestBuildReceiverIntegrations(t *testing.T) { receiver: &config.Receiver{ Name: "foo", WebhookConfigs: []*config.WebhookConfig{ - &config.WebhookConfig{ + { HTTPConfig: &commoncfg.HTTPClientConfig{ TLSConfig: commoncfg.TLSConfig{ CAFile: "not_existing", diff --git a/config/config.go b/config/config.go index 448f1853..4d1e76c7 100644 --- a/config/config.go +++ b/config/config.go @@ -580,7 +580,7 @@ func checkTimeInterval(r *Route, timeIntervals map[string]struct{}) error { // DefaultGlobalConfig returns GlobalConfig with default values. func DefaultGlobalConfig() GlobalConfig { - var defaultHTTPConfig = commoncfg.DefaultHTTPClientConfig + defaultHTTPConfig := commoncfg.DefaultHTTPClientConfig return GlobalConfig{ ResolveTimeout: model.Duration(5 * time.Minute), HTTPConfig: &defaultHTTPConfig, diff --git a/config/config_test.go b/config/config_test.go index 73020a33..921eabd4 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -79,7 +79,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestReceiverExists(t *testing.T) { @@ -100,7 +99,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestReceiverExistsForDeepSubRoute(t *testing.T) { @@ -128,7 +126,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestReceiverHasName(t *testing.T) { @@ -148,7 +145,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestMuteTimeExists(t *testing.T) { @@ -174,7 +170,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestActiveTimeExists(t *testing.T) { @@ -200,7 +195,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestTimeIntervalHasName(t *testing.T) { @@ -233,7 +227,6 @@ route: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestMuteTimeNoDuplicates(t *testing.T) { @@ -271,7 +264,6 @@ route: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestGroupByHasNoDuplicatedLabels(t *testing.T) { @@ -292,7 +284,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestWildcardGroupByWithOtherGroupByLabels(t *testing.T) { @@ -333,7 +324,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestRootRouteExists(t *testing.T) { @@ -351,7 +341,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestRootRouteNoMuteTimes(t *testing.T) { @@ -381,7 +370,6 @@ route: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestRootRouteNoActiveTimes(t *testing.T) { @@ -476,7 +464,6 @@ receivers: if err.Error() != expected { t.Errorf("\nexpected:\n%q\ngot:\n%q", expected, err.Error()) } - } func TestGroupIntervalIsGreaterThanZero(t *testing.T) { @@ -859,13 +846,12 @@ receivers: func TestEmptyFieldsAndRegex(t *testing.T) { boolFoo := true - var regexpFoo = Regexp{ + regexpFoo := Regexp{ Regexp: regexp.MustCompile("^(?:^(foo1|foo2|baz)$)$"), original: "^(foo1|foo2|baz)$", } - var expectedConf = Config{ - + expectedConf := Config{ Global: &GlobalConfig{ HTTPConfig: &commoncfg.HTTPClientConfig{ FollowRedirects: true, @@ -972,7 +958,7 @@ func TestSMTPHello(t *testing.T) { } const refValue = "host.example.org" - var hostName = c.Global.SMTPHello + hostName := c.Global.SMTPHello if hostName != refValue { t.Errorf("Invalid SMTP Hello hostname: %s\nExpected: %s", hostName, refValue) } @@ -995,7 +981,7 @@ func TestVictorOpsDefaultAPIKey(t *testing.T) { t.Fatalf("Error parsing %s: %s", "testdata/conf.victorops-default-apikey.yml", err) } - var defaultKey = conf.Global.VictorOpsAPIKey + defaultKey := conf.Global.VictorOpsAPIKey if defaultKey != conf.Receivers[0].VictorOpsConfigs[0].APIKey { t.Fatalf("Invalid victorops key: %s\nExpected: %s", conf.Receivers[0].VictorOpsConfigs[0].APIKey, defaultKey) } @@ -1020,7 +1006,7 @@ func TestOpsGenieDefaultAPIKey(t *testing.T) { t.Fatalf("Error parsing %s: %s", "testdata/conf.opsgenie-default-apikey.yml", err) } - var defaultKey = conf.Global.OpsGenieAPIKey + defaultKey := conf.Global.OpsGenieAPIKey if defaultKey != conf.Receivers[0].OpsGenieConfigs[0].APIKey { t.Fatalf("Invalid OpsGenie key: %s\nExpected: %s", conf.Receivers[0].OpsGenieConfigs[0].APIKey, defaultKey) } @@ -1035,7 +1021,7 @@ func TestOpsGenieDefaultAPIKeyFile(t *testing.T) { t.Fatalf("Error parsing %s: %s", "testdata/conf.opsgenie-default-apikey-file.yml", err) } - var defaultKey = conf.Global.OpsGenieAPIKeyFile + defaultKey := conf.Global.OpsGenieAPIKeyFile if defaultKey != conf.Receivers[0].OpsGenieConfigs[0].APIKeyFile { t.Fatalf("Invalid OpsGenie key_file: %s\nExpected: %s", conf.Receivers[0].OpsGenieConfigs[0].APIKeyFile, defaultKey) } diff --git a/config/coordinator.go b/config/coordinator.go index 499e939e..5ee44f81 100644 --- a/config/coordinator.go +++ b/config/coordinator.go @@ -150,7 +150,7 @@ func md5HashAsMetricValue(data []byte) float64 { sum := md5.Sum(data) // We only want 48 bits as a float64 only has a 53 bit mantissa. smallSum := sum[0:6] - var bytes = make([]byte, 8) + bytes := make([]byte, 8) copy(bytes, smallSum) return float64(binary.LittleEndian.Uint64(bytes)) } diff --git a/config/notifiers.go b/config/notifiers.go index a2cadf9e..682b38df 100644 --- a/config/notifiers.go +++ b/config/notifiers.go @@ -20,7 +20,6 @@ import ( "time" "github.com/pkg/errors" - commoncfg "github.com/prometheus/common/config" "github.com/prometheus/common/sigv4" ) @@ -452,7 +451,7 @@ func (c *WechatConfig) UnmarshalYAML(unmarshal func(interface{}) error) error { } if !wechatTypeMatcher.MatchString(c.MessageType) { - return errors.Errorf("WeChat message type %q does not match valid options %s", c.MessageType, wechatValidTypesRe) + return errors.Errorf("weChat message type %q does not match valid options %s", c.MessageType, wechatValidTypesRe) } return nil @@ -498,12 +497,12 @@ func (c *OpsGenieConfig) UnmarshalYAML(unmarshal func(interface{}) error) error for _, r := range c.Responders { if r.ID == "" && r.Username == "" && r.Name == "" { - return errors.Errorf("OpsGenieConfig responder %v has to have at least one of id, username or name specified", r) + return errors.Errorf("opsGenieConfig responder %v has to have at least one of id, username or name specified", r) } r.Type = strings.ToLower(r.Type) if !opsgenieTypeMatcher.MatchString(r.Type) { - return errors.Errorf("OpsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe) + return errors.Errorf("opsGenieConfig responder %v type does not match valid options %s", r, opsgenieValidTypesRe) } } @@ -552,7 +551,7 @@ func (c *VictorOpsConfig) UnmarshalYAML(unmarshal func(interface{}) error) error for _, v := range reservedFields { if _, ok := c.CustomFields[v]; ok { - return fmt.Errorf("VictorOps config contains custom field %s which cannot be used as it conflicts with the fixed/static fields", v) + return fmt.Errorf("victorOps config contains custom field %s which cannot be used as it conflicts with the fixed/static fields", v) } } diff --git a/config/notifiers_test.go b/config/notifiers_test.go index 93b9dca2..4d32514f 100644 --- a/config/notifiers_test.go +++ b/config/notifiers_test.go @@ -92,8 +92,7 @@ service_key: '' } func TestPagerdutyDetails(t *testing.T) { - - var tests = []struct { + tests := []struct { in string checkFn func(map[string]string) }{ @@ -137,7 +136,6 @@ details: for _, tc := range tests { var cfg PagerdutyConfig err := yaml.UnmarshalStrict([]byte(tc.in), &cfg) - if err != nil { t.Errorf("expected no error, got:%v", err) } @@ -189,7 +187,6 @@ url: 'http://example.com' ` var cfg WebhookConfig err := yaml.UnmarshalStrict([]byte(in), &cfg) - if err != nil { t.Fatalf("no error expected, returned:\n%v", err.Error()) } @@ -205,7 +202,6 @@ http_config: ` var cfg WebhookConfig err := yaml.UnmarshalStrict([]byte(in), &cfg) - if err != nil { t.Fatalf("no error expected, returned:\n%v", err.Error()) } @@ -245,7 +241,7 @@ custom_fields: var cfg VictorOpsConfig err := yaml.UnmarshalStrict([]byte(in), &cfg) - expected := "VictorOps config contains custom field entity_state which cannot be used as it conflicts with the fixed/static fields" + expected := "victorOps config contains custom field entity_state which cannot be used as it conflicts with the fixed/static fields" if err == nil { t.Fatalf("no error returned, expected:\n%v", expected) @@ -276,7 +272,6 @@ custom_fields: if val != expected { t.Errorf("\nexpected custom field my_special_field value:\n%v\ngot:\n%v", expected, val) } - } func TestPushoverUserKeyIsPresent(t *testing.T) { @@ -315,7 +310,7 @@ token: '' } func TestLoadSlackConfiguration(t *testing.T) { - var tests = []struct { + tests := []struct { in string expected SlackConfig }{ @@ -327,9 +322,11 @@ channel: engineering title_link: http://example.com/ image_url: https://example.com/logo.png `, - expected: SlackConfig{Color: "green", Username: "mark", Channel: "engineering", + expected: SlackConfig{ + Color: "green", Username: "mark", Channel: "engineering", TitleLink: "http://example.com/", - ImageURL: "https://example.com/logo.png"}, + ImageURL: "https://example.com/logo.png", + }, }, { in: ` @@ -341,9 +338,12 @@ mrkdwn_in: - pretext - text `, - expected: SlackConfig{Color: "green", Username: "mark", Channel: "alerts", - MrkdwnIn: []string{"pretext", "text"}, TitleLink: "http://example.com/alert1"}, - }} + expected: SlackConfig{ + Color: "green", Username: "mark", Channel: "alerts", + MrkdwnIn: []string{"pretext", "text"}, TitleLink: "http://example.com/alert1", + }, + }, + } for _, rt := range tests { var cfg SlackConfig err := yaml.UnmarshalStrict([]byte(rt.in), &cfg) @@ -380,7 +380,7 @@ mrkdwn_in: } func TestSlackFieldConfigValidation(t *testing.T) { - var tests = []struct { + tests := []struct { in string expected string }{ @@ -449,17 +449,17 @@ fields: short: false ` expected := []*SlackField{ - &SlackField{ + { Title: "first", Value: "hello", Short: newBoolPointer(true), }, - &SlackField{ + { Title: "second", Value: "world", Short: nil, }, - &SlackField{ + { Title: "third", Value: "slack field test", Short: newBoolPointer(false), diff --git a/dispatch/dispatch_test.go b/dispatch/dispatch_test.go index 74573e00..f4f08c2a 100644 --- a/dispatch/dispatch_test.go +++ b/dispatch/dispatch_test.go @@ -42,8 +42,8 @@ func TestAggrGroup(t *testing.T) { opts := &RouteOpts{ Receiver: "n1", GroupBy: map[model.LabelName]struct{}{ - "a": struct{}{}, - "b": struct{}{}, + "a": {}, + "b": {}, }, GroupWait: 1 * time.Second, GroupInterval: 300 * time.Millisecond, @@ -270,7 +270,7 @@ func TestAggrGroup(t *testing.T) { } func TestGroupLabels(t *testing.T) { - var a = &types.Alert{ + a := &types.Alert{ Alert: model.Alert{ Labels: model.LabelSet{ "a": "v1", @@ -283,8 +283,8 @@ func TestGroupLabels(t *testing.T) { route := &Route{ RouteOpts: RouteOpts{ GroupBy: map[model.LabelName]struct{}{ - "a": struct{}{}, - "b": struct{}{}, + "a": {}, + "b": {}, }, GroupByAll: false, }, @@ -303,7 +303,7 @@ func TestGroupLabels(t *testing.T) { } func TestGroupByAllLabels(t *testing.T) { - var a = &types.Alert{ + a := &types.Alert{ Alert: model.Alert{ Labels: model.LabelSet{ "a": "v1", diff --git a/inhibit/inhibit_test.go b/inhibit/inhibit_test.go index e1074bad..1b34bf88 100644 --- a/inhibit/inhibit_test.go +++ b/inhibit/inhibit_test.go @@ -48,21 +48,21 @@ func TestInhibitRuleHasEqual(t *testing.T) { }, { // No equal labels, any source alerts satisfies the requirement. - initial: map[model.Fingerprint]*types.Alert{1: &types.Alert{}}, + initial: map[model.Fingerprint]*types.Alert{1: {}}, input: model.LabelSet{"a": "b"}, result: true, }, { // Matching but already resolved. initial: map[model.Fingerprint]*types.Alert{ - 1: &types.Alert{ + 1: { Alert: model.Alert{ Labels: model.LabelSet{"a": "b", "b": "f"}, StartsAt: now.Add(-time.Minute), EndsAt: now.Add(-time.Second), }, }, - 2: &types.Alert{ + 2: { Alert: model.Alert{ Labels: model.LabelSet{"a": "b", "b": "c"}, StartsAt: now.Add(-time.Minute), @@ -77,14 +77,14 @@ func TestInhibitRuleHasEqual(t *testing.T) { { // Matching and unresolved. initial: map[model.Fingerprint]*types.Alert{ - 1: &types.Alert{ + 1: { Alert: model.Alert{ Labels: model.LabelSet{"a": "b", "c": "d"}, StartsAt: now.Add(-time.Minute), EndsAt: now.Add(-time.Second), }, }, - 2: &types.Alert{ + 2: { Alert: model.Alert{ Labels: model.LabelSet{"a": "b", "c": "f"}, StartsAt: now.Add(-time.Minute), @@ -99,14 +99,14 @@ func TestInhibitRuleHasEqual(t *testing.T) { { // Equal label does not match. initial: map[model.Fingerprint]*types.Alert{ - 1: &types.Alert{ + 1: { Alert: model.Alert{ Labels: model.LabelSet{"a": "c", "c": "d"}, StartsAt: now.Add(-time.Minute), EndsAt: now.Add(-time.Second), }, }, - 2: &types.Alert{ + 2: { Alert: model.Alert{ Labels: model.LabelSet{"a": "c", "c": "f"}, StartsAt: now.Add(-time.Minute), @@ -233,6 +233,7 @@ func TestInhibitRuleMatches(t *testing.T) { } } } + func TestInhibitRuleMatchers(t *testing.T) { t.Parallel() diff --git a/nflog/nflog.go b/nflog/nflog.go index be2b47db..a9ddd78f 100644 --- a/nflog/nflog.go +++ b/nflog/nflog.go @@ -30,9 +30,10 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/matttproud/golang_protobuf_extensions/pbutil" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/alertmanager/cluster" pb "github.com/prometheus/alertmanager/nflog/nflogpb" - "github.com/prometheus/client_golang/prometheus" ) // ErrNotFound is returned for empty query results. diff --git a/nflog/nflogpb/set_test.go b/nflog/nflogpb/set_test.go index 5a2182a4..e1ce289d 100644 --- a/nflog/nflogpb/set_test.go +++ b/nflog/nflogpb/set_test.go @@ -26,7 +26,7 @@ func TestIsFiringSubset(t *testing.T) { subset map[uint64]struct{} expected bool }{ - {newSubset(), true}, //empty subset + {newSubset(), true}, // empty subset {newSubset(1), true}, {newSubset(2), true}, {newSubset(3), true}, @@ -54,7 +54,7 @@ func TestIsResolvedSubset(t *testing.T) { subset map[uint64]struct{} expected bool }{ - {newSubset(), true}, //empty subset + {newSubset(), true}, // empty subset {newSubset(1), true}, {newSubset(2), true}, {newSubset(3), true}, diff --git a/notify/email/email_test.go b/notify/email/email_test.go index f2127740..361aeabb 100644 --- a/notify/email/email_test.go +++ b/notify/email/email_test.go @@ -43,7 +43,7 @@ import ( commoncfg "github.com/prometheus/common/config" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" - yaml "gopkg.in/yaml.v2" + "gopkg.in/yaml.v2" "github.com/prometheus/alertmanager/config" "github.com/prometheus/alertmanager/template" @@ -115,7 +115,7 @@ func (m *mailDev) deleteAllEmails() error { } // doEmailRequest makes a request to the MailDev API. -func (m *mailDev) doEmailRequest(method string, path string) (int, []byte, error) { +func (m *mailDev) doEmailRequest(method, path string) (int, []byte, error) { req, err := http.NewRequest(method, fmt.Sprintf("%s://%s%s", m.Scheme, m.Host, path), nil) if err != nil { return 0, nil, err diff --git a/notify/notify_test.go b/notify/notify_test.go index d93aa53c..a78fbf74 100644 --- a/notify/notify_test.go +++ b/notify/notify_test.go @@ -396,7 +396,7 @@ func TestRetryStageWithError(t *testing.T) { } alerts := []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ EndsAt: time.Now().Add(time.Hour), }, @@ -437,12 +437,12 @@ func TestRetryStageNoResolved(t *testing.T) { } alerts := []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ EndsAt: time.Now().Add(-time.Hour), }, }, - &types.Alert{ + { Alert: model.Alert{ EndsAt: time.Now().Add(time.Hour), }, @@ -491,12 +491,12 @@ func TestRetryStageSendResolved(t *testing.T) { } alerts := []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ EndsAt: time.Now().Add(-time.Hour), }, }, - &types.Alert{ + { Alert: model.Alert{ EndsAt: time.Now().Add(time.Hour), }, diff --git a/notify/opsgenie/opsgenie.go b/notify/opsgenie/opsgenie.go index d2b4c3bf..856d12ef 100644 --- a/notify/opsgenie/opsgenie.go +++ b/notify/opsgenie/opsgenie.go @@ -114,7 +114,7 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) } // Like Split but filter out empty strings. -func safeSplit(s string, sep string) []string { +func safeSplit(s, sep string) []string { a := strings.Split(strings.TrimSpace(s), sep) b := a[:0] for _, x := range a { @@ -160,7 +160,7 @@ func (n *Notifier) createRequests(ctx context.Context, as ...*types.Alert) ([]*h q := resolvedEndpointURL.Query() q.Set("identifierType", "alias") resolvedEndpointURL.RawQuery = q.Encode() - var msg = &opsGenieCloseMessage{Source: tmpl(n.conf.Source)} + msg := &opsGenieCloseMessage{Source: tmpl(n.conf.Source)} var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(msg); err != nil { return nil, false, err @@ -209,7 +209,7 @@ func (n *Notifier) createRequests(ctx context.Context, as ...*types.Alert) ([]*h responders = append(responders, responder) } - var msg = &opsGenieCreateMessage{ + msg := &opsGenieCreateMessage{ Alias: alias, Message: message, Description: tmpl(n.conf.Description), @@ -233,11 +233,11 @@ func (n *Notifier) createRequests(ctx context.Context, as ...*types.Alert) ([]*h requests = append(requests, req.WithContext(ctx)) if n.conf.UpdateAlerts { - updateMessageEndpointUrl := n.conf.APIURL.Copy() - updateMessageEndpointUrl.Path += fmt.Sprintf("v2/alerts/%s/message", alias) - q := updateMessageEndpointUrl.Query() + updateMessageEndpointURL := n.conf.APIURL.Copy() + updateMessageEndpointURL.Path += fmt.Sprintf("v2/alerts/%s/message", alias) + q := updateMessageEndpointURL.Query() q.Set("identifierType", "alias") - updateMessageEndpointUrl.RawQuery = q.Encode() + updateMessageEndpointURL.RawQuery = q.Encode() updateMsgMsg := &opsGenieUpdateMessageMessage{ Message: msg.Message, } @@ -245,7 +245,7 @@ func (n *Notifier) createRequests(ctx context.Context, as ...*types.Alert) ([]*h if err := json.NewEncoder(&updateMessageBuf).Encode(updateMsgMsg); err != nil { return nil, false, err } - req, err := http.NewRequest("PUT", updateMessageEndpointUrl.String(), &updateMessageBuf) + req, err := http.NewRequest("PUT", updateMessageEndpointURL.String(), &updateMessageBuf) if err != nil { return nil, true, err } diff --git a/notify/opsgenie/opsgenie_test.go b/notify/opsgenie/opsgenie_test.go index 4f7447b5..c4db6db9 100644 --- a/notify/opsgenie/opsgenie_test.go +++ b/notify/opsgenie/opsgenie_test.go @@ -66,7 +66,7 @@ func TestOpsGenieRedactedURL(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, key) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, key) } func TestGettingOpsGegineApikeyFromFile(t *testing.T) { @@ -91,7 +91,7 @@ func TestGettingOpsGegineApikeyFromFile(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, key) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, key) } func TestOpsGenie(t *testing.T) { diff --git a/notify/pagerduty/pagerduty_test.go b/notify/pagerduty/pagerduty_test.go index ad177c73..bb843272 100644 --- a/notify/pagerduty/pagerduty_test.go +++ b/notify/pagerduty/pagerduty_test.go @@ -89,7 +89,7 @@ func TestPagerDutyRedactedURLV1(t *testing.T) { require.NoError(t, err) notifier.apiV1 = u.String() - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, key) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, key) } func TestPagerDutyRedactedURLV2(t *testing.T) { @@ -108,7 +108,7 @@ func TestPagerDutyRedactedURLV2(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, key) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, key) } func TestPagerDutyTemplating(t *testing.T) { @@ -212,7 +212,7 @@ func TestPagerDutyTemplating(t *testing.T) { ctx = notify.WithGroupKey(ctx, "1") ok, err := pd.Notify(ctx, []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{ "lbl1": "val1", diff --git a/notify/pushover/pushover_test.go b/notify/pushover/pushover_test.go index 6bfbbb4b..87a5f125 100644 --- a/notify/pushover/pushover_test.go +++ b/notify/pushover/pushover_test.go @@ -57,5 +57,5 @@ func TestPushoverRedactedURL(t *testing.T) { require.NoError(t, err) notifier.apiURL = u.String() - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, key, token) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, key, token) } diff --git a/notify/slack/slack.go b/notify/slack/slack.go index 5e8d515b..c719c0d4 100644 --- a/notify/slack/slack.go +++ b/notify/slack/slack.go @@ -18,13 +18,12 @@ import ( "context" "encoding/json" "fmt" - "github.com/go-kit/log/level" "io/ioutil" "net/http" - "github.com/pkg/errors" - "github.com/go-kit/log" + "github.com/go-kit/log/level" + "github.com/pkg/errors" commoncfg "github.com/prometheus/common/config" "github.com/prometheus/alertmanager/config" @@ -121,9 +120,9 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) MrkdwnIn: markdownIn, } - var numFields = len(n.conf.Fields) + numFields := len(n.conf.Fields) if numFields > 0 { - var fields = make([]config.SlackField, numFields) + fields := make([]config.SlackField, numFields) for index, field := range n.conf.Fields { // Check if short was defined for the field otherwise fallback to the global setting var short bool @@ -143,9 +142,9 @@ func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) att.Fields = fields } - var numActions = len(n.conf.Actions) + numActions := len(n.conf.Actions) if numActions > 0 { - var actions = make([]config.SlackAction, numActions) + actions := make([]config.SlackAction, numActions) for index, action := range n.conf.Actions { slackAction := config.SlackAction{ Type: tmplText(action.Type), diff --git a/notify/slack/slack_test.go b/notify/slack/slack_test.go index a8ad2ed8..a3aa34f0 100644 --- a/notify/slack/slack_test.go +++ b/notify/slack/slack_test.go @@ -56,7 +56,7 @@ func TestSlackRedactedURL(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, u.String()) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, u.String()) } func TestGettingSlackURLFromFile(t *testing.T) { @@ -78,5 +78,5 @@ func TestGettingSlackURLFromFile(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, u.String()) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, u.String()) } diff --git a/notify/sns/sns.go b/notify/sns/sns.go index 104c4a45..1dfd42b4 100644 --- a/notify/sns/sns.go +++ b/notify/sns/sns.go @@ -71,9 +71,8 @@ func (n *Notifier) Notify(ctx context.Context, alert ...*types.Alert) (bool, err if err != nil { if e, ok := err.(awserr.RequestFailure); ok { return n.retrier.Check(e.StatusCode(), strings.NewReader(e.Message())) - } else { - return true, err } + return true, err } publishInput, err := n.createPublishInput(ctx, tmpl) @@ -85,9 +84,8 @@ func (n *Notifier) Notify(ctx context.Context, alert ...*types.Alert) (bool, err if err != nil { if e, ok := err.(awserr.RequestFailure); ok { return n.retrier.Check(e.StatusCode(), strings.NewReader(e.Message())) - } else { - return true, err } + return true, err } level.Debug(n.logger).Log("msg", "SNS message successfully published", "message_id", publishOutput.MessageId, "sequence number", publishOutput.SequenceNumber) @@ -96,7 +94,7 @@ func (n *Notifier) Notify(ctx context.Context, alert ...*types.Alert) (bool, err } func (n *Notifier) createSNSClient(tmpl func(string) string) (*sns.SNS, error) { - var creds *credentials.Credentials = nil + var creds *credentials.Credentials // If there are provided sigV4 credentials we want to use those to create a session. if n.conf.Sigv4.AccessKey != "" && n.conf.Sigv4.SecretKey != "" { creds = credentials.NewStaticCredentials(n.conf.Sigv4.AccessKey, string(n.conf.Sigv4.SecretKey), "") diff --git a/notify/telegram/telegram.go b/notify/telegram/telegram.go index 0977cdc6..43bf2a36 100644 --- a/notify/telegram/telegram.go +++ b/notify/telegram/telegram.go @@ -18,15 +18,14 @@ import ( "net/http" "github.com/go-kit/log" + "github.com/go-kit/log/level" + commoncfg "github.com/prometheus/common/config" "gopkg.in/telebot.v3" - "github.com/prometheus/alertmanager/template" - - "github.com/go-kit/log/level" "github.com/prometheus/alertmanager/config" "github.com/prometheus/alertmanager/notify" + "github.com/prometheus/alertmanager/template" "github.com/prometheus/alertmanager/types" - commoncfg "github.com/prometheus/common/config" ) // Notifier implements a Notifier for telegram notifications. @@ -84,16 +83,15 @@ func (n *Notifier) Notify(ctx context.Context, alert ...*types.Alert) (bool, err return false, nil } -func createTelegramClient(token config.Secret, apiUrl, parseMode string, httpClient *http.Client) (*telebot.Bot, error) { +func createTelegramClient(token config.Secret, apiURL, parseMode string, httpClient *http.Client) (*telebot.Bot, error) { secret := string(token) bot, err := telebot.NewBot(telebot.Settings{ Token: secret, - URL: apiUrl, + URL: apiURL, ParseMode: parseMode, Client: httpClient, Offline: true, }) - if err != nil { return nil, err } diff --git a/notify/telegram/telegram_test.go b/notify/telegram/telegram_test.go index 35410b54..0c87cf5d 100644 --- a/notify/telegram/telegram_test.go +++ b/notify/telegram/telegram_test.go @@ -28,7 +28,7 @@ import ( func TestTelegramRetry(t *testing.T) { // Fake url for testing purpouses - fakeUrl := config.URL{ + fakeURL := config.URL{ URL: &url.URL{ Scheme: "https", Host: "FAKE_API", @@ -37,7 +37,7 @@ func TestTelegramRetry(t *testing.T) { notifier, err := New( &config.TelegramConfig{ HTTPConfig: &commoncfg.HTTPClientConfig{}, - APIUrl: &fakeUrl, + APIUrl: &fakeURL, }, test.CreateTmpl(t), log.NewNopLogger(), diff --git a/notify/test/test.go b/notify/test/test.go index edc1b529..32b55ca5 100644 --- a/notify/test/test.go +++ b/notify/test/test.go @@ -137,13 +137,13 @@ func CreateTmpl(t *testing.T) *template.Template { // AssertNotifyLeaksNoSecret calls the Notify() method of the notifier, expects // it to fail because the context is canceled by the server and checks that no // secret data is leaked in the error message returned by Notify(). -func AssertNotifyLeaksNoSecret(t *testing.T, ctx context.Context, n notify.Notifier, secret ...string) { +func AssertNotifyLeaksNoSecret(ctx context.Context, t *testing.T, n notify.Notifier, secret ...string) { t.Helper() require.NotEmpty(t, secret) ctx = notify.WithGroupKey(ctx, "1") ok, err := n.Notify(ctx, []*types.Alert{ - &types.Alert{ + { Alert: model.Alert{ Labels: model.LabelSet{ "lbl1": "val1", diff --git a/notify/util.go b/notify/util.go index 3d0a4a24..fb6efe4c 100644 --- a/notify/util.go +++ b/notify/util.go @@ -25,10 +25,10 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/pkg/errors" + "github.com/prometheus/common/version" "github.com/prometheus/alertmanager/template" "github.com/prometheus/alertmanager/types" - "github.com/prometheus/common/version" ) // UserAgentHeader is the default User-Agent for notification requests @@ -59,11 +59,11 @@ func PostText(ctx context.Context, client *http.Client, url string, body io.Read return post(ctx, client, url, "text/plain", body) } -func post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { +func post(ctx context.Context, client *http.Client, url, bodyType string, body io.Reader) (*http.Response, error) { return request(ctx, client, http.MethodPost, url, bodyType, body) } -func request(ctx context.Context, client *http.Client, method string, url string, bodyType string, body io.Reader) (*http.Response, error) { +func request(ctx context.Context, client *http.Client, method, url, bodyType string, body io.Reader) (*http.Response, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, err diff --git a/notify/victorops/victorops.go b/notify/victorops/victorops.go index 3fdbf41d..3878c110 100644 --- a/notify/victorops/victorops.go +++ b/notify/victorops/victorops.go @@ -64,7 +64,6 @@ const ( // Notify implements the Notifier interface. func (n *Notifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) { - var err error var ( data = notify.GetTemplateData(ctx, n.tmpl, as, n.logger) diff --git a/notify/victorops/victorops_test.go b/notify/victorops/victorops_test.go index 9ed0c991..846c8c19 100644 --- a/notify/victorops/victorops_test.go +++ b/notify/victorops/victorops_test.go @@ -116,7 +116,7 @@ func TestVictorOpsRedactedURL(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, secret) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, secret) } func TestVictorOpsTemplating(t *testing.T) { @@ -186,15 +186,16 @@ func TestVictorOpsTemplating(t *testing.T) { ctx := context.Background() ctx = notify.WithGroupKey(ctx, "1") - _, err = vo.Notify(ctx, []*types.Alert{{ - Alert: model.Alert{ - Labels: model.LabelSet{ - "lbl1": "val1", + _, err = vo.Notify(ctx, []*types.Alert{ + { + Alert: model.Alert{ + Labels: model.LabelSet{ + "lbl1": "val1", + }, + StartsAt: time.Now(), + EndsAt: time.Now().Add(time.Hour), }, - StartsAt: time.Now(), - EndsAt: time.Now().Add(time.Hour), }, - }, }...) if tc.errMsg == "" { require.NoError(t, err) @@ -203,5 +204,4 @@ func TestVictorOpsTemplating(t *testing.T) { } }) } - } diff --git a/notify/wechat/wechat_test.go b/notify/wechat/wechat_test.go index 2d4cbb5a..1969d7b7 100644 --- a/notify/wechat/wechat_test.go +++ b/notify/wechat/wechat_test.go @@ -43,7 +43,7 @@ func TestWechatRedactedURLOnInitialAuthentication(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, secret) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, secret) } func TestWechatRedactedURLOnNotify(t *testing.T) { @@ -65,7 +65,7 @@ func TestWechatRedactedURLOnNotify(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, secret, token) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, secret, token) } func TestWechatMessageTypeSelector(t *testing.T) { @@ -88,5 +88,5 @@ func TestWechatMessageTypeSelector(t *testing.T) { ) require.NoError(t, err) - test.AssertNotifyLeaksNoSecret(t, ctx, notifier, secret, token) + test.AssertNotifyLeaksNoSecret(ctx, t, notifier, secret, token) } diff --git a/pkg/labels/parse_test.go b/pkg/labels/parse_test.go index d7847e76..c15541b8 100644 --- a/pkg/labels/parse_test.go +++ b/pkg/labels/parse_test.go @@ -255,5 +255,4 @@ func TestMatchers(t *testing.T) { } }) } - } diff --git a/provider/mem/mem_test.go b/provider/mem/mem_test.go index b955fa3c..7ff5d2f6 100644 --- a/provider/mem/mem_test.go +++ b/provider/mem/mem_test.go @@ -18,11 +18,10 @@ import ( "fmt" "reflect" "strconv" + "sync" "testing" "time" - "sync" - "github.com/go-kit/log" "github.com/kylelemons/godebug/pretty" "github.com/prometheus/client_golang/prometheus" diff --git a/provider/provider.go b/provider/provider.go index 91b5a741..5fcce203 100644 --- a/provider/provider.go +++ b/provider/provider.go @@ -21,10 +21,8 @@ import ( "github.com/prometheus/alertmanager/types" ) -var ( - // ErrNotFound is returned if a provider cannot find a requested item. - ErrNotFound = fmt.Errorf("item not found") -) +// ErrNotFound is returned if a provider cannot find a requested item. +var ErrNotFound = fmt.Errorf("item not found") // Iterator provides the functions common to all iterators. To be useful, a // specific iterator interface (e.g. AlertIterator) has to be implemented that diff --git a/scripts/errcheck_excludes.txt b/scripts/errcheck_excludes.txt index 39ebd379..92974d7a 100644 --- a/scripts/errcheck_excludes.txt +++ b/scripts/errcheck_excludes.txt @@ -1,4 +1,13 @@ // Don't flag lines such as "io.Copy(ioutil.Discard, resp.Body)". io.Copy +// The next two are used in HTTP handlers, any error is handled by the server itself. +io.WriteString +(net/http.ResponseWriter).Write +// No need to check for errors on server's shutdown. +(*net/http.Server).Shutdown + // Never check for logger errors. (github.com/go-kit/log.Logger).Log + +// Never check for rollback errors as Rollback() is called when a previous error was detected. +(github.com/prometheus/prometheus/storage.Appender).Rollback diff --git a/silence/silence.go b/silence/silence.go index 9beaab1d..408b6282 100644 --- a/silence/silence.go +++ b/silence/silence.go @@ -32,12 +32,13 @@ import ( uuid "github.com/gofrs/uuid" "github.com/matttproud/golang_protobuf_extensions/pbutil" "github.com/pkg/errors" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/common/model" + "github.com/prometheus/alertmanager/cluster" "github.com/prometheus/alertmanager/pkg/labels" pb "github.com/prometheus/alertmanager/silence/silencepb" "github.com/prometheus/alertmanager/types" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/common/model" ) // ErrNotFound is returned if a silence was not found. diff --git a/silence/silence_test.go b/silence/silence_test.go index 064927b6..27148bd4 100644 --- a/silence/silence_test.go +++ b/silence/silence_test.go @@ -25,11 +25,12 @@ import ( "github.com/go-kit/log" "github.com/matttproud/golang_protobuf_extensions/pbutil" - pb "github.com/prometheus/alertmanager/silence/silencepb" - "github.com/prometheus/alertmanager/types" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" + + pb "github.com/prometheus/alertmanager/silence/silencepb" + "github.com/prometheus/alertmanager/types" ) func checkErr(t *testing.T, expected string, got error) { @@ -930,7 +931,6 @@ func TestSilenceExpire(t *testing.T) { EndsAt: now.Add(-time.Minute), UpdatedAt: now.Add(-time.Hour), }, sil) - } // TestSilenceExpireWithZeroRetention covers the problem that, with zero @@ -1153,7 +1153,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: validTimestamp, EndsAt: validTimestamp, @@ -1165,7 +1165,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: validTimestamp, EndsAt: validTimestamp, @@ -1187,8 +1187,8 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, - &pb.Matcher{Name: "00", Pattern: "b"}, + {Name: "a", Pattern: "b"}, + {Name: "00", Pattern: "b"}, }, StartsAt: validTimestamp, EndsAt: validTimestamp, @@ -1200,8 +1200,8 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: ""}, - &pb.Matcher{Name: "b", Pattern: ".*", Type: pb.Matcher_REGEXP}, + {Name: "a", Pattern: ""}, + {Name: "b", Pattern: ".*", Type: pb.Matcher_REGEXP}, }, StartsAt: validTimestamp, EndsAt: validTimestamp, @@ -1213,7 +1213,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: now, EndsAt: now.Add(-time.Second), @@ -1225,7 +1225,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: zeroTimestamp, EndsAt: validTimestamp, @@ -1237,7 +1237,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: validTimestamp, EndsAt: zeroTimestamp, @@ -1249,7 +1249,7 @@ func TestValidateSilence(t *testing.T) { s: &pb.Silence{ Id: "some_id", Matchers: []*pb.Matcher{ - &pb.Matcher{Name: "a", Pattern: "b"}, + {Name: "a", Pattern: "b"}, }, StartsAt: validTimestamp, EndsAt: validTimestamp, @@ -1412,8 +1412,8 @@ func benchmarkSilencesQuery(b *testing.B, numSilences int) { s.st[id] = &pb.MeshSilence{Silence: &pb.Silence{ Id: id, Matchers: []*pb.Matcher{ - &pb.Matcher{Type: pb.Matcher_REGEXP, Name: "aaaa", Pattern: patA}, - &pb.Matcher{Type: pb.Matcher_REGEXP, Name: "bbbb", Pattern: patB}, + {Type: pb.Matcher_REGEXP, Name: "aaaa", Pattern: patA}, + {Type: pb.Matcher_REGEXP, Name: "bbbb", Pattern: patB}, }, StartsAt: now.Add(-time.Minute), EndsAt: now.Add(time.Hour), diff --git a/store/store.go b/store/store.go index 488cb451..83f1495a 100644 --- a/store/store.go +++ b/store/store.go @@ -19,14 +19,13 @@ import ( "sync" "time" - "github.com/prometheus/alertmanager/types" "github.com/prometheus/common/model" + + "github.com/prometheus/alertmanager/types" ) -var ( - // ErrNotFound is returned if a Store cannot find the Alert. - ErrNotFound = errors.New("alert not found") -) +// ErrNotFound is returned if a Store cannot find the Alert. +var ErrNotFound = errors.New("alert not found") // Alerts provides lock-coordinated to an in-memory map of alerts, keyed by // their fingerprint. Resolved alerts are removed from the map based on diff --git a/store/store_test.go b/store/store_test.go index 097e5dc1..a681445c 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -18,9 +18,10 @@ import ( "testing" "time" - "github.com/prometheus/alertmanager/types" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" + + "github.com/prometheus/alertmanager/types" ) func TestSetGet(t *testing.T) { diff --git a/test/cli/acceptance.go b/test/cli/acceptance.go index 7c286e8e..5cd7032c 100644 --- a/test/cli/acceptance.go +++ b/test/cli/acceptance.go @@ -122,7 +122,7 @@ func freeAddress() string { func AmtoolOk() (bool, error) { stat, err := os.Stat(amtool) if err != nil { - return false, fmt.Errorf("Error accessing amtool command, try 'make build' to generate the file. %v", err) + return false, fmt.Errorf("error accessing amtool command, try 'make build' to generate the file. %w", err) } else if stat.IsDir() { return false, fmt.Errorf("file %s is a directory, expecting a binary executable file", amtool) } @@ -569,9 +569,7 @@ func (am *Alertmanager) QuerySilence() ([]TestSilence, error) { return parseSilenceQueryResponse(out) } -var ( - silenceHeaderFields = []string{"ID", "Matchers", "Ends At", "Created By", "Comment"} -) +var silenceHeaderFields = []string{"ID", "Matchers", "Ends At", "Created By", "Comment"} func parseSilenceQueryResponse(data []byte) ([]TestSilence, error) { sils := []TestSilence{} diff --git a/test/cli/acceptance/cli_test.go b/test/cli/acceptance/cli_test.go index 4ba7fc0a..3c4c8356 100644 --- a/test/cli/acceptance/cli_test.go +++ b/test/cli/acceptance/cli_test.go @@ -19,8 +19,9 @@ import ( "testing" "time" - . "github.com/prometheus/alertmanager/test/cli" "github.com/stretchr/testify/require" + + . "github.com/prometheus/alertmanager/test/cli" ) func TestMain(m *testing.M) { diff --git a/test/cli/mock.go b/test/cli/mock.go index c4e177ac..a6570160 100644 --- a/test/cli/mock.go +++ b/test/cli/mock.go @@ -174,7 +174,6 @@ func (a *TestAlert) Annotate(keyval ...interface{}) *TestAlert { // must be a single starting value or two values where the second value // declares the resolved time. func (a *TestAlert) Active(tss ...float64) *TestAlert { - if len(tss) > 2 || len(tss) == 0 { panic("only one or two timestamps allowed") } diff --git a/test/with_api_v1/acceptance/send_test.go b/test/with_api_v1/acceptance/send_test.go index 4f270635..060c1da5 100644 --- a/test/with_api_v1/acceptance/send_test.go +++ b/test/with_api_v1/acceptance/send_test.go @@ -97,7 +97,7 @@ receivers: // On restart the alert is flushed right away as the group_wait has already passed. // However, it must be caught in the deduplication stage. // The next attempt will be 1s later and won't be filtered in deduping. - //co.Want(Between(7.7, 8), Alert("alertname", "test").Active(5.3)) + // co.Want(Between(7.7, 8), Alert("alertname", "test").Active(5.3)) at.Run() } diff --git a/test/with_api_v2/acceptance/api_test.go b/test/with_api_v2/acceptance/api_test.go index 990e3e4d..b78915d4 100644 --- a/test/with_api_v2/acceptance/api_test.go +++ b/test/with_api_v2/acceptance/api_test.go @@ -19,12 +19,13 @@ import ( "time" "github.com/go-openapi/strfmt" + "github.com/prometheus/common/model" + "github.com/stretchr/testify/require" + "github.com/prometheus/alertmanager/api/v2/client/alert" "github.com/prometheus/alertmanager/api/v2/client/silence" "github.com/prometheus/alertmanager/api/v2/models" a "github.com/prometheus/alertmanager/test/with_api_v2" - "github.com/prometheus/common/model" - "github.com/stretchr/testify/require" ) // TestAlertGetReturnsCurrentStatus checks that querying the API returns the diff --git a/test/with_api_v2/mock.go b/test/with_api_v2/mock.go index b35e3f0a..7b2872c2 100644 --- a/test/with_api_v2/mock.go +++ b/test/with_api_v2/mock.go @@ -210,7 +210,6 @@ func (a *TestAlert) Annotate(keyval ...interface{}) *TestAlert { // must be a single starting value or two values where the second value // declares the resolved time. func (a *TestAlert) Active(tss ...float64) *TestAlert { - if len(tss) > 2 || len(tss) == 0 { panic("only one or two timestamps allowed") } diff --git a/timeinterval/timeinterval.go b/timeinterval/timeinterval.go index 24c4a4ea..7d1586ac 100644 --- a/timeinterval/timeinterval.go +++ b/timeinterval/timeinterval.go @@ -125,6 +125,7 @@ var daysOfWeek = map[string]int{ "friday": 5, "saturday": 6, } + var daysOfWeekInv = map[int]string{ 0: "sunday", 1: "monday", @@ -316,7 +317,7 @@ func (r WeekdayRange) MarshalYAML() (interface{}, error) { } // MarshalText implements the econding.TextMarshaler interface for WeekdayRange. -// It converts the range into a colon-seperated string, or a single weekday if possible. +// It converts the range into a colon-separated string, or a single weekday if possible. // e.g. "monday:friday" or "saturday". func (r WeekdayRange) MarshalText() ([]byte, error) { beginStr, ok := daysOfWeekInv[r.Begin] @@ -373,7 +374,7 @@ func (ir InclusiveRange) MarshalText() ([]byte, error) { return []byte(out), nil } -//MarshalYAML implements the yaml.Marshaler interface for InclusiveRange. +// MarshalYAML implements the yaml.Marshaler interface for InclusiveRange. func (ir InclusiveRange) MarshalYAML() (interface{}, error) { bytes, err := ir.MarshalText() return string(bytes), err @@ -382,8 +383,10 @@ func (ir InclusiveRange) MarshalYAML() (interface{}, error) { // TimeLayout specifies the layout to be used in time.Parse() calls for time intervals. const TimeLayout = "15:04" -var validTime string = "^((([01][0-9])|(2[0-3])):[0-5][0-9])$|(^24:00$)" -var validTimeRE *regexp.Regexp = regexp.MustCompile(validTime) +var ( + validTime = "^((([01][0-9])|(2[0-3])):[0-5][0-9])$|(^24:00$)" + validTimeRE = regexp.MustCompile(validTime) +) // Given a time, determines the number of days in the month that time occurs in. func daysInMonth(t time.Time) int { diff --git a/timeinterval/timeinterval_test.go b/timeinterval/timeinterval_test.go index 47b8e0b8..f8eeca54 100644 --- a/timeinterval/timeinterval_test.go +++ b/timeinterval/timeinterval_test.go @@ -357,7 +357,7 @@ var yamlUnmarshalTestCases = []struct { err: "end day must be negative if start day is negative", }, { - // Negative end date before positive postive start date. + // Negative end date before positive positive start date. in: ` --- - days_of_month: ['10:-25'] diff --git a/types/types.go b/types/types.go index a412453d..521d8670 100644 --- a/types/types.go +++ b/types/types.go @@ -18,9 +18,10 @@ import ( "sync" "time" - "github.com/prometheus/alertmanager/pkg/labels" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" + + "github.com/prometheus/alertmanager/pkg/labels" ) // AlertState is used as part of AlertStatus. @@ -58,7 +59,7 @@ type Marker interface { // complete set of relevant silences. If no active silence IDs are provided and // InhibitedBy is already empty, it sets the provided alert to AlertStateActive. // Otherwise, it sets the provided alert to AlertStateSuppressed. - SetSilenced(alert model.Fingerprint, version int, activeSilenceIDs []string, pendingSilenceIDs []string) + SetSilenced(alert model.Fingerprint, version int, activeSilenceIDs, pendingSilenceIDs []string) // SetInhibited replaces the previous InhibitedBy by the provided IDs of // alerts. In contrast to SetSilenced, the set of provided IDs is not // expected to represent the complete set of inhibiting alerts. (In @@ -85,7 +86,7 @@ type Marker interface { // result is based on. Unprocessed(model.Fingerprint) bool Active(model.Fingerprint) bool - Silenced(model.Fingerprint) (activeIDs []string, pendingIDs []string, version int, silenced bool) + Silenced(model.Fingerprint) (activeIDs, pendingIDs []string, version int, silenced bool) Inhibited(model.Fingerprint) ([]string, bool) } @@ -148,7 +149,7 @@ func (m *memMarker) Count(states ...AlertState) int { } // SetSilenced implements Marker. -func (m *memMarker) SetSilenced(alert model.Fingerprint, version int, activeIDs []string, pendingIDs []string) { +func (m *memMarker) SetSilenced(alert model.Fingerprint, version int, activeIDs, pendingIDs []string) { m.mtx.Lock() defer m.mtx.Unlock() @@ -238,7 +239,7 @@ func (m *memMarker) Inhibited(alert model.Fingerprint) ([]string, bool) { // Silenced returns whether the alert for the given Fingerprint is in the // Silenced state, any associated silence IDs, and the silences state version // the result is based on. -func (m *memMarker) Silenced(alert model.Fingerprint) (activeIDs []string, pendingIDs []string, version int, silenced bool) { +func (m *memMarker) Silenced(alert model.Fingerprint) (activeIDs, pendingIDs []string, version int, silenced bool) { s := m.Status(alert) return s.SilencedBy, s.pendingSilences, s.silencesVersion, s.State == AlertStateSuppressed && len(s.SilencedBy) > 0 diff --git a/types/types_test.go b/types/types_test.go index d9ad8bdc..84cb21b4 100644 --- a/types/types_test.go +++ b/types/types_test.go @@ -262,7 +262,6 @@ func TestAlertMerge(t *testing.T) { } func TestCalcSilenceState(t *testing.T) { - var ( pastStartTime = time.Now() pastEndTime = time.Now()