diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 7c60ca843..b2332ec54 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -16,5 +16,5 @@ jobs: - name: Run linter uses: golangci/golangci-lint-action@v3 with: - version: v1.56.2 + version: v1.59.1 diff --git a/.golangci.yml b/.golangci.yml index d47c96dd7..00000ecff 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,6 +1,5 @@ linters-settings: govet: - check-shadowing: true settings: printf: funcs: @@ -10,31 +9,103 @@ linters-settings: - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf gocyclo: min-complexity: 15 - maligned: - suggest-new: true unparam: check-exported: false - gomnd: - settings: - mnd: - checks: argument,case,condition,return - ignored-numbers: 1,2,3,5,10,60,64,100,600,0755,0644,0666 + revive: + enable-all-rules: true + rules: + - name: unhandled-error + disabled: true + - name: unexported-return + disabled: true + - name: line-length-limit + disabled: true + - name: add-constant + disabled: true + - name: cognitive-complexity + disabled: true + - name: cyclomatic + disabled: true + - name: flag-parameter + disabled: true + - name: unused-receiver + disabled: true + - name: unchecked-type-assertion + disabled: true + - name: get-return + disabled: true + - name: function-length + disabled: true + - name: import-shadowing + disabled: true + - name: bare-return + disabled: true + - name: import-alias-naming + disabled: true + - name: function-result-limit + disabled: true + - name: confusing-naming + disabled: true + - name: receiver-naming + disabled: true + - name: var-naming + disabled: true + - name: confusing-results + disabled: true + - name: max-public-structs + disabled: true + - name: deep-exit + disabled: true + - name: modifies-value-receiver + disabled: true + - name: exported + disabled: true + - name: unnecessary-stmt + disabled: true + + mnd: + checks: + - argument + - case + - condition + - return + ignored-numbers: + - '1' + - '2' + - '3' + - '5' + - '10' + - '30' + - '60' + - '64' + - '100' + - '600' + - '0755' + - '0644' + - '0666' + - '0o666' + - '0o644' + - '0o755' linters: - # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint disable-all: true enable: - asasalint - asciicheck - bidichk - bodyclose + - contextcheck - decorder - dogsled + - durationcheck - errcheck - errorlint - exportloopref - - goconst + - fatcontext + - ginkgolinter - gocheckcompilerdirectives + - gochecksumtype + - goconst - gocyclo - goconst - godot @@ -42,7 +113,6 @@ linters: - gofumpt - goheader - goimports - - gomnd - gosimple - govet - grouper @@ -50,28 +120,45 @@ linters: - loggercheck - makezero - misspell + - mnd - nilerr - noctx + - nosprintfhostport - prealloc + - predeclared - promlinter + - protogetter + - reassign + - revive + - rowserrcheck + - sloglint + - spancheck + - sqlclosecheck - staticcheck + - testifylint + - tparallel - typecheck - unconvert - unparam - unused + - usestdlibvars + - wastedassign - whitespace issues: + exclude-dirs: + - vendor + exclude-files: + - notifier/registrator.go exclude-rules: - path: _test\.go linters: - - gomnd + - contextcheck + - mnd + - err113 - errcheck - goconst + - revive run: timeout: 5m - skip-files: - - notifier/registrator.go - skip-dirs: - - vendor diff --git a/api/authorization.go b/api/authorization.go index 234bece71..81e068617 100644 --- a/api/authorization.go +++ b/api/authorization.go @@ -25,12 +25,12 @@ func (auth *Authorization) IsAdmin(login string) bool { type Role string var ( - RoleUndefined Role = "" + RoleUndefined Role RoleUser Role = "user" RoleAdmin Role = "admin" ) -// Returns the role of the given user. +// GetRole Returns the role of the given user. func (auth *Authorization) GetRole(login string) Role { if !auth.IsEnabled() { return RoleUndefined diff --git a/api/config.go b/api/config.go index 7750b68d5..0b344ddcb 100644 --- a/api/config.go +++ b/api/config.go @@ -53,10 +53,10 @@ type WebConfig struct { // MetricSourceCluster contains data about supported metric source cluster. type MetricSourceCluster struct { TriggerSource moira.TriggerSource `json:"trigger_source" example:"graphite_remote"` - ClusterId moira.ClusterId `json:"cluster_id" example:"default"` + ClusterID moira.ClusterID `json:"cluster_id" example:"default"` ClusterName string `json:"cluster_name" example:"Graphite Remote Prod"` } -func (WebConfig) Render(w http.ResponseWriter, r *http.Request) error { +func (WebConfig) Render(http.ResponseWriter, *http.Request) error { return nil } diff --git a/api/controller/contact.go b/api/controller/contact.go index d829343b9..ae523e879 100644 --- a/api/controller/contact.go +++ b/api/controller/contact.go @@ -30,8 +30,8 @@ func GetAllContacts(database moira.Database) (*dto.ContactList, *api.ErrorRespon return &contactsList, nil } -// GetContactById gets notification contact by its id string. -func GetContactById(database moira.Database, contactID string) (*dto.Contact, *api.ErrorResponse) { +// GetContactByID gets notification contact by its id string. +func GetContactByID(database moira.Database, contactID string) (*dto.Contact, *api.ErrorResponse) { contact, err := database.GetContact(contactID) if err != nil { return nil, api.ErrorInternalServer(err) @@ -160,6 +160,7 @@ func RemoveContact(database moira.Database, contactID string, userLogin string, if contact == contactID { subscription.Contacts = append(subscription.Contacts[:i], subscription.Contacts[i+1:]...) subscriptionsWithDeletingContact = append(subscriptionsWithDeletingContact, subscription) + break } } diff --git a/api/controller/contact_events.go b/api/controller/contact_events.go index a6e5f3174..2f051d69a 100644 --- a/api/controller/contact_events.go +++ b/api/controller/contact_events.go @@ -8,8 +8,9 @@ import ( "github.com/moira-alert/moira/api/dto" ) -func GetContactEventsByIdWithLimit(database moira.Database, contactID string, from int64, to int64) (*dto.ContactEventItemList, *api.ErrorResponse) { - events, err := database.GetNotificationsByContactIdWithLimit(contactID, from, to) +// GetContactEventsByIDWithLimit func returns events by contact id with limit. +func GetContactEventsByIDWithLimit(database moira.Database, contactID string, from int64, to int64) (*dto.ContactEventItemList, *api.ErrorResponse) { + events, err := database.GetNotificationsByContactIDWithLimit(contactID, from, to) if err != nil { return nil, api.ErrorInternalServer(fmt.Errorf("GetContactEventsByIdWithLimit: can't get notifications for contact with id %v", contactID)) } diff --git a/api/controller/contact_events_test.go b/api/controller/contact_events_test.go index 9c594dae1..5dfd0b0c8 100644 --- a/api/controller/contact_events_test.go +++ b/api/controller/contact_events_test.go @@ -79,9 +79,9 @@ func TestGetContactEventsByIdWithLimit(t *testing.T) { Convey("Ensure that request with default parameters would return both event items (no url params specified)", t, func() { dataBase.EXPECT().GetContact(contact.ID).Return(contactExpect, nil).AnyTimes() - dataBase.EXPECT().GetNotificationsByContactIdWithLimit(contact.ID, defaultFromParameter, defaultToParameter).Return(items, nil) + dataBase.EXPECT().GetNotificationsByContactIDWithLimit(contact.ID, defaultFromParameter, defaultToParameter).Return(items, nil) - actualEvents, err := GetContactEventsByIdWithLimit(dataBase, contact.ID, defaultFromParameter, defaultToParameter) + actualEvents, err := GetContactEventsByIDWithLimit(dataBase, contact.ID, defaultFromParameter, defaultToParameter) So(err, ShouldBeNil) So(actualEvents, ShouldResemble, &itemsExpected) @@ -89,9 +89,9 @@ func TestGetContactEventsByIdWithLimit(t *testing.T) { Convey("Ensure that request with only 'from' parameter given and 'to' default will return only one (newest) event", t, func() { dataBase.EXPECT().GetContact(contact.ID).Return(contactExpect, nil).AnyTimes() - dataBase.EXPECT().GetNotificationsByContactIdWithLimit(contact.ID, defaultFromParameter-20, defaultToParameter).Return(items[:1], nil) + dataBase.EXPECT().GetNotificationsByContactIDWithLimit(contact.ID, defaultFromParameter-20, defaultToParameter).Return(items[:1], nil) - actualEvents, err := GetContactEventsByIdWithLimit(dataBase, contact.ID, defaultFromParameter-20, defaultToParameter) + actualEvents, err := GetContactEventsByIDWithLimit(dataBase, contact.ID, defaultFromParameter-20, defaultToParameter) So(err, ShouldBeNil) So(actualEvents, ShouldResemble, &dto.ContactEventItemList{ List: []dto.ContactEventItem{ @@ -102,9 +102,9 @@ func TestGetContactEventsByIdWithLimit(t *testing.T) { Convey("Ensure that request with only 'to' parameter given and 'from' default will return only one (oldest) event", t, func() { dataBase.EXPECT().GetContact(contact.ID).Return(contactExpect, nil).AnyTimes() - dataBase.EXPECT().GetNotificationsByContactIdWithLimit(contact.ID, defaultFromParameter, defaultToParameter-30).Return(items[1:], nil) + dataBase.EXPECT().GetNotificationsByContactIDWithLimit(contact.ID, defaultFromParameter, defaultToParameter-30).Return(items[1:], nil) - actualEvents, err := GetContactEventsByIdWithLimit(dataBase, contact.ID, defaultFromParameter, defaultToParameter-30) + actualEvents, err := GetContactEventsByIDWithLimit(dataBase, contact.ID, defaultFromParameter, defaultToParameter-30) So(err, ShouldBeNil) So(actualEvents, ShouldResemble, &dto.ContactEventItemList{ List: []dto.ContactEventItem{ diff --git a/api/controller/contact_test.go b/api/controller/contact_test.go index 961deba9f..6195eac73 100644 --- a/api/controller/contact_test.go +++ b/api/controller/contact_test.go @@ -74,7 +74,7 @@ func TestGetContactById(t *testing.T) { } dataBase.EXPECT().GetContact(contact.ID).Return(contact, nil) - actual, err := GetContactById(dataBase, contact.ID) + actual, err := GetContactByID(dataBase, contact.ID) So(err, ShouldBeNil) So(actual, ShouldResemble, @@ -88,9 +88,9 @@ func TestGetContactById(t *testing.T) { }) Convey("Get contact with invalid or unexisting guid id should be empty json", t, func() { - const invalidId = "invalidID" - dataBase.EXPECT().GetContact(invalidId).Return(moira.ContactData{}, nil) - actual, err := GetContactById(dataBase, invalidId) + const invalidID = "invalidID" + dataBase.EXPECT().GetContact(invalidID).Return(moira.ContactData{}, nil) + actual, err := GetContactByID(dataBase, invalidID) So(err, ShouldBeNil) So(actual, ShouldResemble, &dto.Contact{}) }) @@ -101,7 +101,7 @@ func TestGetContactById(t *testing.T) { dbError := fmt.Errorf("some db internal error here") dataBase.EXPECT().GetContact(contactID).Return(emptyContact, dbError) - contact, err := GetContactById(dataBase, contactID) + contact, err := GetContactByID(dataBase, contactID) So(err, ShouldResemble, api.ErrorInternalServer(dbError)) So(contact, ShouldBeNil) }) diff --git a/api/controller/team.go b/api/controller/team.go index 3c35ac0e2..bbf16bcfa 100644 --- a/api/controller/team.go +++ b/api/controller/team.go @@ -81,7 +81,7 @@ func GetTeam(dataBase moira.Database, teamID string) (dto.TeamModel, *api.ErrorR return teamModel, nil } -// GetUserTeams is a controller function that returns a teams in which user is a member bu user ID. +// GetUserTeams is a controller function that returns a teams in which user is a member by user ID. func GetUserTeams(dataBase moira.Database, userID string) (dto.UserTeams, *api.ErrorResponse) { teams, err := dataBase.GetUserTeams(userID) @@ -406,7 +406,6 @@ func CheckUserPermissionsForTeam( if auth.IsAdmin(userID) { return nil } - _, err := dataBase.GetTeam(teamID) if err != nil { if errors.Is(err, database.ErrNil) { @@ -426,19 +425,19 @@ func CheckUserPermissionsForTeam( } // GetTeamSettings gets team contacts and subscriptions. -func GetTeamSettings(database moira.Database, teamID string) (dto.TeamSettings, *api.ErrorResponse) { +func GetTeamSettings(dataBase moira.Database, teamID string) (dto.TeamSettings, *api.ErrorResponse) { teamSettings := dto.TeamSettings{ TeamID: teamID, Contacts: make([]moira.ContactData, 0), Subscriptions: make([]moira.SubscriptionData, 0), } - subscriptionIDs, err := database.GetTeamSubscriptionIDs(teamID) + subscriptionIDs, err := dataBase.GetTeamSubscriptionIDs(teamID) if err != nil { return dto.TeamSettings{}, api.ErrorInternalServer(err) } - subscriptions, err := database.GetSubscriptions(subscriptionIDs) + subscriptions, err := dataBase.GetSubscriptions(subscriptionIDs) if err != nil { return dto.TeamSettings{}, api.ErrorInternalServer(err) } @@ -447,12 +446,12 @@ func GetTeamSettings(database moira.Database, teamID string) (dto.TeamSettings, teamSettings.Subscriptions = append(teamSettings.Subscriptions, *subscription) } } - contactIDs, err := database.GetTeamContactIDs(teamID) + contactIDs, err := dataBase.GetTeamContactIDs(teamID) if err != nil { return dto.TeamSettings{}, api.ErrorInternalServer(err) } - contacts, err := database.GetContacts(contactIDs) + contacts, err := dataBase.GetContacts(contactIDs) if err != nil { return dto.TeamSettings{}, api.ErrorInternalServer(err) } diff --git a/api/controller/trigger_metrics_test.go b/api/controller/trigger_metrics_test.go index 5cd76b3b3..49085da0b 100644 --- a/api/controller/trigger_metrics_test.go +++ b/api/controller/trigger_metrics_test.go @@ -282,7 +282,7 @@ func TestGetTriggerMetrics(t *testing.T) { ID: triggerID, Targets: []string{pattern}, TriggerSource: moira.PrometheusRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } dataBase.EXPECT().GetTrigger(triggerID).Return(trigger, nil) triggerMetrics, err := GetTriggerMetrics(dataBase, sourceProvider, from, until, triggerID) @@ -295,7 +295,7 @@ func TestGetTriggerMetrics(t *testing.T) { ID: triggerID, Targets: []string{pattern}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil) localSource.EXPECT().Fetch(pattern, from, until, false).Return(fetchResult, nil) fetchResult.EXPECT().GetMetricsData().Return([]metricSource.MetricData{*metricSource.MakeMetricData(metric, []float64{0, 1, 2, 3, 4}, retention, from)}) @@ -328,7 +328,7 @@ func TestGetTriggerMetrics(t *testing.T) { ID: triggerID, Targets: []string{pattern}, TriggerSource: moira.GraphiteRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil) remoteSource.EXPECT().Fetch(pattern, from, until, false).Return(nil, expectedError) diff --git a/api/dto/event_history_item.go b/api/dto/event_history_item.go index 74783d284..b631a4e89 100644 --- a/api/dto/event_history_item.go +++ b/api/dto/event_history_item.go @@ -14,6 +14,6 @@ type ContactEventItemList struct { List []ContactEventItem `json:"list"` } -func (*ContactEventItemList) Render(w http.ResponseWriter, r *http.Request) error { +func (*ContactEventItemList) Render(http.ResponseWriter, *http.Request) error { return nil } diff --git a/api/dto/subscription.go b/api/dto/subscription.go index 38178db3a..a6662c524 100644 --- a/api/dto/subscription.go +++ b/api/dto/subscription.go @@ -95,7 +95,7 @@ func (subscription *Subscription) checkContacts(request *http.Request) error { return err } - contactIDsHash := make(map[string]interface{}) + contactIDsHash := make(map[string]any) for _, contactId := range contactIDs { contactIDsHash[contactId] = true } diff --git a/api/dto/team.go b/api/dto/team.go index 9b08cb7ee..14e5d8546 100644 --- a/api/dto/team.go +++ b/api/dto/team.go @@ -30,7 +30,7 @@ func NewTeamModel(team moira.Team) TeamModel { } // Bind is a method that implements Binder interface from chi and checks that validity of data in request. -func (t TeamModel) Bind(request *http.Request) error { +func (t TeamModel) Bind(*http.Request) error { if t.Name == "" { return fmt.Errorf("team name cannot be empty") } @@ -44,7 +44,7 @@ func (t TeamModel) Bind(request *http.Request) error { } // Render is a function that implements chi Renderer interface for TeamModel. -func (TeamModel) Render(w http.ResponseWriter, r *http.Request) error { +func (TeamModel) Render(_ http.ResponseWriter, _ *http.Request) error { return nil } @@ -63,7 +63,7 @@ type SaveTeamResponse struct { } // Render is a function that implements chi Renderer interface for SaveTeamResponse. -func (SaveTeamResponse) Render(w http.ResponseWriter, r *http.Request) error { +func (SaveTeamResponse) Render(_ http.ResponseWriter, _ *http.Request) error { return nil } @@ -73,7 +73,7 @@ type UserTeams struct { } // Render is a function that implements chi Renderer interface for UserTeams. -func (UserTeams) Render(w http.ResponseWriter, r *http.Request) error { +func (UserTeams) Render(_ http.ResponseWriter, _ *http.Request) error { return nil } @@ -83,7 +83,7 @@ type TeamMembers struct { } // Bind is a method that implements Binder interface from chi and checks that validity of data in request. -func (m TeamMembers) Bind(request *http.Request) error { +func (m TeamMembers) Bind(*http.Request) error { if len(m.Usernames) == 0 { return fmt.Errorf("at least one user should be specified") } @@ -91,7 +91,7 @@ func (m TeamMembers) Bind(request *http.Request) error { } // Render is a function that implements chi Renderer interface for TeamMembers. -func (TeamMembers) Render(w http.ResponseWriter, r *http.Request) error { +func (TeamMembers) Render(http.ResponseWriter, *http.Request) error { return nil } @@ -101,6 +101,6 @@ type TeamSettings struct { Subscriptions []moira.SubscriptionData `json:"subscriptions"` } -func (TeamSettings) Render(w http.ResponseWriter, r *http.Request) error { +func (TeamSettings) Render(http.ResponseWriter, *http.Request) error { return nil } diff --git a/api/dto/triggers.go b/api/dto/triggers.go index b35ce20ef..bd0daedd0 100644 --- a/api/dto/triggers.go +++ b/api/dto/triggers.go @@ -77,7 +77,7 @@ type TriggerModel struct { // Shows the type of source from where the metrics are fetched TriggerSource moira.TriggerSource `json:"trigger_source" example:"graphite_local"` // Shows the exact cluster from where the metrics are fetched - ClusterId moira.ClusterId `json:"cluster_id" example:"default"` + ClusterId moira.ClusterID `json:"cluster_id" example:"default"` // If true, first event NODATA → OK will be omitted MuteNewMetrics bool `json:"mute_new_metrics" example:"false"` // A list of targets that have only alone metrics @@ -114,7 +114,7 @@ func (model *TriggerModel) ToMoiraTrigger() *moira.Trigger { Expression: &model.Expression, Patterns: model.Patterns, TriggerSource: model.TriggerSource, - ClusterId: model.ClusterId, + ClusterID: model.ClusterId, MuteNewMetrics: model.MuteNewMetrics, AloneMetrics: model.AloneMetrics, UpdatedBy: model.UpdatedBy, @@ -139,7 +139,7 @@ func CreateTriggerModel(trigger *moira.Trigger) TriggerModel { Patterns: trigger.Patterns, IsRemote: trigger.TriggerSource == moira.GraphiteRemote, TriggerSource: trigger.TriggerSource, - ClusterId: trigger.ClusterId, + ClusterId: trigger.ClusterID, MuteNewMetrics: trigger.MuteNewMetrics, AloneMetrics: trigger.AloneMetrics, CreatedAt: getDateTime(trigger.CreatedAt), diff --git a/api/dto/triggers_test.go b/api/dto/triggers_test.go index 90b8a87d0..27d3c8a60 100644 --- a/api/dto/triggers_test.go +++ b/api/dto/triggers_test.go @@ -27,7 +27,7 @@ func TestTriggerValidation(t *testing.T) { fetchResult := mock_metric_source.NewMockFetchResult(mockCtrl) sourceProvider := metricSource.CreateTestMetricSourceProvider(localSource, remoteSource, nil) - request, _ := http.NewRequest("PUT", "/api/trigger", nil) + request, _ := http.NewRequest(http.MethodPut, "/api/trigger", nil) request.Header.Set("Content-Type", "application/json") ctx := request.Context() ctx = context.WithValue(ctx, middleware.ContextKey("metricSourceProvider"), sourceProvider) @@ -309,7 +309,7 @@ func TestTriggerModel_ToMoiraTrigger(t *testing.T) { Expression: &expression, Patterns: []string{"pattern-1", "pattern-2"}, TriggerSource: moira.GraphiteRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, MuteNewMetrics: true, AloneMetrics: map[string]bool{ "t1": true, @@ -351,7 +351,7 @@ func TestCreateTriggerModel(t *testing.T) { Expression: &expression, Patterns: []string{"pattern-1", "pattern-2"}, TriggerSource: moira.GraphiteRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, MuteNewMetrics: true, AloneMetrics: map[string]bool{ "t1": true, diff --git a/api/error_response.go b/api/error_response.go index a52999472..48582fcc9 100644 --- a/api/error_response.go +++ b/api/error_response.go @@ -17,7 +17,7 @@ type ErrorResponse struct { } // Render realization method for render.renderer. -func (e *ErrorResponse) Render(w http.ResponseWriter, r *http.Request) error { +func (e *ErrorResponse) Render(_ http.ResponseWriter, r *http.Request) error { render.Status(r, e.HTTPStatusCode) return nil } diff --git a/api/handler/contact.go b/api/handler/contact.go index ba31d1f2d..82af5a548 100644 --- a/api/handler/contact.go +++ b/api/handler/contact.go @@ -20,7 +20,7 @@ func contact(router chi.Router) { router.Route("/{contactId}", func(router chi.Router) { router.Use(middleware.ContactContext) router.Use(contactFilter) - router.Get("/", getContactById) + router.Get("/", getContactByID) router.Put("/", updateContact) router.Delete("/", removeContact) router.Post("/test", sendTestContactNotification) @@ -63,10 +63,10 @@ func getAllContacts(writer http.ResponseWriter, request *http.Request) { // @failure 422 {object} api.ErrorRenderExample "Render error" // @failure 500 {object} api.ErrorInternalServerExample "Internal server error" // @router /contact/{contactID} [get] -func getContactById(writer http.ResponseWriter, request *http.Request) { +func getContactByID(writer http.ResponseWriter, request *http.Request) { contactData := request.Context().Value(contactKey).(moira.ContactData) - contact, apiErr := controller.GetContactById(database, contactData.ID) + contact, apiErr := controller.GetContactByID(database, contactData.ID) if apiErr != nil { render.Render(writer, request, apiErr) //nolint diff --git a/api/handler/contact_events.go b/api/handler/contact_events.go index 7c57b409e..6325e0a5c 100644 --- a/api/handler/contact_events.go +++ b/api/handler/contact_events.go @@ -20,7 +20,7 @@ func contactEvents(router chi.Router) { router.Route("/{contactId}/events", func(router chi.Router) { router.Use(middleware.ContactContext) router.Use(contactFilter) - router.With(middleware.DateRange("-3hour", "now")).Get("/", getContactByIdWithEvents) + router.With(middleware.DateRange("-3hour", "now")).Get("/", getContactByIDWithEvents) }) } @@ -40,7 +40,7 @@ func contactEvents(router chi.Router) { // @failure 422 {object} api.ErrorRenderExample "Render error" // @failure 500 {object} api.ErrorInternalServerExample "Internal server error" // @router /contact/{contactID}/events [get] -func getContactByIdWithEvents(writer http.ResponseWriter, request *http.Request) { +func getContactByIDWithEvents(writer http.ResponseWriter, request *http.Request) { contactData := request.Context().Value(contactKey).(moira.ContactData) fromStr := middleware.GetFromStr(request) toStr := middleware.GetToStr(request) @@ -54,7 +54,7 @@ func getContactByIdWithEvents(writer http.ResponseWriter, request *http.Request) render.Render(writer, request, api.ErrorInvalidRequest(fmt.Errorf("can not parse to: %v", to))) //nolint return } - contactWithEvents, err := controller.GetContactEventsByIdWithLimit(database, contactData.ID, from, to) + contactWithEvents, err := controller.GetContactEventsByIDWithLimit(database, contactData.ID, from, to) if err != nil { render.Render(writer, request, err) //nolint } diff --git a/api/handler/contact_test.go b/api/handler/contact_test.go index 6f469b23b..37d8e2c08 100644 --- a/api/handler/contact_test.go +++ b/api/handler/contact_test.go @@ -139,7 +139,7 @@ func TestGetContactById(t *testing.T) { testRequest = testRequest.WithContext(middleware.SetContextValueForTest(testRequest.Context(), ContactIDKey, contactID)) testRequest = testRequest.WithContext(middleware.SetContextValueForTest(testRequest.Context(), ContactKey, moira.ContactData{ID: contactID})) - getContactById(responseWriter, testRequest) + getContactByID(responseWriter, testRequest) response := responseWriter.Result() defer response.Body.Close() @@ -168,7 +168,7 @@ func TestGetContactById(t *testing.T) { testRequest = testRequest.WithContext(middleware.SetContextValueForTest(testRequest.Context(), ContactIDKey, contactID)) testRequest = testRequest.WithContext(middleware.SetContextValueForTest(testRequest.Context(), ContactKey, moira.ContactData{ID: contactID})) - getContactById(responseWriter, testRequest) + getContactByID(responseWriter, testRequest) response := responseWriter.Result() defer response.Body.Close() diff --git a/api/handler/trigger_render_test.go b/api/handler/trigger_render_test.go index d31de3d53..236e36e3f 100644 --- a/api/handler/trigger_render_test.go +++ b/api/handler/trigger_render_test.go @@ -53,7 +53,7 @@ func TestRenderTrigger(t *testing.T) { ID: "triggerID-0000000000001", Targets: []string{"t1"}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil).Times(1) fetchResult := mock_metric_source.NewMockFetchResult(mockCtrl) fetchResult.EXPECT().GetMetricsData().Return([]metricSource.MetricData{*metricSource.MakeMetricData("", []float64{}, 0, 0)}).Times(1) @@ -86,7 +86,7 @@ func TestRenderTrigger(t *testing.T) { ID: "triggerID-0000000000001", Targets: []string{"t1"}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil).Times(1) fetchResult := mock_metric_source.NewMockFetchResult(mockCtrl) fetchResult.EXPECT().GetMetricsData().Return([]metricSource.MetricData{*metricSource.MakeMetricData("", []float64{}, 0, 0)}).Times(1) diff --git a/api/handler/trigger_test.go b/api/handler/trigger_test.go index 1e32507d8..c3018346f 100644 --- a/api/handler/trigger_test.go +++ b/api/handler/trigger_test.go @@ -38,7 +38,7 @@ func TestGetTrigger(t *testing.T) { mockDb.EXPECT().GetTrigger("triggerID-0000000000001").Return(moira.Trigger{ ID: "triggerID-0000000000001", TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil) mockDb.EXPECT().GetTriggerThrottling("triggerID-0000000000001").Return(throttlingTime, throttlingTime) database = mockDb @@ -68,7 +68,7 @@ func TestGetTrigger(t *testing.T) { ID: "triggerID-0000000000001", CreatedAt: &triggerTime, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, UpdatedAt: &triggerTime, }, nil) @@ -156,7 +156,7 @@ func TestUpdateTrigger(t *testing.T) { ErrorValue: &triggerErrorValue, Targets: []string{"my.metric"}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } mockDb.EXPECT().GetTrigger(gomock.Any()).Return(trigger, nil) @@ -399,15 +399,15 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { database = db defer func() { database = nil }() - const triggerId = "TestTriggerId" + const triggerID = "TestTriggerId" Convey("Given database returns trigger with TriggerSource = GraphiteLocal", t, func() { - request := httptest.NewRequest("GET", "/trigger/"+triggerId, nil) - request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerId)) + request := httptest.NewRequest(http.MethodGet, "/trigger/"+triggerID, nil) + request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerID)) request = request.WithContext(middleware.SetContextValueForTest(request.Context(), "populated", true)) trigger := moira.Trigger{ - ID: triggerId, + ID: triggerID, WarnValue: newFloat64(1.0), ErrorValue: newFloat64(2.0), TriggerType: moira.RisingTrigger, @@ -418,10 +418,10 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { TriggerSource: moira.GraphiteLocal, } - db.EXPECT().GetTrigger(triggerId).Return(trigger, nil) - db.EXPECT().GetTriggerThrottling(triggerId) - db.EXPECT().GetNotificationEvents(triggerId, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) - db.EXPECT().GetNotificationEventCount(triggerId, gomock.Any()).Return(int64(0)) + db.EXPECT().GetTrigger(triggerID).Return(trigger, nil) + db.EXPECT().GetTriggerThrottling(triggerID) + db.EXPECT().GetNotificationEvents(triggerID, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) + db.EXPECT().GetNotificationEventCount(triggerID, gomock.Any()).Return(int64(0)) responseWriter := httptest.NewRecorder() getTrigger(responseWriter, request) @@ -446,12 +446,12 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { }) Convey("Given database returns trigger with TriggerSource = GraphiteRemote", t, func() { - request := httptest.NewRequest("GET", "/trigger/"+triggerId, nil) - request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerId)) + request := httptest.NewRequest(http.MethodGet, "/trigger/"+triggerID, nil) + request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerID)) request = request.WithContext(middleware.SetContextValueForTest(request.Context(), "populated", true)) trigger := moira.Trigger{ - ID: triggerId, + ID: triggerID, WarnValue: newFloat64(1.0), ErrorValue: newFloat64(2.0), TriggerType: moira.RisingTrigger, @@ -462,10 +462,10 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { TriggerSource: moira.GraphiteRemote, } - db.EXPECT().GetTrigger(triggerId).Return(trigger, nil) - db.EXPECT().GetTriggerThrottling(triggerId) - db.EXPECT().GetNotificationEvents(triggerId, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) - db.EXPECT().GetNotificationEventCount(triggerId, gomock.Any()).Return(int64(0)) + db.EXPECT().GetTrigger(triggerID).Return(trigger, nil) + db.EXPECT().GetTriggerThrottling(triggerID) + db.EXPECT().GetNotificationEvents(triggerID, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) + db.EXPECT().GetNotificationEventCount(triggerID, gomock.Any()).Return(int64(0)) responseWriter := httptest.NewRecorder() getTrigger(responseWriter, request) @@ -490,12 +490,12 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { }) Convey("Given database returns trigger with TriggerSource = PrometheusTrigger", t, func() { - request := httptest.NewRequest("GET", "/trigger/"+triggerId, nil) - request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerId)) + request := httptest.NewRequest(http.MethodGet, "/trigger/"+triggerID, nil) + request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerID)) request = request.WithContext(middleware.SetContextValueForTest(request.Context(), "populated", true)) trigger := moira.Trigger{ - ID: triggerId, + ID: triggerID, WarnValue: newFloat64(1.0), ErrorValue: newFloat64(2.0), TriggerType: moira.RisingTrigger, @@ -506,10 +506,10 @@ func TestGetTriggerWithTriggerSource(t *testing.T) { TriggerSource: moira.PrometheusRemote, } - db.EXPECT().GetTrigger(triggerId).Return(trigger, nil) - db.EXPECT().GetTriggerThrottling(triggerId) - db.EXPECT().GetNotificationEvents(triggerId, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) - db.EXPECT().GetNotificationEventCount(triggerId, gomock.Any()).Return(int64(0)) + db.EXPECT().GetTrigger(triggerID).Return(trigger, nil) + db.EXPECT().GetTriggerThrottling(triggerID) + db.EXPECT().GetNotificationEvents(triggerID, gomock.Any(), gomock.Any()).Return(make([]*moira.NotificationEvent, 0), nil) + db.EXPECT().GetNotificationEventCount(triggerID, gomock.Any()).Return(int64(0)) responseWriter := httptest.NewRecorder() getTrigger(responseWriter, request) diff --git a/api/handler/triggers.go b/api/handler/triggers.go index 090ed6607..50eaf00cb 100644 --- a/api/handler/triggers.go +++ b/api/handler/triggers.go @@ -77,7 +77,10 @@ func getAllTriggers(writer http.ResponseWriter, request *http.Request) { func getUnusedTriggers(writer http.ResponseWriter, request *http.Request) { triggersList, errorResponse := controller.GetUnusedTriggerIDs(database) if errorResponse != nil { - render.Render(writer, request, errorResponse) //nolint + err := render.Render(writer, request, errorResponse) + if err != nil { + return + } //nolint return } diff --git a/api/handler/triggers_test.go b/api/handler/triggers_test.go index 83d0a1bea..62c8a332a 100644 --- a/api/handler/triggers_test.go +++ b/api/handler/triggers_test.go @@ -545,15 +545,15 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { database = db defer func() { database = nil }() - triggerId := "test" + triggerID := "test" target := `test_target_value` Convey("Given is_remote flag is false and trigger_source is not set", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"is_remote": false`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"is_remote": false`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be graphite local", func() { - setupExpectationsForCreateTrigger(localSource, db, target, triggerId, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) + setupExpectationsForCreateTrigger(localSource, db, target, triggerID, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -563,11 +563,11 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { }) Convey("Given is_remote flag is true and trigger_source is not set", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"is_remote": true`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"is_remote": true`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be graphite remote", func() { - setupExpectationsForCreateTrigger(remoteSource, db, target, triggerId, moira.DefaultGraphiteRemoteCluster) + setupExpectationsForCreateTrigger(remoteSource, db, target, triggerID, moira.DefaultGraphiteRemoteCluster) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -577,11 +577,11 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { }) Convey("Given is_remote flag is not set and trigger_source is graphite_local", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"trigger_source": "graphite_local"`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"trigger_source": "graphite_local"`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be graphite local", func() { - setupExpectationsForCreateTrigger(localSource, db, target, triggerId, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) + setupExpectationsForCreateTrigger(localSource, db, target, triggerID, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -591,11 +591,11 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { }) Convey("Given is_remote flag is not set and trigger_source is graphite_remote", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"trigger_source": "graphite_remote"`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"trigger_source": "graphite_remote"`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be graphite remote", func() { - setupExpectationsForCreateTrigger(remoteSource, db, target, triggerId, moira.DefaultGraphiteRemoteCluster) + setupExpectationsForCreateTrigger(remoteSource, db, target, triggerID, moira.DefaultGraphiteRemoteCluster) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -605,11 +605,11 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { }) Convey("Given is_remote flag is not set and trigger_source is prometheus_remote", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"trigger_source": "prometheus_remote"`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"trigger_source": "prometheus_remote"`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be prometheus remote", func() { - setupExpectationsForCreateTrigger(prometheusSource, db, target, triggerId, moira.MakeClusterKey(moira.PrometheusRemote, moira.DefaultCluster)) + setupExpectationsForCreateTrigger(prometheusSource, db, target, triggerID, moira.MakeClusterKey(moira.PrometheusRemote, moira.DefaultCluster)) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -619,11 +619,11 @@ func TestTriggersCreatedWithTriggerSource(t *testing.T) { }) Convey("Given is_remote flag is true and trigger_source is graphite_local", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"is_remote": true, "trigger_source": "graphite_local"`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"is_remote": true, "trigger_source": "graphite_local"`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger to be graphite local", func() { - setupExpectationsForCreateTrigger(localSource, db, target, triggerId, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) + setupExpectationsForCreateTrigger(localSource, db, target, triggerID, moira.MakeClusterKey(moira.GraphiteLocal, moira.DefaultCluster)) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -639,7 +639,7 @@ func TestTriggersCreatedWithNonDefaultClusterId(t *testing.T) { localSource := mock_metric_source.NewMockMetricSource(mockCtrl) - remoteStagingCluster := moira.MakeClusterKey(moira.GraphiteLocal, moira.ClusterId("staging")) + remoteStagingCluster := moira.MakeClusterKey(moira.GraphiteLocal, moira.ClusterID("staging")) remoteStagingSource := mock_metric_source.NewMockMetricSource(mockCtrl) sourceProvider := metricSource.CreateTestMetricSourceProvider(localSource, nil, nil) @@ -649,15 +649,15 @@ func TestTriggersCreatedWithNonDefaultClusterId(t *testing.T) { database = db defer func() { database = nil }() - triggerId := "test" + triggerID := "test" target := `test_target_value` Convey("Given cluster_id is set", t, func() { - jsonTrigger := makeTestTriggerJson(target, triggerId, `"trigger_source": "graphite_local", "cluster_id": "staging"`) - request := newTriggerCreateRequest(sourceProvider, triggerId, jsonTrigger) + jsonTrigger := makeTestTriggerJSON(target, triggerID, `"trigger_source": "graphite_local", "cluster_id": "staging"`) + request := newTriggerCreateRequest(sourceProvider, triggerID, jsonTrigger) Convey("Expect trigger have non default cluster id", func() { - setupExpectationsForCreateTrigger(remoteStagingSource, db, target, triggerId, remoteStagingCluster) + setupExpectationsForCreateTrigger(remoteStagingSource, db, target, triggerID, remoteStagingCluster) responseWriter := httptest.NewRecorder() createTrigger(responseWriter, request) @@ -667,8 +667,8 @@ func TestTriggersCreatedWithNonDefaultClusterId(t *testing.T) { }) } -func makeTestTriggerJson(target, triggerId, triggerSource string) []byte { - targetJson, _ := json.Marshal(target) +func makeTestTriggerJSON(target, triggerID, triggerSource string) []byte { + targetJSON, _ := json.Marshal(target) jsonTrigger := fmt.Sprintf(`{ "name": "Test", "targets": [ %s ], @@ -680,37 +680,37 @@ func makeTestTriggerJson(target, triggerId, triggerSource string) []byte { "ttl_state": "NODATA", %s, "ttl": 600 - }`, targetJson, triggerId, triggerSource) + }`, targetJSON, triggerID, triggerSource) return []byte(jsonTrigger) } func setupExpectationsForCreateTrigger( source *mock_metric_source.MockMetricSource, db *mock_moira_alert.MockDatabase, - target, triggerId string, + target, triggerID string, clusterKey moira.ClusterKey, ) { source.EXPECT().GetMetricsTTLSeconds().Return(int64(3600)) source.EXPECT().Fetch(target, gomock.Any(), gomock.Any(), gomock.Any()).Return(&local.FetchResult{}, nil) - db.EXPECT().GetTrigger(triggerId).Return(moira.Trigger{}, dataBase.ErrNil) - db.EXPECT().AcquireTriggerCheckLock(triggerId, gomock.Any()).Return(nil) - db.EXPECT().DeleteTriggerCheckLock(triggerId).Return(nil) - db.EXPECT().GetTriggerLastCheck(triggerId).Return(moira.CheckData{}, dataBase.ErrNil) - db.EXPECT().SetTriggerLastCheck(triggerId, gomock.Any(), clusterKey).Return(nil) - db.EXPECT().SaveTrigger(triggerId, gomock.Any()).Return(nil) + db.EXPECT().GetTrigger(triggerID).Return(moira.Trigger{}, dataBase.ErrNil) + db.EXPECT().AcquireTriggerCheckLock(triggerID, gomock.Any()).Return(nil) + db.EXPECT().DeleteTriggerCheckLock(triggerID).Return(nil) + db.EXPECT().GetTriggerLastCheck(triggerID).Return(moira.CheckData{}, dataBase.ErrNil) + db.EXPECT().SetTriggerLastCheck(triggerID, gomock.Any(), clusterKey).Return(nil) + db.EXPECT().SaveTrigger(triggerID, gomock.Any()).Return(nil) } func newTriggerCreateRequest( sourceProvider *metricSource.SourceProvider, - triggerId string, + triggerID string, jsonTrigger []byte, ) *http.Request { - request := httptest.NewRequest("PUT", "/trigger", bytes.NewBuffer(jsonTrigger)) + request := httptest.NewRequest(http.MethodPut, "/trigger", bytes.NewBuffer(jsonTrigger)) request.Header.Add("content-type", "application/json") request = request.WithContext(middleware.SetContextValueForTest(request.Context(), "metricSourceProvider", sourceProvider)) request = request.WithContext(middleware.SetContextValueForTest(request.Context(), "clustersMetricTTL", MakeTestTTLs())) - request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerId)) + request = request.WithContext(middleware.SetContextValueForTest(request.Context(), triggerIDKey, triggerID)) return request } diff --git a/api/middleware/logger.go b/api/middleware/logger.go index aac401a26..dd93d585c 100644 --- a/api/middleware/logger.go +++ b/api/middleware/logger.go @@ -140,7 +140,7 @@ func (entry *apiLoggerEntry) write(status, bytes int, elapsed time.Duration, res Msg(entry.msg) } -func (entry *apiLoggerEntry) writePanic(status, bytes int, elapsed time.Duration, v interface{}, stack []byte) { +func (entry *apiLoggerEntry) writePanic(status, bytes int, elapsed time.Duration, v any, stack []byte) { entry.logger.Error(). Int("http_status", status). Int("http_content_length", bytes). diff --git a/api/middleware/middleware.go b/api/middleware/middleware.go index a520f01b4..7c9c01bc5 100644 --- a/api/middleware/middleware.go +++ b/api/middleware/middleware.go @@ -63,7 +63,7 @@ func GetTriggerID(request *http.Request) string { return request.Context().Value(triggerIDKey).(string) } -// GetLocalMetricTTL gets local metric ttl duration time from request context, which was sets in TriggerContext middleware. +// GetMetricTTL gets local metric ttl duration time from request context, which was sets in TriggerContext middleware. func GetMetricTTL(request *http.Request) map[moira.ClusterKey]time.Duration { return request.Context().Value(clustersMetricTTLKey).(map[moira.ClusterKey]time.Duration) } @@ -154,7 +154,7 @@ func GetTeamUserID(request *http.Request) string { } // SetContextValueForTest is a helper function that is needed for testing purposes and sets context values with local ContextKey type. -func SetContextValueForTest(ctx context.Context, key string, value interface{}) context.Context { +func SetContextValueForTest(ctx context.Context, key string, value any) context.Context { return context.WithValue(ctx, ContextKey(key), value) } diff --git a/checker/check.go b/checker/check.go index 7c295792e..22f64bd1a 100644 --- a/checker/check.go +++ b/checker/check.go @@ -179,7 +179,7 @@ func (triggerChecker *TriggerChecker) handleUndefinedError(checkData moira.Check triggerChecker.logger.Error(). String(moira.LogFieldNameTriggerID, triggerChecker.triggerID). - String("trigger.cluster_id", triggerChecker.trigger.ClusterId.String()). + String("trigger.cluster_id", triggerChecker.trigger.ClusterID.String()). String("trigger.source", triggerChecker.trigger.TriggerSource.String()). Error(err). Msg("Trigger check failed") diff --git a/checker/check_test.go b/checker/check_test.go index 772f1eb0b..5bae35f39 100644 --- a/checker/check_test.go +++ b/checker/check_test.go @@ -1803,7 +1803,7 @@ func TestTriggerChecker_handlePrepareError(t *testing.T) { trigger := &moira.Trigger{ TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } triggerChecker := TriggerChecker{ triggerID: "test trigger", diff --git a/checker/metrics/conversion/set_helper.go b/checker/metrics/conversion/set_helper.go index bbe98e5ca..3ca1aa501 100644 --- a/checker/metrics/conversion/set_helper.go +++ b/checker/metrics/conversion/set_helper.go @@ -1,6 +1,6 @@ package conversion -var void struct{} = struct{}{} +var void = struct{}{} // set[string] is a map that represents a set of strings with corresponding methods. type set[K comparable] map[K]struct{} diff --git a/checker/metrics/conversion/trigger_metrics.go b/checker/metrics/conversion/trigger_metrics.go index 16027069a..80a1eb450 100644 --- a/checker/metrics/conversion/trigger_metrics.go +++ b/checker/metrics/conversion/trigger_metrics.go @@ -62,11 +62,11 @@ func NewTriggerMetricsWithCapacity(capacity int) TriggerMetrics { // Populate is a function that takes TriggerMetrics and populate targets // that is missing metrics that appear in another targets except the targets that have // only alone metrics. -func (triggerMetrics TriggerMetrics) Populate(lastMetrics map[string]moira.MetricState, declaredAloneMetrics map[string]bool, from int64, to int64) TriggerMetrics { +func (m TriggerMetrics) Populate(lastMetrics map[string]moira.MetricState, declaredAloneMetrics map[string]bool, from int64, to int64) TriggerMetrics { // This one have all metrics that should be in final TriggerMetrics. // This structure filled with metrics from last check, // current received metrics alone metrics from last check. - allMetrics := make(map[string]set[string], len(triggerMetrics)) + allMetrics := make(map[string]set[string], len(m)) for metricName, metricState := range lastMetrics { for targetName := range metricState.Values { @@ -78,7 +78,7 @@ func (triggerMetrics TriggerMetrics) Populate(lastMetrics map[string]moira.Metri } } - for targetName, metrics := range triggerMetrics { + for targetName, metrics := range m { if _, ok := allMetrics[targetName]; !ok { allMetrics[targetName] = make(set[string]) } @@ -88,7 +88,7 @@ func (triggerMetrics TriggerMetrics) Populate(lastMetrics map[string]moira.Metri } } - diff := triggerMetrics.FindMissingMetrics(newSet(declaredAloneMetrics)) + diff := m.FindMissingMetrics(newSet(declaredAloneMetrics)) for targetName, metrics := range diff { for metricName := range metrics { @@ -102,7 +102,7 @@ func (triggerMetrics TriggerMetrics) Populate(lastMetrics map[string]moira.Metri // if declaredAloneMetrics[targetName] { // continue // } - targetMetrics, ok := triggerMetrics[targetName] + targetMetrics, ok := m[targetName] if !ok { targetMetrics = newTriggerTargetMetricsWithCapacity(len(metrics)) } @@ -141,21 +141,21 @@ func (triggerMetrics TriggerMetrics) Populate(lastMetrics map[string]moira.Metri // { // "t3": {metrics}, // } -func (triggerMetrics TriggerMetrics) FilterAloneMetrics(declaredAloneMetrics map[string]bool) (TriggerMetrics, AloneMetrics, error) { +func (m TriggerMetrics) FilterAloneMetrics(declaredAloneMetrics map[string]bool) (TriggerMetrics, AloneMetrics, error) { if len(declaredAloneMetrics) == 0 { - return triggerMetrics, NewAloneMetricsWithCapacity(0), nil + return m, NewAloneMetricsWithCapacity(0), nil } - metricCountUpperBound := len(triggerMetrics) + metricCountUpperBound := len(m) result := NewTriggerMetricsWithCapacity(metricCountUpperBound) aloneMetrics := NewAloneMetricsWithCapacity(metricCountUpperBound) errorBuilder := newErrUnexpectedAloneMetricBuilder() errorBuilder.setDeclared(declaredAloneMetrics) - for targetName, targetMetrics := range triggerMetrics { + for targetName, targetMetrics := range m { if !declaredAloneMetrics[targetName] { - result[targetName] = triggerMetrics[targetName] + result[targetName] = m[targetName] continue } @@ -180,16 +180,16 @@ func (triggerMetrics TriggerMetrics) FilterAloneMetrics(declaredAloneMetrics map // FindMissingMetrics is a function that returns a map of target names with metric names that are absent in // current target but appear in another targets. -func (triggerMetrics TriggerMetrics) FindMissingMetrics(declaredAloneMetrics set[string]) map[string]set[string] { +func (m TriggerMetrics) FindMissingMetrics(declaredAloneMetrics set[string]) map[string]set[string] { result := make(map[string]set[string]) - if len(triggerMetrics) == 0 { + if len(m) == 0 { return result } fullMetrics := make(set[string]) - for targetName, targetMetrics := range triggerMetrics { + for targetName, targetMetrics := range m { if declaredAloneMetrics.contains(targetName) { continue } @@ -197,7 +197,7 @@ func (triggerMetrics TriggerMetrics) FindMissingMetrics(declaredAloneMetrics set fullMetrics = fullMetrics.union(currentMetrics) } - for targetName, targetMetrics := range triggerMetrics { + for targetName, targetMetrics := range m { metricsSet := newSetFromTriggerTargetMetrics(targetMetrics) if declaredAloneMetrics.contains(targetName) { continue diff --git a/checker/trigger_checker_test.go b/checker/trigger_checker_test.go index 234ea9da0..114b12305 100644 --- a/checker/trigger_checker_test.go +++ b/checker/trigger_checker_test.go @@ -33,7 +33,7 @@ func TestInitTriggerChecker(t *testing.T) { getTriggerError := fmt.Errorf("Oppps! Can't read trigger") dataBase.EXPECT().GetTrigger(triggerID).Return(moira.Trigger{ TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, getTriggerError) _, err := MakeTriggerChecker(triggerID, dataBase, logger, config, metricSource.CreateTestMetricSourceProvider(localSource, nil, nil), checkerMetrics) So(err, ShouldBeError) @@ -43,7 +43,7 @@ func TestInitTriggerChecker(t *testing.T) { Convey("No trigger error", func() { dataBase.EXPECT().GetTrigger(triggerID).Return(moira.Trigger{ TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, database.ErrNil) _, err := MakeTriggerChecker(triggerID, dataBase, logger, config, metricSource.CreateTestMetricSourceProvider(localSource, nil, nil), checkerMetrics) So(err, ShouldBeError) @@ -55,7 +55,7 @@ func TestInitTriggerChecker(t *testing.T) { dataBase.EXPECT().GetTrigger(triggerID).Return(moira.Trigger{ TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, nil) dataBase.EXPECT().GetTriggerLastCheck(triggerID).Return(moira.CheckData{}, readLastCheckError) _, err := MakeTriggerChecker(triggerID, dataBase, logger, config, metricSource.CreateTestMetricSourceProvider(localSource, nil, nil), checkerMetrics) @@ -80,7 +80,7 @@ func TestInitTriggerChecker(t *testing.T) { Patterns: []string{"Egais.elasticsearch.*.*.jvm.gc.collection.time"}, TTL: ttl, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } metrics, _ := checkerMetrics.GetCheckMetrics(&trigger) diff --git a/checker/worker/lazy_triggers.go b/checker/worker/lazy_triggers.go index 515cd4c36..aa947762a 100644 --- a/checker/worker/lazy_triggers.go +++ b/checker/worker/lazy_triggers.go @@ -12,7 +12,7 @@ const ( lazyTriggersWorkerTicker = time.Second * 10 ) -func (manager *WorkerManager) lazyTriggersWorker() error { +func (manager *Manager) lazyTriggersWorker() error { localConfig, ok := manager.Config.SourceCheckConfigs[moira.DefaultLocalCluster] if !ok { return fmt.Errorf("can not initialize lazyTriggersWorker: default local source is not configured") @@ -48,7 +48,7 @@ func (manager *WorkerManager) lazyTriggersWorker() error { } } -func (manager *WorkerManager) fillLazyTriggerIDs() error { +func (manager *Manager) fillLazyTriggerIDs() error { triggerIDs, err := manager.Database.GetUnusedTriggerIDs() if err != nil { return err @@ -62,7 +62,7 @@ func (manager *WorkerManager) fillLazyTriggerIDs() error { return nil } -func (manager *WorkerManager) getRandomLazyCacheDuration() time.Duration { +func (manager *Manager) getRandomLazyCacheDuration() time.Duration { maxLazyCacheSeconds := manager.Config.LazyTriggersCheckInterval.Seconds() min := maxLazyCacheSeconds / 2 //nolint i := rand.Float64()*min + min diff --git a/checker/worker/metric_events.go b/checker/worker/metric_events.go index c7a5d44e5..f8ed4aa67 100644 --- a/checker/worker/metric_events.go +++ b/checker/worker/metric_events.go @@ -11,7 +11,7 @@ import ( const defaultMetricEventPopBatchSize = 100 -func (manager *WorkerManager) startLocalMetricEvents() error { +func (manager *Manager) startLocalMetricEvents() error { if manager.Config.MetricEventPopBatchSize < 0 { return errors.New("MetricEventPopBatchSize param was less than zero") } @@ -58,7 +58,7 @@ func (manager *WorkerManager) startLocalMetricEvents() error { return nil } -func (manager *WorkerManager) newMetricsHandler(metricEventsChannel <-chan *moira.MetricEvent) error { +func (manager *Manager) newMetricsHandler(metricEventsChannel <-chan *moira.MetricEvent) error { for { metricEvent, ok := <-metricEventsChannel if !ok { @@ -75,42 +75,42 @@ func (manager *WorkerManager) newMetricsHandler(metricEventsChannel <-chan *moir } } -func (manager *WorkerManager) needHandlePattern(pattern string) bool { +func (manager *Manager) needHandlePattern(pattern string) bool { err := manager.PatternCache.Add(pattern, true, cache.DefaultExpiration) return err == nil } -func (manager *WorkerManager) handleMetricEvent(pattern string) error { +func (manager *Manager) handleMetricEvent(pattern string) error { start := time.Now() defer manager.Metrics.MetricEventsHandleTime.UpdateSince(start) now := time.Now().UTC().Unix() manager.lastData = now - triggerIds, err := manager.Database.GetPatternTriggerIDs(pattern) + triggerIDs, err := manager.Database.GetPatternTriggerIDs(pattern) if err != nil { return err } // Cleanup pattern and its metrics if this pattern doesn't match to any trigger - if len(triggerIds) == 0 { + if len(triggerIDs) == 0 { if err := manager.Database.RemovePatternWithMetrics(pattern); err != nil { return err } } - manager.scheduleLocalTriggerIDsIfNeeded(triggerIds) + manager.scheduleLocalTriggerIDsIfNeeded(triggerIDs) return nil } -func (manager *WorkerManager) scheduleLocalTriggerIDsIfNeeded(triggerIDs []string) { +func (manager *Manager) scheduleLocalTriggerIDsIfNeeded(triggerIDs []string) { needToCheckTriggerIDs := manager.filterOutLazyTriggerIDs(triggerIDs) if len(needToCheckTriggerIDs) > 0 { manager.Database.AddTriggersToCheck(moira.DefaultLocalCluster, needToCheckTriggerIDs) //nolint } } -func (manager *WorkerManager) checkMetricEventsChannelLen(ch <-chan *moira.MetricEvent) error { +func (manager *Manager) checkMetricEventsChannelLen(ch <-chan *moira.MetricEvent) error { checkTicker := time.NewTicker(time.Millisecond * 100) //nolint for { select { diff --git a/checker/worker/scheduler.go b/checker/worker/scheduler.go index c1b5f46c5..9e7fe4885 100644 --- a/checker/worker/scheduler.go +++ b/checker/worker/scheduler.go @@ -12,7 +12,7 @@ import ( const checkerLockTTL = time.Second * 15 type scheduler struct { - manager *WorkerManager + manager *Manager clusterKey moira.ClusterKey sourceCheckConfig checker.SourceCheckConfig name string @@ -21,7 +21,7 @@ type scheduler struct { metrics *metrics.CheckMetrics } -func newScheduler(manager *WorkerManager, clusterKey moira.ClusterKey, validateSource func() error) (*scheduler, error) { +func newScheduler(manager *Manager, clusterKey moira.ClusterKey, validateSource func() error) (*scheduler, error) { metrics, err := manager.Metrics.GetCheckMetricsBySource(clusterKey) if err != nil { return nil, err @@ -95,12 +95,12 @@ func (ch *scheduler) scheduleTriggersToCheck() error { String("cluster_key", ch.clusterKey.String()). Msg("Scheduling triggers") - triggerIds, err := ch.manager.Database.GetTriggerIDs(ch.clusterKey) + triggerIDs, err := ch.manager.Database.GetTriggerIDs(ch.clusterKey) if err != nil { return err } - err = ch.scheduleTriggerIDsIfNeeded(ch.clusterKey, triggerIds) + err = ch.scheduleTriggerIDsIfNeeded(ch.clusterKey, triggerIDs) if err != nil { return err } diff --git a/checker/worker/trigger_handler.go b/checker/worker/trigger_handler.go index 7ae1bde84..8f5f61999 100644 --- a/checker/worker/trigger_handler.go +++ b/checker/worker/trigger_handler.go @@ -14,7 +14,7 @@ import ( const sleepAfterCheckingError = time.Second * 2 // startTriggerHandler is a blocking func. -func (manager *WorkerManager) startTriggerHandler(triggerIDsToCheck <-chan string, metrics *metrics.CheckMetrics) error { +func (manager *Manager) startTriggerHandler(triggerIDsToCheck <-chan string, metrics *metrics.CheckMetrics) error { for { triggerID, ok := <-triggerIDsToCheck if !ok { @@ -35,7 +35,7 @@ func (manager *WorkerManager) startTriggerHandler(triggerIDsToCheck <-chan strin } } -func (manager *WorkerManager) handleTrigger(triggerID string, metrics *metrics.CheckMetrics) (err error) { +func (manager *Manager) handleTrigger(triggerID string, metrics *metrics.CheckMetrics) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("panic: '%s' stack: %s", r, debug.Stack()) @@ -45,7 +45,7 @@ func (manager *WorkerManager) handleTrigger(triggerID string, metrics *metrics.C return err } -func (manager *WorkerManager) handleTriggerInLock(triggerID string, metrics *metrics.CheckMetrics) error { +func (manager *Manager) handleTriggerInLock(triggerID string, metrics *metrics.CheckMetrics) error { acquired, err := manager.Database.SetTriggerCheckLock(triggerID) if err != nil { return err @@ -74,7 +74,7 @@ func (manager *WorkerManager) handleTriggerInLock(triggerID string, metrics *met return err } -func (manager *WorkerManager) checkTrigger(triggerID string) error { +func (manager *Manager) checkTrigger(triggerID string) error { triggerChecker, err := checker.MakeTriggerChecker( triggerID, manager.Database, diff --git a/checker/worker/trigger_queue_pipe.go b/checker/worker/trigger_queue_pipe.go index 16c5d0e31..21dc11e32 100644 --- a/checker/worker/trigger_queue_pipe.go +++ b/checker/worker/trigger_queue_pipe.go @@ -11,7 +11,7 @@ const ( sleepWhenNoTriggerToCheck = time.Millisecond * 500 ) -func (manager *WorkerManager) pipeTriggerToCheckQueue(fetch func(int) ([]string, error), batchSize int) <-chan string { +func (manager *Manager) pipeTriggerToCheckQueue(fetch func(int) ([]string, error), batchSize int) <-chan string { triggerIDsToCheck := make(chan string, batchSize*2) //nolint manager.tomb.Go(func() error { return manager.pipeTriggerToCheckQueueToChan(fetch, batchSize, triggerIDsToCheck) @@ -19,7 +19,7 @@ func (manager *WorkerManager) pipeTriggerToCheckQueue(fetch func(int) ([]string, return triggerIDsToCheck } -func (manager *WorkerManager) pipeTriggerToCheckQueueToChan(fetch func(int) ([]string, error), batchSize int, triggerIDsToCheck chan<- string) error { +func (manager *Manager) pipeTriggerToCheckQueueToChan(fetch func(int) ([]string, error), batchSize int, triggerIDsToCheck chan<- string) error { var fetchDelay time.Duration for { startFetch := time.After(fetchDelay) @@ -36,7 +36,7 @@ func (manager *WorkerManager) pipeTriggerToCheckQueueToChan(fetch func(int) ([]s } } -func (manager *WorkerManager) handleFetchResponse(triggerIDs []string, fetchError error, triggerIDsToCheck chan<- string) time.Duration { +func (manager *Manager) handleFetchResponse(triggerIDs []string, fetchError error, triggerIDsToCheck chan<- string) time.Duration { if fetchError != nil { manager.Logger.Error(). Error(fetchError). @@ -56,7 +56,7 @@ func (manager *WorkerManager) handleFetchResponse(triggerIDs []string, fetchErro return time.Duration(0) } -func (manager *WorkerManager) filterOutLazyTriggerIDs(triggerIDs []string) []string { +func (manager *Manager) filterOutLazyTriggerIDs(triggerIDs []string) []string { triggerIDsToCheck := make([]string, 0, len(triggerIDs)) lazyTriggerIDs := manager.lazyTriggerIDs.Load().(map[string]bool) @@ -64,15 +64,15 @@ func (manager *WorkerManager) filterOutLazyTriggerIDs(triggerIDs []string) []str for _, triggerID := range triggerIDs { if _, ok := lazyTriggerIDs[triggerID]; ok { randomDuration := manager.getRandomLazyCacheDuration() - cacheContainsIdErr := manager.LazyTriggersCache.Add(triggerID, true, randomDuration) + cacheContainsIDErr := manager.LazyTriggersCache.Add(triggerID, true, randomDuration) - if cacheContainsIdErr != nil { + if cacheContainsIDErr != nil { continue } } - cacheContainsIdErr := manager.TriggerCache.Add(triggerID, true, cache.DefaultExpiration) - if cacheContainsIdErr == nil { + cacheContainsIDErr := manager.TriggerCache.Add(triggerID, true, cache.DefaultExpiration) + if cacheContainsIDErr == nil { triggerIDsToCheck = append(triggerIDsToCheck, triggerID) } } diff --git a/checker/worker/worker_manager.go b/checker/worker/worker_manager.go index d4df70f8b..49c363e9c 100644 --- a/checker/worker/worker_manager.go +++ b/checker/worker/worker_manager.go @@ -16,8 +16,8 @@ import ( "github.com/moira-alert/moira/checker" ) -// WorkerManager represents workers for periodically triggers checking based by new events. -type WorkerManager struct { +// Manager represents workers for periodically triggers checking based by new events. +type Manager struct { Logger moira.Logger Database moira.Database @@ -34,7 +34,7 @@ type WorkerManager struct { } // StartWorkers start schedule new MetricEvents and check for NODATA triggers. -func (manager *WorkerManager) StartWorkers() error { +func (manager *Manager) StartWorkers() error { var err error err = manager.startLazyTriggers() @@ -66,7 +66,7 @@ func (manager *WorkerManager) StartWorkers() error { return nil } -func (manager *WorkerManager) makeSourceValidator(clusterKey moira.ClusterKey) (func() error, error) { +func (manager *Manager) makeSourceValidator(clusterKey moira.ClusterKey) (func() error, error) { if clusterKey.TriggerSource == moira.GraphiteLocal { return manager.validateGraphiteLocal, nil } @@ -84,7 +84,7 @@ func (manager *WorkerManager) makeSourceValidator(clusterKey moira.ClusterKey) ( }, nil } -func (manager *WorkerManager) validateGraphiteLocal() error { +func (manager *Manager) validateGraphiteLocal() error { now := time.Now().UTC().Unix() if manager.lastData+manager.Config.StopCheckingIntervalSeconds > now { @@ -94,7 +94,7 @@ func (manager *WorkerManager) validateGraphiteLocal() error { return fmt.Errorf("graphite local source invalid: no metrics for %d second", now-manager.lastData) } -func (manager *WorkerManager) startCheckerWorker(w *scheduler) error { +func (manager *Manager) startCheckerWorker(w *scheduler) error { const maxParallelChecksMaxValue = 1024 * 8 if w.getMaxParallelChecks() > maxParallelChecksMaxValue { return errors.New("MaxParallel" + w.name + "Checks value is too large") @@ -103,7 +103,7 @@ func (manager *WorkerManager) startCheckerWorker(w *scheduler) error { manager.tomb.Go(w.startTriggerScheduler) manager.Logger.Info().Msg(w.name + " scheduler started") - triggerIdsToCheckChan := manager.pipeTriggerToCheckQueue( + triggerIDsToCheckChan := manager.pipeTriggerToCheckQueue( w.getTriggersToCheck, w.getMaxParallelChecks(), ) @@ -111,7 +111,7 @@ func (manager *WorkerManager) startCheckerWorker(w *scheduler) error { for i := 0; i < w.getMaxParallelChecks(); i++ { manager.tomb.Go(func() error { return manager.startTriggerHandler( - triggerIdsToCheckChan, + triggerIDsToCheckChan, w.metrics, ) }) @@ -120,7 +120,7 @@ func (manager *WorkerManager) startCheckerWorker(w *scheduler) error { return nil } -func (manager *WorkerManager) startLazyTriggers() error { +func (manager *Manager) startLazyTriggers() error { manager.lastData = time.Now().UTC().Unix() manager.lazyTriggerIDs.Store(make(map[string]bool)) @@ -131,7 +131,7 @@ func (manager *WorkerManager) startLazyTriggers() error { return nil } -func (manager *WorkerManager) checkTriggersToCheckCount() error { +func (manager *Manager) checkTriggersToCheckCount() error { checkTicker := time.NewTicker(time.Millisecond * 100) //nolint defer checkTicker.Stop() @@ -162,7 +162,7 @@ func getTriggersToCheck(database moira.Database, clusterKey moira.ClusterKey) (i } // Stop stops checks triggers. -func (manager *WorkerManager) Stop() error { +func (manager *Manager) Stop() error { manager.tomb.Kill(nil) return manager.tomb.Wait() } diff --git a/cmd/api/config.go b/cmd/api/config.go index bfd5ca3eb..41fb7b2ba 100644 --- a/cmd/api/config.go +++ b/cmd/api/config.go @@ -29,12 +29,12 @@ func (config *config) ClustersMetricTTL() map[moira.ClusterKey]time.Duration { result[moira.DefaultLocalCluster] = to.Duration(config.Redis.MetricsTTL) for _, remote := range config.Remotes.Graphite { - key := moira.MakeClusterKey(moira.GraphiteRemote, remote.ClusterId) + key := moira.MakeClusterKey(moira.GraphiteRemote, remote.ClusterID) result[key] = to.Duration(remote.MetricsTTL) } for _, remote := range config.Remotes.Prometheus { - key := moira.MakeClusterKey(moira.PrometheusRemote, remote.ClusterId) + key := moira.MakeClusterKey(moira.PrometheusRemote, remote.ClusterID) result[key] = to.Duration(remote.MetricsTTL) } @@ -115,11 +115,11 @@ func (config *apiConfig) getSettings( Listen: config.Listen, MetricsTTL: metricsTTL, Flags: flags, - Authorization: config.Authorization.toApiConfig(webConfig), + Authorization: config.Authorization.toAPIConfig(webConfig), } } -func (auth *authorization) toApiConfig(webConfig *webConfig) api.Authorization { +func (auth *authorization) toAPIConfig(webConfig *webConfig) api.Authorization { adminList := make(map[string]struct{}, len(auth.AdminList)) for _, admin := range auth.AdminList { adminList[admin] = struct{}{} @@ -156,14 +156,14 @@ func (config *webConfig) getSettings(isRemoteEnabled bool, remotes cmd.RemotesCo clusters := []api.MetricSourceCluster{{ TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, ClusterName: "Graphite Local", }} for _, remote := range remotes.Graphite { cluster := api.MetricSourceCluster{ TriggerSource: moira.GraphiteRemote, - ClusterId: remote.ClusterId, + ClusterID: remote.ClusterID, ClusterName: remote.ClusterName, } clusters = append(clusters, cluster) @@ -172,7 +172,7 @@ func (config *webConfig) getSettings(isRemoteEnabled bool, remotes cmd.RemotesCo for _, remote := range remotes.Prometheus { cluster := api.MetricSourceCluster{ TriggerSource: moira.PrometheusRemote, - ClusterId: remote.ClusterId, + ClusterID: remote.ClusterID, ClusterName: remote.ClusterName, } clusters = append(clusters, cluster) diff --git a/cmd/api/config_test.go b/cmd/api/config_test.go index 782fcf301..456aa8d2b 100644 --- a/cmd/api/config_test.go +++ b/cmd/api/config_test.go @@ -123,7 +123,7 @@ func Test_webConfig_getDefault(t *testing.T) { func Test_webConfig_getSettings(t *testing.T) { metricSourceClustersDefault := []api.MetricSourceCluster{{ TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, ClusterName: "Graphite Local", }} remotesDefault := cmd.RemotesConfig{} @@ -213,13 +213,13 @@ func Test_webConfig_getSettings(t *testing.T) { remotes := cmd.RemotesConfig{ Graphite: []cmd.GraphiteRemoteConfig{{ RemoteCommonConfig: cmd.RemoteCommonConfig{ - ClusterId: "default", + ClusterID: "default", ClusterName: "Graphite Remote 123", }, }}, Prometheus: []cmd.PrometheusRemoteConfig{{ RemoteCommonConfig: cmd.RemoteCommonConfig{ - ClusterId: "default", + ClusterID: "default", ClusterName: "Prometheus Remote 888", }, }}, @@ -232,17 +232,17 @@ func Test_webConfig_getSettings(t *testing.T) { MetricSourceClusters: []api.MetricSourceCluster{ { TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, ClusterName: "Graphite Local", }, { TriggerSource: moira.GraphiteRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, ClusterName: "Graphite Remote 123", }, { TriggerSource: moira.PrometheusRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, ClusterName: "Prometheus Remote 888", }, }, diff --git a/cmd/checker/config.go b/cmd/checker/config.go index 5d0cf97ba..53430a4a4 100644 --- a/cmd/checker/config.go +++ b/cmd/checker/config.go @@ -92,10 +92,10 @@ func (config *config) getSettings(logger moira.Logger) *checker.Config { logger.Info(). Int("number_of_cpu", checkConfig.MaxParallelChecks). String("trigger_source", moira.GraphiteRemote.String()). - String("cluster_id", remote.ClusterId.String()). + String("cluster_id", remote.ClusterID.String()). Msg("MaxParallelChecks is not configured, set it to the number of CPU") } - sourceCheckConfigs[moira.MakeClusterKey(moira.GraphiteRemote, remote.ClusterId)] = checkConfig + sourceCheckConfigs[moira.MakeClusterKey(moira.GraphiteRemote, remote.ClusterID)] = checkConfig } for _, remote := range config.Remotes.Prometheus { @@ -107,10 +107,10 @@ func (config *config) getSettings(logger moira.Logger) *checker.Config { logger.Info(). Int("number_of_cpu", checkConfig.MaxParallelChecks). String("trigger_source", moira.PrometheusRemote.String()). - String("cluster_id", remote.ClusterId.String()). + String("cluster_id", remote.ClusterID.String()). Msg("MaxParallelChecks is not configured, set it to the number of CPU") } - sourceCheckConfigs[moira.MakeClusterKey(moira.PrometheusRemote, remote.ClusterId)] = checkConfig + sourceCheckConfigs[moira.MakeClusterKey(moira.PrometheusRemote, remote.ClusterID)] = checkConfig } return &checker.Config{ diff --git a/cmd/checker/main.go b/cmd/checker/main.go index cf1c56fe3..bcdb88cf6 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -97,7 +97,7 @@ func main() { } cacheExpiration := checkerSettings.MetricEventTriggerCheckInterval - checkerWorkerManager := &worker.WorkerManager{ + checkerWorkerManager := &worker.Manager{ Logger: logger, Database: database, Config: checkerSettings, @@ -146,7 +146,7 @@ func checkSingleTrigger(database moira.Database, metrics *metrics.CheckerMetrics os.Exit(0) } -func stopChecker(service *worker.WorkerManager) { +func stopChecker(service *worker.Manager) { if err := service.Stop(); err != nil { logger.Error(). Error(err). diff --git a/cmd/cli/from_2.3_to_2.4.go b/cmd/cli/from_2.3_to_2.4.go index de98dbf64..4377c97ff 100644 --- a/cmd/cli/from_2.3_to_2.4.go +++ b/cmd/cli/from_2.3_to_2.4.go @@ -14,7 +14,7 @@ func updateFrom23(logger moira.Logger, dataBase moira.Database) error { return nil } -func downgradeTo23(logger moira.Logger, dataBase moira.Database) error { +func downgradeTo23() error { return nil } diff --git a/cmd/cli/from_2.9_to_2.10.go b/cmd/cli/from_2.9_to_2.10.go index 3542dfc6a..5ea470070 100644 --- a/cmd/cli/from_2.9_to_2.10.go +++ b/cmd/cli/from_2.9_to_2.10.go @@ -47,14 +47,14 @@ func createKeyForLocalTriggers(ctx context.Context, logger moira.Logger, databas case *redis.DbConnector: client := d.Client() - localTriggerIds, err := client.SDiff(ctx, triggersListKey, remoteTriggersListKey, prometheusTriggersListKey).Result() + localTriggerIDs, err := client.SDiff(ctx, triggersListKey, remoteTriggersListKey, prometheusTriggersListKey).Result() if err != nil { return err } logger.Info().Msg("Finish getting local trigger IDs") - _, err = client.SAdd(ctx, localTriggersListKey, localTriggerIds).Result() + _, err = client.SAdd(ctx, localTriggersListKey, localTriggerIDs).Result() if err != nil { return err } diff --git a/cmd/cli/main.go b/cmd/cli/main.go index 54a054c96..3ff7d92a1 100644 --- a/cmd/cli/main.go +++ b/cmd/cli/main.go @@ -124,7 +124,7 @@ func main() { //nolint toVersion := checkValidVersion(logger, downgradeToVersion, false) switch toVersion { case "2.3": - err := downgradeTo23(logger, database) + err := downgradeTo23() if err != nil { logger.Fatal(). Error(err). @@ -483,7 +483,7 @@ func openFile(filePath string, mode int) (*os.File, error) { if filePath == "" { return nil, fmt.Errorf("file is not specified") } - file, err := os.OpenFile(filePath, mode, 0o666) //nolint:gofumpt,gomnd + file, err := os.OpenFile(filePath, mode, 0o666) //nolint:gofumpt if err != nil { return nil, fmt.Errorf("cannot open file: %w", err) } diff --git a/cmd/cli/metrics.go b/cmd/cli/metrics.go index b4b0d61ff..7450215e3 100644 --- a/cmd/cli/metrics.go +++ b/cmd/cli/metrics.go @@ -12,11 +12,7 @@ func handleCleanUpOutdatedMetrics(config cleanupConfig, database moira.Database) return err } - if err = database.CleanUpOutdatedMetrics(duration); err != nil { - return err - } - - return nil + return database.CleanUpOutdatedMetrics(duration) } func handleCleanUpFutureMetrics(config cleanupConfig, database moira.Database) error { @@ -25,11 +21,7 @@ func handleCleanUpFutureMetrics(config cleanupConfig, database moira.Database) e return err } - if err = database.CleanUpFutureMetrics(duration); err != nil { - return err - } - - return nil + return database.CleanUpFutureMetrics(duration) } func handleCleanUpAbandonedRetentions(database moira.Database) error { diff --git a/cmd/cli/telegram_utils.go b/cmd/cli/telegram_utils.go index cd1fa5fad..5a4ba3e6d 100644 --- a/cmd/cli/telegram_utils.go +++ b/cmd/cli/telegram_utils.go @@ -25,7 +25,7 @@ func callFunc(connector *redis.DbConnector, fn func(connector *redis.DbConnector switch c := client.(type) { case *goredis.ClusterClient: - return c.ForEachMaster(ctx, func(ctx context.Context, shard *goredis.Client) error { + return c.ForEachMaster(ctx, func(_ context.Context, shard *goredis.Client) error { return fn(connector, shard) }) default: diff --git a/cmd/config.go b/cmd/config.go index 7a5ce2321..4cc775261 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -186,16 +186,16 @@ func (remotes *RemotesConfig) Validate() error { func validateRemotes[T remoteCommon](remotes []T) []error { errs := make([]error, 0) - keys := make(map[moira.ClusterId]int) + keys := make(map[moira.ClusterID]int) for _, remote := range remotes { common := remote.getRemoteCommon() - if common.ClusterId == moira.ClusterNotSet { + if common.ClusterID == moira.ClusterNotSet { err := fmt.Errorf("cluster id must be set for remote source (name: `%s`, url: `%s`)", common.ClusterName, common.URL, ) errs = append(errs, err) } - keys[common.ClusterId]++ + keys[common.ClusterID]++ } for key, count := range keys { @@ -211,7 +211,7 @@ func validateRemotes[T remoteCommon](remotes []T) []error { // RemoteCommonConfig is designed to be embedded in remote configs, It contains fields that are similar for all remotes. type RemoteCommonConfig struct { // Unique id of the cluster - ClusterId moira.ClusterId `yaml:"cluster_id"` + ClusterID moira.ClusterID `yaml:"cluster_id"` // Human-readable name of the cluster ClusterName string `yaml:"cluster_name"` // graphite url e.g http://graphite/render @@ -297,7 +297,7 @@ type ImageStoreConfig struct { } // ReadConfig parses config file by the given path into Moira-used type. -func ReadConfig(configFileName string, config interface{}) error { +func ReadConfig(configFileName string, config any) error { configYaml, err := os.ReadFile(configFileName) if err != nil { return fmt.Errorf("can't read file [%s] [%s]", configFileName, err.Error()) @@ -310,7 +310,7 @@ func ReadConfig(configFileName string, config interface{}) error { } // PrintConfig prints config to stdout. -func PrintConfig(config interface{}) { +func PrintConfig(config any) { d, _ := yaml.Marshal(&config) fmt.Println(string(d)) } diff --git a/cmd/notifier/config.go b/cmd/notifier/config.go index 8277024b9..a056a6fbb 100644 --- a/cmd/notifier/config.go +++ b/cmd/notifier/config.go @@ -41,7 +41,7 @@ type notifierConfig struct { // Delay before performing one more send attempt ReschedulingDelay string `yaml:"rescheduling_delay"` // Senders configuration section. See https://moira.readthedocs.io/en/latest/installation/configuration.html for more explanation - Senders []map[string]interface{} `yaml:"senders"` + Senders []map[string]any `yaml:"senders"` // Self state monitor configuration section. Note: No inner subscriptions is required. It's own notification mechanism will be used. SelfState selfStateConfig `yaml:"moira_selfstate"` // Web-UI uri prefix for trigger links in notifications. For example: with 'http://localhost' every notification will contain link like 'http://localhost/trigger/triggerId' @@ -209,7 +209,7 @@ func (config *notifierConfig) getSettings(logger moira.Logger) notifier.Config { func checkDateTimeFormat(format string) error { fallbackTime := time.Date(0, 1, 1, 0, 0, 0, 0, time.UTC) parsedTime, err := time.Parse(format, time.Now().Format(format)) - if err != nil || parsedTime == fallbackTime { + if err != nil || parsedTime.Equal(fallbackTime) { return fmt.Errorf("could not parse date time format '%v', result: '%v', error: '%w'", format, parsedTime, err) } return nil diff --git a/cmd/notifier/main.go b/cmd/notifier/main.go index 37e1ac7f7..d03337430 100644 --- a/cmd/notifier/main.go +++ b/cmd/notifier/main.go @@ -98,7 +98,7 @@ func main() { ReschedulingDelay: notifierConfig.ReschedulingDelay, } - notifierMetrics := metrics.ConfigureNotifierMetrics(telemetry.Metrics, serviceName) + notifierMetrics := metrics.ConfigureNotifierMetrics(telemetry.Metrics) sender := notifier.NewNotifier( database, logger, diff --git a/cmd/source_provider.go b/cmd/source_provider.go index cbd8cf063..d5e8833ee 100644 --- a/cmd/source_provider.go +++ b/cmd/source_provider.go @@ -26,7 +26,7 @@ func InitMetricSources(remotes RemotesConfig, database moira.Database, logger mo if err != nil { return nil, err } - provider.RegisterSource(moira.MakeClusterKey(moira.GraphiteRemote, graphite.ClusterId), source) + provider.RegisterSource(moira.MakeClusterKey(moira.GraphiteRemote, graphite.ClusterID), source) } for _, prom := range remotes.Prometheus { @@ -35,7 +35,7 @@ func InitMetricSources(remotes RemotesConfig, database moira.Database, logger mo if err != nil { return nil, err } - provider.RegisterSource(moira.MakeClusterKey(moira.PrometheusRemote, prom.ClusterId), source) + provider.RegisterSource(moira.MakeClusterKey(moira.PrometheusRemote, prom.ClusterID), source) } return provider, nil diff --git a/database/redis/contact_notification_history.go b/database/redis/contact_notification_history.go index 6b15c27aa..70dbef5c7 100644 --- a/database/redis/contact_notification_history.go +++ b/database/redis/contact_notification_history.go @@ -29,7 +29,7 @@ func getNotificationStruct(notificationString string) (moira.NotificationEventHi return object, nil } -func (connector *DbConnector) GetNotificationsByContactIdWithLimit(contactID string, from int64, to int64) ([]*moira.NotificationEventHistoryItem, error) { +func (connector *DbConnector) GetNotificationsByContactIDWithLimit(contactID string, from int64, to int64) ([]*moira.NotificationEventHistoryItem, error) { c := *connector.client var notifications []*moira.NotificationEventHistoryItem diff --git a/database/redis/contact_notification_history_test.go b/database/redis/contact_notification_history_test.go index b57e60c17..d7fc1e837 100644 --- a/database/redis/contact_notification_history_test.go +++ b/database/redis/contact_notification_history_test.go @@ -60,7 +60,7 @@ var eventsShouldBeInDb = []*moira.NotificationEventHistoryItem{ }, } -func TestGetNotificationsByContactIdWithLimit(t *testing.T) { +func TestGetNotificationsByContactIDWithLimit(t *testing.T) { logger, _ := logging.GetLogger("dataBase") dataBase := NewTestDatabase(logger) @@ -69,7 +69,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { defer dataBase.Flush() Convey("While no data then notification items should be empty", func() { - items, err := dataBase.GetNotificationsByContactIdWithLimit( + items, err := dataBase.GetNotificationsByContactIDWithLimit( "id", eventsShouldBeInDb[0].TimeStamp, eventsShouldBeInDb[0].TimeStamp) @@ -83,7 +83,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { So(err, ShouldBeNil) Convey("Ensure that we can find event on +- 5 seconds interval", func() { - eventFromDb, err := dataBase.GetNotificationsByContactIdWithLimit( + eventFromDb, err := dataBase.GetNotificationsByContactIDWithLimit( eventsShouldBeInDb[0].ContactID, eventsShouldBeInDb[0].TimeStamp-5, eventsShouldBeInDb[0].TimeStamp+5) @@ -92,7 +92,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { }) Convey("Ensure that we can find event exactly by its timestamp", func() { - eventFromDb, err := dataBase.GetNotificationsByContactIdWithLimit( + eventFromDb, err := dataBase.GetNotificationsByContactIDWithLimit( eventsShouldBeInDb[0].ContactID, eventsShouldBeInDb[0].TimeStamp, eventsShouldBeInDb[0].TimeStamp) @@ -101,7 +101,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { }) Convey("Ensure that we can find event if 'from' border equals its timestamp", func() { - eventFromDb, err := dataBase.GetNotificationsByContactIdWithLimit( + eventFromDb, err := dataBase.GetNotificationsByContactIDWithLimit( eventsShouldBeInDb[0].ContactID, eventsShouldBeInDb[0].TimeStamp, eventsShouldBeInDb[0].TimeStamp+5) @@ -110,7 +110,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { }) Convey("Ensure that we can find event if 'to' border equals its timestamp", func() { - eventFromDb, err := dataBase.GetNotificationsByContactIdWithLimit( + eventFromDb, err := dataBase.GetNotificationsByContactIDWithLimit( eventsShouldBeInDb[0].ContactID, eventsShouldBeInDb[0].TimeStamp-5, eventsShouldBeInDb[0].TimeStamp) @@ -119,7 +119,7 @@ func TestGetNotificationsByContactIdWithLimit(t *testing.T) { }) Convey("Ensure that we can't find event time borders don't fit event timestamp", func() { - eventFromDb, err := dataBase.GetNotificationsByContactIdWithLimit( + eventFromDb, err := dataBase.GetNotificationsByContactIDWithLimit( eventsShouldBeInDb[0].ContactID, 928930626, 992089026) @@ -145,7 +145,7 @@ func TestPushNotificationToHistory(t *testing.T) { err2 := dataBase.PushContactNotificationToHistory(&inputScheduledNotification) So(err2, ShouldBeNil) - dbContent, err3 := dataBase.GetNotificationsByContactIdWithLimit( + dbContent, err3 := dataBase.GetNotificationsByContactIDWithLimit( inputScheduledNotification.Contact.ID, inputScheduledNotification.Timestamp, inputScheduledNotification.Timestamp) diff --git a/database/redis/database.go b/database/redis/database.go index 0633b3098..7be066f58 100644 --- a/database/redis/database.go +++ b/database/redis/database.go @@ -163,7 +163,7 @@ func (connector *DbConnector) callFunc(fn func(connector *DbConnector, client re switch c := client.(type) { case *redis.ClusterClient: - return c.ForEachMaster(connector.context, func(ctx context.Context, shard *redis.Client) error { + return c.ForEachMaster(connector.context, func(_ context.Context, shard *redis.Client) error { return fn(connector, shard) }) default: diff --git a/database/redis/last_check.go b/database/redis/last_check.go index ab351c3ed..81f36e4ff 100644 --- a/database/redis/last_check.go +++ b/database/redis/last_check.go @@ -86,8 +86,8 @@ func (connector *DbConnector) getSelfStateCheckCountKey(clusterKey moira.Cluster return "" } - if clusterKey.ClusterId != moira.DefaultCluster { - key = key + ":" + clusterKey.ClusterId.String() + if clusterKey.ClusterID != moira.DefaultCluster { + key = key + ":" + clusterKey.ClusterID.String() } return key diff --git a/database/redis/last_check_test.go b/database/redis/last_check_test.go index 92dd43c32..58f84c6e3 100644 --- a/database/redis/last_check_test.go +++ b/database/redis/last_check_test.go @@ -327,7 +327,7 @@ func TestCleanUpAbandonedTriggerLastCheck(t *testing.T) { TTLState: &moira.TTLStateNODATA, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } err := dataBase.SaveTrigger(trigger.ID, &trigger) So(err, ShouldBeNil) @@ -527,7 +527,7 @@ func TestGetTriggersLastCheck(t *testing.T) { }) Convey("Test with deleted trigger", func() { - dataBase.RemoveTriggerLastCheck("test2") //nolint + dataBase.RemoveTriggerLastCheck("test2") defer func() { _ = dataBase.SetTriggerLastCheck("test2", &moira.CheckData{ Timestamp: 2, diff --git a/database/redis/locks.go b/database/redis/locks.go index 5d9eccafb..90c346b86 100644 --- a/database/redis/locks.go +++ b/database/redis/locks.go @@ -40,7 +40,7 @@ func (lock *Lock) Acquire(stop <-chan struct{}) (<-chan struct{}, error) { return nil, database.ErrLockAlreadyHeld } - switch e := err.(type) { // nolint:errorlint + switch e := err.(type) { // nolint:errorlint,revive case *database.ErrLockNotAcquired: if !errors.Is(e.Err, redsync.ErrFailed) { return nil, err diff --git a/database/redis/notification_test.go b/database/redis/notification_test.go index 06048b813..b81ea8fbc 100644 --- a/database/redis/notification_test.go +++ b/database/redis/notification_test.go @@ -308,7 +308,7 @@ func TestGetNotificationsInTxWithLimit(t *testing.T) { ctx := database.context Convey("Test getNotificationsInTxWithLimit", t, func() { - var limit int64 = 0 + var limit int64 now = time.Now().Unix() notificationNew := moira.ScheduledNotification{ SendFail: 1, @@ -589,7 +589,7 @@ func TestFilterNotificationsByState(t *testing.T) { }) Convey("With trigger on maintenance", func() { - var triggerMaintenance int64 = time.Now().Add(time.Hour).Unix() + triggerMaintenance := time.Now().Add(time.Hour).Unix() database.SetTriggerCheckMaintenance("test1", map[string]int64{}, &triggerMaintenance, "test", 100) //nolint defer func() { triggerMaintenance = 0 @@ -732,7 +732,7 @@ func TestHandleNotifications(t *testing.T) { }) Convey("With both delayed and not delayed valid notifications and trigger on maintenance", func() { - var triggerMaintenance int64 = time.Now().Add(time.Hour).Unix() + triggerMaintenance := time.Now().Add(time.Hour).Unix() database.SetTriggerCheckMaintenance("test1", map[string]int64{}, &triggerMaintenance, "test", 100) //nolint defer func() { triggerMaintenance = 0 @@ -1066,7 +1066,7 @@ func TestFetchNotificationsDo(t *testing.T) { }) Convey("Test delayed notifications with ts and trigger on maintenance", func() { - var triggerMaintenance int64 = time.Now().Add(time.Hour).Unix() + triggerMaintenance := time.Now().Add(time.Hour).Unix() database.SetTriggerCheckMaintenance("test1", map[string]int64{}, &triggerMaintenance, "test", 100) //nolint defer func() { triggerMaintenance = 0 diff --git a/database/redis/reply/trigger.go b/database/redis/reply/trigger.go index ed830e27f..b1d8c11fe 100644 --- a/database/redis/reply/trigger.go +++ b/database/redis/reply/trigger.go @@ -29,7 +29,7 @@ type triggerStorageElement struct { TTL string `json:"ttl,omitempty"` IsRemote bool `json:"is_remote"` TriggerSource moira.TriggerSource `json:"trigger_source,omitempty"` - ClusterId moira.ClusterId `json:"cluster_id,omitempty"` + ClusterID moira.ClusterID `json:"cluster_id,omitempty"` MuteNewMetrics bool `json:"mute_new_metrics,omitempty"` AloneMetrics map[string]bool `json:"alone_metrics"` CreatedAt *int64 `json:"created_at"` @@ -51,7 +51,7 @@ func (storageElement *triggerStorageElement) toTrigger() moira.Trigger { // TODO(litleleprikon): END remove in moira v2.8.0. Compatibility with moira < v2.6.0 triggerSource := storageElement.TriggerSource.FillInIfNotSet(storageElement.IsRemote) - clusterId := storageElement.ClusterId.FillInIfNotSet() + clusterID := storageElement.ClusterID.FillInIfNotSet() return moira.Trigger{ ID: storageElement.ID, Name: storageElement.Name, @@ -68,7 +68,7 @@ func (storageElement *triggerStorageElement) toTrigger() moira.Trigger { Patterns: storageElement.Patterns, TTL: getTriggerTTL(storageElement.TTL), TriggerSource: triggerSource, - ClusterId: clusterId, + ClusterID: clusterID, MuteNewMetrics: storageElement.MuteNewMetrics, AloneMetrics: storageElement.AloneMetrics, CreatedAt: storageElement.CreatedAt, @@ -96,7 +96,7 @@ func toTriggerStorageElement(trigger *moira.Trigger, triggerID string) *triggerS TTL: getTriggerTTLString(trigger.TTL), IsRemote: trigger.TriggerSource == moira.GraphiteRemote, TriggerSource: trigger.TriggerSource, - ClusterId: trigger.ClusterId, + ClusterID: trigger.ClusterID, MuteNewMetrics: trigger.MuteNewMetrics, AloneMetrics: trigger.AloneMetrics, CreatedAt: trigger.CreatedAt, diff --git a/database/redis/subscription.go b/database/redis/subscription.go index 905ac0095..37062002b 100644 --- a/database/redis/subscription.go +++ b/database/redis/subscription.go @@ -269,7 +269,7 @@ func addSendSubscriptionRequest(context context.Context, pipe redis.Pipeliner, s return nil } -func (connector *DbConnector) getTriggersIdsByTags(tags []string) ([]string, error) { +func (connector *DbConnector) getTriggersIDsByTags(tags []string) ([]string, error) { if len(tags) == 0 { return make([]string, 0), nil } @@ -293,7 +293,7 @@ func (connector *DbConnector) getSubscriptionTriggers(subscription *moira.Subscr if subscription == nil { return make([]*moira.Trigger, 0), nil } - triggersIDs, err := connector.getTriggersIdsByTags(subscription.Tags) + triggersIDs, err := connector.getTriggersIDsByTags(subscription.Tags) if err != nil { return nil, err } diff --git a/database/redis/trigger.go b/database/redis/trigger.go index 86ca752fd..e76eaba85 100644 --- a/database/redis/trigger.go +++ b/database/redis/trigger.go @@ -17,11 +17,11 @@ import ( // GetAllTriggerIDs gets all moira triggerIDs. func (connector *DbConnector) GetAllTriggerIDs() ([]string, error) { c := *connector.client - triggerIds, err := c.SMembers(connector.context, allTriggersListKey).Result() + triggerIDs, err := c.SMembers(connector.context, allTriggersListKey).Result() if err != nil { return nil, fmt.Errorf("failed to get all triggers-list: %s", err.Error()) } - return triggerIds, nil + return triggerIDs, nil } // GetTriggerIDs returns list of ids of triggers with given cluster key. @@ -32,11 +32,11 @@ func (connector *DbConnector) GetTriggerIDs(clusterKey moira.ClusterKey) ([]stri return nil, fmt.Errorf("failed to get triggers-list: %w", err) } - triggerIds, err := c.SMembers(connector.context, key).Result() + triggerIDs, err := c.SMembers(connector.context, key).Result() if err != nil { return nil, fmt.Errorf("failed to get triggers-list: %w", err) } - return triggerIds, nil + return triggerIDs, nil } func (connector *DbConnector) GetTriggerCount(clusterKeys []moira.ClusterKey) (map[moira.ClusterKey]int64, error) { @@ -119,11 +119,11 @@ func (connector *DbConnector) GetTriggers(triggerIDs []string) ([]*moira.Trigger func (connector *DbConnector) GetPatternTriggerIDs(pattern string) ([]string, error) { c := *connector.client - triggerIds, err := c.SMembers(connector.context, patternTriggersKey(pattern)).Result() + triggerIDs, err := c.SMembers(connector.context, patternTriggersKey(pattern)).Result() if err != nil { return nil, fmt.Errorf("failed to retrieve pattern triggers for pattern: %s, error: %s", pattern, err.Error()) } - return triggerIds, nil + return triggerIDs, nil } // RemovePatternTriggerIDs removes all triggerIDs list accepted to given pattern. @@ -331,9 +331,9 @@ func (connector *DbConnector) GetTriggerChecks(triggerIDs []string) ([]*moira.Tr if err != nil && !errors.Is(err, redis.Nil) { return nil, fmt.Errorf("failed to EXEC: %w", err) } - var slices [][]interface{} + var slices [][]any for i := 0; i < len(rawResponse); i += 4 { - arr := make([]interface{}, 0, 5) + arr := make([]any, 0, 5) arr = append(arr, triggerIDs[i/4]) arr = append(arr, rawResponse[i], rawResponse[i+1], rawResponse[i+2], rawResponse[i+3]) slices = append(slices, arr) @@ -447,8 +447,8 @@ func makeTriggerListKey(clusterKey moira.ClusterKey) (string, error) { return "", fmt.Errorf("unknown trigger source %s", clusterKey.TriggerSource) } - if clusterKey.ClusterId != moira.DefaultCluster { - key = key + ":" + clusterKey.ClusterId.String() + if clusterKey.ClusterID != moira.DefaultCluster { + key = key + ":" + clusterKey.ClusterID.String() } return key, nil diff --git a/database/redis/trigger_test.go b/database/redis/trigger_test.go index 957b2c2ca..d6d836b1c 100644 --- a/database/redis/trigger_test.go +++ b/database/redis/trigger_test.go @@ -98,7 +98,6 @@ func TestTriggerStoring(t *testing.T) { So(actualTags, ShouldResemble, trigger.Tags) // Now just add tag and pattern in trigger and save it - trigger = nil changedTrigger := &testTriggers[1] err = dataBase.SaveTrigger(changedTrigger.ID, changedTrigger) So(err, ShouldBeNil) @@ -138,7 +137,6 @@ func TestTriggerStoring(t *testing.T) { // Now remove old tag and pattern in trigger and save it oldTag := changedTrigger.Tags[1] oldPattern := changedTrigger.Patterns[1] - changedTrigger = nil changedAgainTrigger := &testTriggers[2] err = dataBase.SaveTrigger(changedAgainTrigger.ID, changedAgainTrigger) So(err, ShouldBeNil) @@ -312,7 +310,7 @@ func TestTriggerStoring(t *testing.T) { Patterns: []string{pattern1}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, AloneMetrics: map[string]bool{}, } @@ -324,7 +322,7 @@ func TestTriggerStoring(t *testing.T) { Patterns: []string{pattern2}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, AloneMetrics: map[string]bool{}, } @@ -547,7 +545,7 @@ func TestRemoteTrigger(t *testing.T) { Targets: []string{"test.target.remote1"}, Patterns: []string{pattern}, TriggerSource: moira.GraphiteRemote, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, } @@ -814,17 +812,17 @@ func TestDbConnector_GetTriggerIDsStartWith(t *testing.T) { triggerWithPrefix1 := moira.Trigger{ ID: prefix + "1", TriggerSource: moira.GraphiteLocal, - ClusterId: moira.ClusterNotSet, + ClusterID: moira.ClusterNotSet, } triggerWithPrefix2 := moira.Trigger{ ID: prefix + "2", TriggerSource: moira.GraphiteLocal, - ClusterId: moira.ClusterNotSet, + ClusterID: moira.ClusterNotSet, } triggerWithoutPrefix := moira.Trigger{ ID: "without-prefix", TriggerSource: moira.GraphiteLocal, - ClusterId: moira.ClusterNotSet, + ClusterID: moira.ClusterNotSet, } triggers := []moira.Trigger{ triggerWithPrefix1, @@ -865,7 +863,7 @@ var testTriggers = []moira.Trigger{ AloneMetrics: map[string]bool{}, // TODO: Test that empty TriggerSource is filled on getting vale from db TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000001", @@ -876,7 +874,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{"t2": true}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000001", @@ -887,7 +885,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000004", @@ -897,7 +895,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000005", @@ -907,7 +905,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000006", @@ -917,7 +915,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000007", @@ -927,7 +925,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000008", @@ -937,7 +935,7 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "triggerID-0000000000009", @@ -947,6 +945,6 @@ var testTriggers = []moira.Trigger{ TriggerType: moira.RisingTrigger, AloneMetrics: map[string]bool{}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, } diff --git a/database/redis/triggers_to_check.go b/database/redis/triggers_to_check.go index b6a990a74..0a2f4ab5d 100644 --- a/database/redis/triggers_to_check.go +++ b/database/redis/triggers_to_check.go @@ -141,8 +141,8 @@ func makeTriggersToCheckKey(clusterKey moira.ClusterKey) (string, error) { return "", fmt.Errorf("unknown trigger source `%s`", clusterKey.TriggerSource.String()) } - if clusterKey.ClusterId != moira.DefaultCluster { - key = key + ":" + clusterKey.ClusterId.String() + if clusterKey.ClusterID != moira.DefaultCluster { + key = key + ":" + clusterKey.ClusterID.String() } return key, nil diff --git a/database/redis/unused_triggers.go b/database/redis/unused_triggers.go index 15d1b2fb6..511235b1a 100644 --- a/database/redis/unused_triggers.go +++ b/database/redis/unused_triggers.go @@ -32,14 +32,14 @@ func (connector *DbConnector) GetUnusedTriggerIDs() ([]string, error) { ctx := connector.context c := *connector.client - triggerIds, err := c.SMembers(ctx, unusedTriggersKey).Result() + triggerIDs, err := c.SMembers(ctx, unusedTriggersKey).Result() if err != nil { if errors.Is(err, redis.Nil) { return make([]string, 0), nil } return nil, fmt.Errorf("failed to get all unused triggers: %s", err.Error()) } - return triggerIds, nil + return triggerIDs, nil } // MarkTriggersAsUsed removes trigger IDs from Redis set. diff --git a/database/redis/unused_triggers_test.go b/database/redis/unused_triggers_test.go index dbed460f1..9ebb0afc1 100644 --- a/database/redis/unused_triggers_test.go +++ b/database/redis/unused_triggers_test.go @@ -93,7 +93,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } trigger1Ver2 := &moira.Trigger{ @@ -104,7 +104,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } trigger1Ver3 := &moira.Trigger{ @@ -115,7 +115,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } subscription1Ver1 := &moira.SubscriptionData{ @@ -193,7 +193,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "new-trigger-2", @@ -203,7 +203,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "new-trigger-3", @@ -213,7 +213,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "new-trigger-4", @@ -223,7 +223,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "new-trigger-5", @@ -233,7 +233,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, { ID: "new-trigger-6", @@ -243,7 +243,7 @@ func TestUnusedTriggers(t *testing.T) { Patterns: []string{"test.pattern.1"}, TriggerType: moira.RisingTrigger, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, }, } subscriptions := []*moira.SubscriptionData{ diff --git a/datatypes.go b/datatypes.go index 7756697a6..dfd4d0cb1 100644 --- a/datatypes.go +++ b/datatypes.go @@ -85,7 +85,8 @@ func (event *NotificationEvent) CreateMessage(location *time.Location) string { return "" } - if event.MessageEventInfo.Interval != nil && event.MessageEventInfo.Maintenance == nil { + if event.MessageEventInfo.Interval != nil && + event.MessageEventInfo.Maintenance == nil { return fmt.Sprintf(remindMessage, *event.MessageEventInfo.Interval) } @@ -100,7 +101,8 @@ func (event *NotificationEvent) CreateMessage(location *time.Location) string { location = time.UTC } - if event.MessageEventInfo.Maintenance.StartUser != nil || event.MessageEventInfo.Maintenance.StartTime != nil { + if event.MessageEventInfo.Maintenance.StartUser != nil || + event.MessageEventInfo.Maintenance.StartTime != nil { messageBuffer.WriteString(" Maintenance was set") if event.MessageEventInfo.Maintenance.StartUser != nil { messageBuffer.WriteString(" by ") @@ -169,7 +171,7 @@ type TriggerData struct { ErrorValue float64 `json:"error_value" example:"1000"` IsRemote bool `json:"is_remote" example:"false"` TriggerSource TriggerSource `json:"trigger_source,omitempty" example:"graphite_local"` - ClusterId ClusterId `json:"cluster_id,omitempty" example:"default"` + ClusterID ClusterID `json:"cluster_id,omitempty" example:"default"` Tags []string `json:"__notifier_trigger_tags" example:"server,disk"` } @@ -373,7 +375,7 @@ type Trigger struct { PythonExpression *string `json:"python_expression,omitempty" extensions:"x-nullable"` Patterns []string `json:"patterns" example:""` TriggerSource TriggerSource `json:"trigger_source,omitempty" example:"graphite_local"` - ClusterId ClusterId `json:"cluster_id,omitempty" example:"default"` + ClusterID ClusterID `json:"cluster_id,omitempty" example:"default"` MuteNewMetrics bool `json:"mute_new_metrics" example:"false"` AloneMetrics map[string]bool `json:"alone_metrics" example:"t1:true"` CreatedAt *int64 `json:"created_at" format:"int64" extensions:"x-nullable"` @@ -389,20 +391,20 @@ const ( // ClusterKey returns cluster key composed of trigger source and cluster id associated with the trigger. func (trigger *Trigger) ClusterKey() ClusterKey { - return MakeClusterKey(trigger.TriggerSource, trigger.ClusterId) + return MakeClusterKey(trigger.TriggerSource, trigger.ClusterID) } // TriggerSource is a enum which values correspond to types of moira's metric sources. type TriggerSource string var ( - TriggerSourceNotSet TriggerSource = "" + TriggerSourceNotSet TriggerSource GraphiteLocal TriggerSource = "graphite_local" GraphiteRemote TriggerSource = "graphite_remote" PrometheusRemote TriggerSource = "prometheus_remote" ) -func (s *TriggerSource) UnmarshalJSON(data []byte) error { +func (ts *TriggerSource) UnmarshalJSON(data []byte) error { var v string if err := json.Unmarshal(data, &v); err != nil { return err @@ -410,54 +412,53 @@ func (s *TriggerSource) UnmarshalJSON(data []byte) error { source := TriggerSource(v) if source != GraphiteLocal && source != GraphiteRemote && source != PrometheusRemote { - *s = TriggerSourceNotSet + *ts = TriggerSourceNotSet return nil } - *s = source + *ts = source return nil } -// Needed for backwards compatibility with moira versions that used only isRemote flag. -func (triggerSource TriggerSource) FillInIfNotSet(isRemote bool) TriggerSource { - if triggerSource == TriggerSourceNotSet { +// FillInIfNotSet Needed for backwards compatibility with moira versions that used only isRemote flag. +func (ts TriggerSource) FillInIfNotSet(isRemote bool) TriggerSource { + if ts == TriggerSourceNotSet { if isRemote { return GraphiteRemote - } else { - return GraphiteLocal } + return GraphiteLocal } - return triggerSource + return ts } -func (triggerSource TriggerSource) String() string { - return string(triggerSource) +func (ts TriggerSource) String() string { + return string(ts) } // ClusterId represent the unique id for each cluster with the same TriggerSource. -type ClusterId string +type ClusterID string var ( - ClusterNotSet ClusterId = "" - DefaultCluster ClusterId = "default" + ClusterNotSet ClusterID + DefaultCluster ClusterID = "default" ) // FillInIfNotSet returns new ClusterId with value set to default if it was empty. -func (clusterId ClusterId) FillInIfNotSet() ClusterId { +func (clusterId ClusterID) FillInIfNotSet() ClusterID { if clusterId == ClusterNotSet { return DefaultCluster } return clusterId } -func (clusterId ClusterId) String() string { +func (clusterId ClusterID) String() string { return string(clusterId) } // ClusterKey represents unique key of a metric source. type ClusterKey struct { TriggerSource TriggerSource - ClusterId ClusterId + ClusterID ClusterID } var ( @@ -467,15 +468,15 @@ var ( ) // MakeClusterKey creates new cluster key with given trigger source and cluster id. -func MakeClusterKey(triggerSource TriggerSource, clusterId ClusterId) ClusterKey { +func MakeClusterKey(triggerSource TriggerSource, clusterID ClusterID) ClusterKey { return ClusterKey{ TriggerSource: triggerSource, - ClusterId: clusterId, + ClusterID: clusterID, } } func (clusterKey ClusterKey) String() string { - return fmt.Sprintf("%s.%s", clusterKey.TriggerSource, clusterKey.ClusterId) + return fmt.Sprintf("%s.%s", clusterKey.TriggerSource, clusterKey.ClusterID) } // TriggerCheck represents trigger data with last check data and check timestamp. @@ -656,7 +657,7 @@ func (events NotificationEvents) getLastState() State { return StateNODATA } -// Returns the current state depending on the throttled parameter. +// GetCurrentState Returns the current state depending on the throttled parameter. func (events NotificationEvents) GetCurrentState(throttled bool) State { if throttled { return events.getLastState() @@ -751,7 +752,7 @@ func (event NotificationEvent) GetMetricsValues(settings NotificationEventSettin builder.WriteString(targetName) builder.WriteString(": ") value := strconv.FormatFloat(event.Values[targetName], 'f', -1, 64) - switch settings { + switch settings { //nolint:revive case SIFormatNumbers: if event.Values[targetName] >= limit { value = humanize.SIWithDigits(event.Values[targetName], 3, "") diff --git a/expression/expression.go b/expression/expression.go index c60e9f797..57881ea92 100644 --- a/expression/expression.go +++ b/expression/expression.go @@ -44,7 +44,7 @@ type TriggerExpression struct { } // Get realizing govaluate.Parameters interface used in evaluable expression. -func (triggerExpression TriggerExpression) Get(name string) (interface{}, error) { +func (triggerExpression TriggerExpression) Get(name string) (any, error) { name = strings.ToLower(name) switch name { diff --git a/filter/series_by_tag.go b/filter/series_by_tag.go index 90b522964..c2a58523f 100644 --- a/filter/series_by_tag.go +++ b/filter/series_by_tag.go @@ -219,7 +219,7 @@ func handleRegexMatch( // We don't need to create a regular for the asterisk, because in such a tag // it is the fact of the tag's presence that matters, not its value. if spec.Value == "*" || spec.Value == ".*" { - return func(value string) bool { + return func(_ string) bool { return isMatchOperator }, nil } diff --git a/helpers.go b/helpers.go index c0432ca21..95691c074 100644 --- a/helpers.go +++ b/helpers.go @@ -174,7 +174,7 @@ func GetTriggerListsDiff(triggerLists ...[]*Trigger) []*Trigger { // ChunkSlice gets slice of strings and chunks it to a given size. It returns a batch of chunked lists. func ChunkSlice(original []string, chunkSize int) (divided [][]string) { if chunkSize < 1 { - return + return nil } for i := 0; i < len(original); i += chunkSize { end := i + chunkSize @@ -185,7 +185,7 @@ func ChunkSlice(original []string, chunkSize int) (divided [][]string) { divided = append(divided, original[i:end]) } - return + return divided } func RoundToNearestRetention(ts, retention int64) int64 { diff --git a/image_store/s3/store.go b/image_store/s3/store.go index 9fe0cdd47..ab634f149 100644 --- a/image_store/s3/store.go +++ b/image_store/s3/store.go @@ -25,11 +25,11 @@ func (imageStore *ImageStore) StoreImage(image []byte) (string, error) { } func (imageStore *ImageStore) buildUploadInput(image []byte) (*s3manager.UploadInput, error) { - uuid, err := uuid.NewV4() + plotUUID, err := uuid.NewV4() if err != nil { - return nil, fmt.Errorf("failed to generate uuid: %w", err) + return nil, fmt.Errorf("failed to generate plotUUID: %w", err) } - key := "moira-plots/" + uuid.String() + key := "moira-plots/" + plotUUID.String() return &s3manager.UploadInput{ Bucket: aws.String(imageStore.bucket), Key: aws.String(key), diff --git a/index/batch.go b/index/batch.go index 1fbdc3502..6218b82c8 100644 --- a/index/batch.go +++ b/index/batch.go @@ -14,10 +14,11 @@ func (index *Index) writeByBatches(triggerIDs []string, batchSize int) error { return index.handleTriggerBatches(triggerChecksChan, errorsChan, len(triggerIDs)) } -func (index *Index) getTriggerChecksBatches(triggerIDsBatches [][]string) (triggerChecksChan chan []*moira.TriggerCheck, errors chan error) { +func (index *Index) getTriggerChecksBatches(triggerIDsBatches [][]string) (chan []*moira.TriggerCheck, chan error) { wg := sync.WaitGroup{} - triggerChecksChan = make(chan []*moira.TriggerCheck) - errors = make(chan error) + triggerChecksChan := make(chan []*moira.TriggerCheck, len(triggerIDsBatches)) + errors := make(chan error, len(triggerIDsBatches)) + for _, triggerIDsBatch := range triggerIDsBatches { wg.Add(1) go func(batch []string) { @@ -36,12 +37,14 @@ func (index *Index) getTriggerChecksBatches(triggerIDsBatches [][]string) (trigg triggerChecksChan <- newBatch }(triggerIDsBatch) } + go func() { wg.Wait() close(triggerChecksChan) close(errors) }() - return + + return triggerChecksChan, errors } func (index *Index) getTriggerChecksWithRetries(batch []string) ([]*moira.TriggerCheck, error) { diff --git a/index/bleve/trigger_index.go b/index/bleve/trigger_index.go index 1300c440c..d8edd73f5 100644 --- a/index/bleve/trigger_index.go +++ b/index/bleve/trigger_index.go @@ -13,7 +13,7 @@ type TriggerIndex struct { // CreateTriggerIndex returns TriggerIndex by provided mapping. func CreateTriggerIndex(mapping mapping.IndexMapping) (*TriggerIndex, error) { - bleveIdx, err := bleve.NewUsing("", mapping, scorch.Name, scorch.Name, map[string]interface{}{}) + bleveIdx, err := bleve.NewUsing("", mapping, scorch.Name, scorch.Name, map[string]any{}) if err != nil { return nil, err } diff --git a/index/fixtures/fixtures.go b/index/fixtures/fixtures.go index 0b68b0b40..2227ccb81 100644 --- a/index/fixtures/fixtures.go +++ b/index/fixtures/fixtures.go @@ -85,7 +85,7 @@ var IndexedTriggerTestCases = fixtureIndexedTriggers{ }, triggerTags: []string{"DND-generator", "common"}, triggerCreatedBy: "test", - triggerScore: 30, //nolint + triggerScore: 30, }, { triggerID: "SuperTrigger2", diff --git a/integration_tests/notifier/notifier_test.go b/integration_tests/notifier/notifier_test.go index e8f9a814b..1e5ece102 100644 --- a/integration_tests/notifier/notifier_test.go +++ b/integration_tests/notifier/notifier_test.go @@ -43,7 +43,7 @@ var notifierConfig = notifier.Config{ var shutdown = make(chan struct{}) var ( - notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") + notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) logger, _ = logging.GetLogger("Notifier_Test") mockCtrl *gomock.Controller ) @@ -68,7 +68,7 @@ var trigger = moira.Trigger{ Targets: []string{"test.target.1"}, Tags: []string{"test-tag-1"}, TriggerSource: moira.GraphiteLocal, - ClusterId: moira.DefaultCluster, + ClusterID: moira.DefaultCluster, } var triggerData = moira.TriggerData{ @@ -141,7 +141,7 @@ func TestNotifier(t *testing.T) { sender.EXPECT(). SendEvents(gomock.Any(), contact, triggerData, gomock.Any(), false). Return(nil). - Do(func(arg0, arg1, arg2, arg3, arg4 interface{}) { + Do(func(_, _, _, _, _ interface{}) { fmt.Print("SendEvents called. End test") close(shutdown) }) diff --git a/interfaces.go b/interfaces.go index bd3ba84a9..5b0a4e8b1 100644 --- a/interfaces.go +++ b/interfaces.go @@ -87,7 +87,7 @@ type Database interface { // ScheduledNotification storing GetNotifications(start, end int64) ([]*ScheduledNotification, int64, error) - GetNotificationsByContactIdWithLimit(contactID string, from int64, to int64) ([]*NotificationEventHistoryItem, error) + GetNotificationsByContactIDWithLimit(contactID string, from int64, to int64) ([]*NotificationEventHistoryItem, error) RemoveNotification(notificationKey string) (int64, error) RemoveAllNotifications() error FetchNotifications(to int64, limit int64) ([]*ScheduledNotification, error) @@ -159,7 +159,7 @@ type Database interface { // Lock implements lock abstraction. type Lock interface { - Acquire(stop <-chan struct{}) (lost <-chan struct{}, error error) + Acquire(stop <-chan struct{}) (lost <-chan struct{}, err error) Release() } @@ -182,7 +182,7 @@ type Logger interface { String(key, value string) Logger Int(key string, value int) Logger Int64(key string, value int64) Logger - Fields(fields map[string]interface{}) Logger + Fields(fields map[string]any) Logger // Get child logger with the minimum accepted level Level(string) (Logger, error) @@ -194,7 +194,7 @@ type Logger interface { type Sender interface { // TODO refactor: https://github.com/moira-alert/moira/issues/794 SendEvents(events NotificationEvents, contact ContactData, trigger TriggerData, plot [][]byte, throttled bool) error - Init(senderSettings interface{}, logger Logger, location *time.Location, dateTimeFormat string) error + Init(senderSettings any, logger Logger, location *time.Location, dateTimeFormat string) error } // ImageStore is the interface for image storage providers. diff --git a/logging/interfaces.go b/logging/interfaces.go index a1ad6cfb5..cb8d0bec1 100644 --- a/logging/interfaces.go +++ b/logging/interfaces.go @@ -6,8 +6,8 @@ type EventBuilder interface { Error(err error) EventBuilder Int(key string, value int) EventBuilder Int64(key string, value int64) EventBuilder - Interface(key string, value interface{}) EventBuilder - Fields(fields map[string]interface{}) EventBuilder + Interface(key string, value any) EventBuilder + Fields(fields map[string]any) EventBuilder // Msg must be called after all tags were set Msg(message string) diff --git a/logging/zerolog_adapter/event_builder.go b/logging/zerolog_adapter/event_builder.go index 62433042d..efeb60cd1 100644 --- a/logging/zerolog_adapter/event_builder.go +++ b/logging/zerolog_adapter/event_builder.go @@ -43,14 +43,14 @@ func (e EventBuilder) Int64(key string, value int64) logging.EventBuilder { return e } -func (e EventBuilder) Interface(key string, value interface{}) logging.EventBuilder { +func (e EventBuilder) Interface(key string, value any) logging.EventBuilder { if e.event != nil { e.event.Interface(key, value) } return e } -func (e EventBuilder) Fields(fields map[string]interface{}) logging.EventBuilder { +func (e EventBuilder) Fields(fields map[string]any) logging.EventBuilder { if e.event != nil { e.event.Fields(fields) } diff --git a/logging/zerolog_adapter/logger.go b/logging/zerolog_adapter/logger.go index fc3b446fd..bbe50888e 100644 --- a/logging/zerolog_adapter/logger.go +++ b/logging/zerolog_adapter/logger.go @@ -62,10 +62,10 @@ func getLogWriter(logFileName string) (io.Writer, error) { } logDir := filepath.Dir(logFileName) - if err := os.MkdirAll(logDir, 0o755); err != nil { //nolint:gofumpt,gomnd + if err := os.MkdirAll(logDir, 0o755); err != nil { //nolint:gofumpt return nil, fmt.Errorf("can't create log directories %s: %s", logDir, err.Error()) } - logFile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) //nolint:gofumpt,gomnd + logFile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o644) //nolint:gofumpt if err != nil { return nil, fmt.Errorf("can't open log file %s: %s", logFileName, err.Error()) } @@ -107,7 +107,7 @@ func (l *Logger) Int64(key string, value int64) moira.Logger { return l } -func (l *Logger) Fields(fields map[string]interface{}) moira.Logger { +func (l *Logger) Fields(fields map[string]any) moira.Logger { l.logger = l.logger.With().Fields(fields).Logger() return l } diff --git a/metric_source/local/errors.go b/metric_source/local/errors.go index b9605024f..71e569fa5 100644 --- a/metric_source/local/errors.go +++ b/metric_source/local/errors.go @@ -34,7 +34,7 @@ func (err ErrUnknownFunction) Error() string { // isErrUnknownFunction checks error for carbonapi.errUnknownFunction. func isErrUnknownFunction(err error) bool { - switch merry.Unwrap(err).(type) { // nolint:errorlint + switch merry.Unwrap(err).(type) { // nolint:errorlint,revive case helper.ErrUnknownFunction: return true } @@ -66,7 +66,7 @@ func (err ErrEvalExpr) Error() string { // ErrEvaluateTargetFailedWithPanic used to identify occurred error as a result of recover from panic. type ErrEvaluateTargetFailedWithPanic struct { target string - recoverMessage interface{} + recoverMessage any stackRecord []byte } diff --git a/metric_source/local/local_test.go b/metric_source/local/local_test.go index 6f0feb8a9..35f4ed5a8 100644 --- a/metric_source/local/local_test.go +++ b/metric_source/local/local_test.go @@ -310,7 +310,7 @@ func TestLocalSourceFetch(t *testing.T) { }) Convey("Test enormous fetch interval", t, func() { - var fromPast int64 = 0 + var fromPast int64 var toFuture int64 = 1e15 ttl := 2*retention - 1 diff --git a/metric_source/prometheus/convert_test.go b/metric_source/prometheus/convert_test.go index 565fac521..cf79c2bc4 100644 --- a/metric_source/prometheus/convert_test.go +++ b/metric_source/prometheus/convert_test.go @@ -17,11 +17,12 @@ func MakeSamplePair(time time.Time, value float64) model.SamplePair { } func TestConvertToFetchResult(t *testing.T) { - metric_1 := model.Metric{ + metric1 := model.Metric{ "__name__": "name", "label_1": "value_1", } - metric_2 := model.Metric{ + + metric2 := model.Metric{ "__name__": "name", "label_1": "value_2", } @@ -44,7 +45,7 @@ func TestConvertToFetchResult(t *testing.T) { now := time.Now() mat := model.Matrix{&model.SampleStream{ - Metric: metric_1, + Metric: metric1, Values: []model.SamplePair{}, }} @@ -70,7 +71,7 @@ func TestConvertToFetchResult(t *testing.T) { now := time.Now() mat := model.Matrix{&model.SampleStream{ - Metric: metric_1, + Metric: metric1, Values: []model.SamplePair{MakeSamplePair(now, 1.0)}, }} @@ -96,7 +97,7 @@ func TestConvertToFetchResult(t *testing.T) { now := time.Now() mat := model.Matrix{&model.SampleStream{ - Metric: metric_1, + Metric: metric1, Values: []model.SamplePair{ MakeSamplePair(now, 1.0), MakeSamplePair(now.Add(60*time.Second), 2.0), @@ -128,14 +129,14 @@ func TestConvertToFetchResult(t *testing.T) { mat := model.Matrix{ &model.SampleStream{ - Metric: metric_1, + Metric: metric1, Values: []model.SamplePair{ MakeSamplePair(now, 1.0), MakeSamplePair(now.Add(60*time.Second), 2.0), }, }, &model.SampleStream{ - Metric: metric_2, + Metric: metric2, Values: []model.SamplePair{ MakeSamplePair(now, 3.0), MakeSamplePair(now.Add(60*time.Second), 4.0), diff --git a/metric_source/prometheus/prometheus.go b/metric_source/prometheus/prometheus.go index d554c68db..b8c6c233f 100644 --- a/metric_source/prometheus/prometheus.go +++ b/metric_source/prometheus/prometheus.go @@ -24,12 +24,12 @@ type Config struct { } func Create(config *Config, logger moira.Logger) (metricSource.MetricSource, error) { - promApi, err := createPrometheusApi(config) + promAPI, err := createPrometheusAPI(config) if err != nil { return nil, err } - return &Prometheus{config: config, api: promApi, logger: logger}, nil + return &Prometheus{config: config, api: promAPI, logger: logger}, nil } type Prometheus struct { diff --git a/metric_source/prometheus/prometheus_api.go b/metric_source/prometheus/prometheus_api.go index 70bdeeb11..4662b6877 100644 --- a/metric_source/prometheus/prometheus_api.go +++ b/metric_source/prometheus/prometheus_api.go @@ -15,7 +15,7 @@ type PrometheusApi interface { QueryRange(ctx context.Context, query string, r promApi.Range, opts ...promApi.Option) (model.Value, promApi.Warnings, error) } -func createPrometheusApi(config *Config) (promApi.API, error) { +func createPrometheusAPI(config *Config) (promApi.API, error) { roundTripper := api.DefaultRoundTripper if config.User != "" && config.Password != "" { diff --git a/metric_source/remote/remote.go b/metric_source/remote/remote.go index 853a96240..8b2ebf614 100644 --- a/metric_source/remote/remote.go +++ b/metric_source/remote/remote.go @@ -81,7 +81,7 @@ func (remote *Remote) IsConfigured() (bool, error) { return true, nil } -// IsRemoteAvailable checks if graphite API is available and returns 200 response. +// IsAvailable checks if remote API is available and returns 200 response. func (remote *Remote) IsAvailable() (bool, error) { maxRetries := 3 until := time.Now().Unix() diff --git a/metrics/checker.go b/metrics/checker.go index dbbee2b5e..c4da00eaa 100644 --- a/metrics/checker.go +++ b/metrics/checker.go @@ -51,7 +51,7 @@ func ConfigureCheckerMetrics(registry Registry, sources []moira.ClusterKey) *Che } func configureCheckMetrics(registry Registry, clusterKey moira.ClusterKey) *CheckMetrics { - source, id := clusterKey.TriggerSource.String(), clusterKey.ClusterId.String() + source, id := clusterKey.TriggerSource.String(), clusterKey.ClusterID.String() return &CheckMetrics{ CheckError: registry.NewMeter(source, id, "errors", "check"), HandleError: registry.NewMeter(source, id, "errors", "handle"), diff --git a/metrics/notifier.go b/metrics/notifier.go index 8711ef11c..b2a908e5d 100644 --- a/metrics/notifier.go +++ b/metrics/notifier.go @@ -19,7 +19,7 @@ type NotifierMetrics struct { } // ConfigureNotifierMetrics is notifier metrics configurator. -func ConfigureNotifierMetrics(registry Registry, prefix string) *NotifierMetrics { +func ConfigureNotifierMetrics(registry Registry) *NotifierMetrics { return &NotifierMetrics{ SubsMalformed: registry.NewMeter("subs", "malformed"), EventsReceived: registry.NewMeter("events", "received"), diff --git a/metrics/triggers.go b/metrics/triggers.go index bf784fbd6..b31132762 100644 --- a/metrics/triggers.go +++ b/metrics/triggers.go @@ -13,7 +13,7 @@ type TriggersMetrics struct { func NewTriggersMetrics(registry Registry, clusterKeys []moira.ClusterKey) *TriggersMetrics { meters := make(map[moira.ClusterKey]Meter, len(clusterKeys)) for _, key := range clusterKeys { - meters[key] = registry.NewMeter("triggers", key.TriggerSource.String(), key.ClusterId.String()) + meters[key] = registry.NewMeter("triggers", key.TriggerSource.String(), key.ClusterID.String()) } return &TriggersMetrics{ diff --git a/mock/moira-alert/database.go b/mock/moira-alert/database.go index b0687cb78..74293f55a 100644 --- a/mock/moira-alert/database.go +++ b/mock/moira-alert/database.go @@ -506,19 +506,19 @@ func (mr *MockDatabaseMockRecorder) GetNotifications(arg0, arg1 any) *gomock.Cal return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotifications", reflect.TypeOf((*MockDatabase)(nil).GetNotifications), arg0, arg1) } -// GetNotificationsByContactIdWithLimit mocks base method. -func (m *MockDatabase) GetNotificationsByContactIdWithLimit(arg0 string, arg1, arg2 int64) ([]*moira.NotificationEventHistoryItem, error) { +// GetNotificationsByContactIDWithLimit mocks base method. +func (m *MockDatabase) GetNotificationsByContactIDWithLimit(arg0 string, arg1, arg2 int64) ([]*moira.NotificationEventHistoryItem, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetNotificationsByContactIdWithLimit", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "GetNotificationsByContactIDWithLimit", arg0, arg1, arg2) ret0, _ := ret[0].([]*moira.NotificationEventHistoryItem) ret1, _ := ret[1].(error) return ret0, ret1 } -// GetNotificationsByContactIdWithLimit indicates an expected call of GetNotificationsByContactIdWithLimit. -func (mr *MockDatabaseMockRecorder) GetNotificationsByContactIdWithLimit(arg0, arg1, arg2 any) *gomock.Call { +// GetNotificationsByContactIDWithLimit indicates an expected call of GetNotificationsByContactIDWithLimit. +func (mr *MockDatabaseMockRecorder) GetNotificationsByContactIDWithLimit(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotificationsByContactIdWithLimit", reflect.TypeOf((*MockDatabase)(nil).GetNotificationsByContactIdWithLimit), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetNotificationsByContactIDWithLimit", reflect.TypeOf((*MockDatabase)(nil).GetNotificationsByContactIDWithLimit), arg0, arg1, arg2) } // GetNotifierState mocks base method. diff --git a/mock/scheduler/scheduler.go b/mock/scheduler/scheduler.go index 8a146a314..3274a1760 100644 --- a/mock/scheduler/scheduler.go +++ b/mock/scheduler/scheduler.go @@ -48,7 +48,7 @@ func (m *MockScheduler) ScheduleNotification(arg0 moira.SchedulerParams, arg1 mo } // ScheduleNotification indicates an expected call of ScheduleNotification. -func (mr *MockSchedulerMockRecorder) ScheduleNotification(arg0, arg1 interface{}) *gomock.Call { +func (mr *MockSchedulerMockRecorder) ScheduleNotification(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ScheduleNotification", reflect.TypeOf((*MockScheduler)(nil).ScheduleNotification), arg0, arg1) } diff --git a/notifier/config.go b/notifier/config.go index a89b4b7ec..dda4d42fb 100644 --- a/notifier/config.go +++ b/notifier/config.go @@ -14,7 +14,7 @@ type Config struct { SendingTimeout time.Duration ResendingTimeout time.Duration ReschedulingDelay time.Duration - Senders []map[string]interface{} + Senders []map[string]any LogFile string LogLevel string FrontURL string diff --git a/notifier/events/event_test.go b/notifier/events/event_test.go index 219f03f60..0d22af406 100644 --- a/notifier/events/event_test.go +++ b/notifier/events/event_test.go @@ -18,7 +18,7 @@ import ( "github.com/moira-alert/moira/notifier" ) -var notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") +var notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) func TestEvent(t *testing.T) { mockCtrl := gomock.NewController(t) @@ -707,7 +707,7 @@ func TestGoRoutine(t *testing.T) { dataBase.EXPECT().GetTagsSubscriptions(triggerData.Tags).Times(1).Return([]*moira.SubscriptionData{&subscription}, nil) dataBase.EXPECT().GetContact(contact.ID).Times(1).Return(contact, nil) scheduler.EXPECT().ScheduleNotification(params, gomock.Any()).Times(1).Return(&emptyNotification) - dataBase.EXPECT().AddNotification(&emptyNotification).Times(1).Return(nil).Do(func(f ...interface{}) { close(shutdown) }) + dataBase.EXPECT().AddNotification(&emptyNotification).Times(1).Return(nil).Do(func(_ ...interface{}) { close(shutdown) }) worker.Start() waitTestEnd(shutdown, worker) diff --git a/notifier/notifications/notifications_test.go b/notifier/notifications/notifications_test.go index 2b40438d6..a273cc1a5 100644 --- a/notifier/notifications/notifications_test.go +++ b/notifier/notifications/notifications_test.go @@ -15,7 +15,7 @@ import ( notifier2 "github.com/moira-alert/moira/notifier" ) -var notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") +var notifierMetrics = metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) func TestProcessScheduledEvent(t *testing.T) { subID2 := "subscriptionID-00000000000002" @@ -169,7 +169,7 @@ func TestGoRoutine(t *testing.T) { shutdown := make(chan struct{}) dataBase.EXPECT().FetchNotifications(gomock.Any(), notifier2.NotificationsLimitUnlimited).Return([]*moira.ScheduledNotification{¬ification1}, nil) dataBase.EXPECT().PushContactNotificationToHistory(¬ification1).Return(nil).AnyTimes() - notifier.EXPECT().Send(&pkg, gomock.Any()).Do(func(arg0, arg1 interface{}) { close(shutdown) }) + notifier.EXPECT().Send(&pkg, gomock.Any()).Do(func(_, _ interface{}) { close(shutdown) }) notifier.EXPECT().StopSenders() notifier.EXPECT().GetReadBatchSize().Return(notifier2.NotificationsLimitUnlimited) dataBase.EXPECT().GetNotifierState().Return(moira.SelfStateOK, nil) diff --git a/notifier/notifier.go b/notifier/notifier.go index 6a31134a0..779ab0dcd 100644 --- a/notifier/notifier.go +++ b/notifier/notifier.go @@ -65,7 +65,7 @@ func (pkg NotificationPackage) GetMetricNames() []string { // Notifier implements notification functionality. type Notifier interface { Send(pkg *NotificationPackage, waitGroup *sync.WaitGroup) - RegisterSender(senderSettings map[string]interface{}, sender moira.Sender) error + RegisterSender(senderSettings map[string]any, sender moira.Sender) error StopSenders() GetSenders() map[string]bool GetReadBatchSize() int64 @@ -118,10 +118,8 @@ func (notifier *StandardNotifier) Send(pkg *NotificationPackage, waitGroup *sync select { case ch <- *pkg: - break case <-time.After(notifier.config.SendingTimeout): notifier.reschedule(pkg, fmt.Sprintf("Timeout sending %s", pkg)) - break } }(pkg) } diff --git a/notifier/notifier_test.go b/notifier/notifier_test.go index 4234abc9c..fc43e15f4 100644 --- a/notifier/notifier_test.go +++ b/notifier/notifier_test.go @@ -224,7 +224,7 @@ func TestTimeout(t *testing.T) { } scheduler.EXPECT().ScheduleNotification(params, gomock.Any()).Return(¬ification) - dataBase.EXPECT().AddNotification(¬ification).Return(nil).Do(func(f ...interface{}) { close(shutdown) }) + dataBase.EXPECT().AddNotification(¬ification).Return(nil).Do(func(_ ...interface{}) { close(shutdown) }) standardNotifier.Send(&pkg2, &wg) wg.Wait() @@ -242,7 +242,7 @@ func waitTestEnd() { } func configureNotifier(t *testing.T, config Config) { - notifierMetrics := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") + notifierMetrics := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) mockCtrl = gomock.NewController(t) dataBase = mock_moira_alert.NewMockDatabase(mockCtrl) diff --git a/notifier/registrator.go b/notifier/registrator.go index d1c4bfebb..3a102ca2e 100644 --- a/notifier/registrator.go +++ b/notifier/registrator.go @@ -92,7 +92,7 @@ func (notifier *StandardNotifier) RegisterSenders(connector moira.Database) erro } } if notifier.config.SelfStateEnabled { - selfStateSettings := map[string]interface{}{ + selfStateSettings := map[string]any{ "sender_type": selfStateSender, "contact_type": selfStateSender, } @@ -113,7 +113,7 @@ func (notifier *StandardNotifier) registerMetrics(senderContactType string) { } // RegisterSender adds sender for notification type and registers metrics. -func (notifier *StandardNotifier) RegisterSender(senderSettings map[string]interface{}, sender moira.Sender) error { +func (notifier *StandardNotifier) RegisterSender(senderSettings map[string]any, sender moira.Sender) error { senderType, ok := senderSettings["sender_type"].(string) if !ok { return ErrMissingSenderType diff --git a/notifier/scheduler.go b/notifier/scheduler.go index 0868c7f8a..0dc6f424c 100644 --- a/notifier/scheduler.go +++ b/notifier/scheduler.go @@ -33,7 +33,7 @@ type throttlingLevel struct { } // NewScheduler is initializer for StandardScheduler. -func NewScheduler(database moira.Database, logger moira.Logger, metrics *metrics.NotifierMetrics, config SchedulerConfig, clock moira.Clock, +func NewScheduler(database moira.Database, _ moira.Logger, metrics *metrics.NotifierMetrics, config SchedulerConfig, clock moira.Clock, ) *StandardScheduler { return &StandardScheduler{ database: database, diff --git a/notifier/scheduler_test.go b/notifier/scheduler_test.go index 930955f59..e97b49ddf 100644 --- a/notifier/scheduler_test.go +++ b/notifier/scheduler_test.go @@ -49,7 +49,7 @@ func TestThrottling(t *testing.T) { defer mockCtrl.Finish() dataBase := mock_moira_alert.NewMockDatabase(mockCtrl) logger, _ := logging.GetLogger("Scheduler") - metrics2 := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") + metrics2 := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) now := time.Now() systemClock := mock_clock.NewMockClock(mockCtrl) @@ -159,7 +159,7 @@ func TestSubscriptionSchedule(t *testing.T) { defer mockCtrl.Finish() dataBase := mock_moira_alert.NewMockDatabase(mockCtrl) logger, _ := logging.GetLogger("Scheduler") - notifierMetrics := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry(), "notifier") + notifierMetrics := metrics.ConfigureNotifierMetrics(metrics.NewDummyRegistry()) systemClock := mock_clock.NewMockClock(mockCtrl) scheduler := NewScheduler(dataBase, logger, notifierMetrics, SchedulerConfig{ReschedulingDelay: time.Minute}, systemClock) diff --git a/plotting/curve.go b/plotting/curve.go index 5db9c70bc..d9a9abd1e 100644 --- a/plotting/curve.go +++ b/plotting/curve.go @@ -78,12 +78,12 @@ func resolveFirstPoint(metricData metricSource.MetricData) (int, int64) { start := 0 startTime := metricData.StartTime for _, metricVal := range metricData.Values { - if !moira.IsFiniteNumber(metricVal) { - start++ - startTime += metricData.StepTime - } else { + if moira.IsFiniteNumber(metricVal) { break } + + start++ + startTime += metricData.StepTime } return start, startTime } diff --git a/plotting/helpers.go b/plotting/helpers.go index 8d1674c27..00636b8d2 100644 --- a/plotting/helpers.go +++ b/plotting/helpers.go @@ -29,7 +29,7 @@ func percentsOfRange(min, max, percent float64) float64 { // getTimeValueFormatter returns a time formatter with a given format and timezone. func getTimeValueFormatter(location *time.Location, format string) chart.ValueFormatter { - return func(v interface{}) string { + return func(v any) string { storage := &locationStorage{location: location} return storage.formatTimeWithLocation(v, format) } @@ -42,7 +42,7 @@ type locationStorage struct { } // TimeValueFormatterWithFormat is a ValueFormatter for timestamps with a given format. -func (storage locationStorage) formatTimeWithLocation(v interface{}, dateFormat string) string { +func (storage locationStorage) formatTimeWithLocation(v any, dateFormat string) string { if typed, isTyped := v.(time.Time); isTyped { return typed.In(storage.location).Format(dateFormat) } @@ -57,8 +57,8 @@ func (storage locationStorage) formatTimeWithLocation(v interface{}, dateFormat // getYAxisValuesFormatter returns value formatter // for values on yaxis and resolved maximal formatted value length. -func getYAxisValuesFormatter(limits plotLimits) (func(v interface{}) string, int) { - var formatter func(v interface{}) string +func getYAxisValuesFormatter(limits plotLimits) (func(v any) string, int) { + var formatter func(v any) string deltaLimits := int64(limits.highest) - int64(limits.lowest) if deltaLimits > 10 { //nolint formatter = floatToHumanizedValueFormatter @@ -74,7 +74,7 @@ func getYAxisValuesFormatter(limits plotLimits) (func(v interface{}) string, int } // floatToHumanizedValueFormatter converts floats into humanized strings on y axis of plot. -func floatToHumanizedValueFormatter(v interface{}) string { +func floatToHumanizedValueFormatter(v any) string { if typed, isTyped := v.(float64); isTyped { if math.Abs(typed) < 1000 { //nolint return fmt.Sprintf("%.f", typed) diff --git a/plotting/legend.go b/plotting/legend.go index 5a51f5f30..0204aa282 100644 --- a/plotting/legend.go +++ b/plotting/legend.go @@ -21,7 +21,7 @@ type plotLine struct { // getPlotLegend returns plot legend. func getPlotLegend(c *chart.Chart, legendStyle chart.Style, plotWidth int) chart.Renderable { // TODO: Simplify this method - return func(r chart.Renderer, cb chart.Box, chartDefaults chart.Style) { + return func(r chart.Renderer, _ chart.Box, _ chart.Style) { foundLabels := make(map[string]bool) lines := make([]plotLine, 0, maxLabelsCount) diff --git a/plotting/threshold.go b/plotting/threshold.go index 86b1a1228..1a8eb2bed 100644 --- a/plotting/threshold.go +++ b/plotting/threshold.go @@ -69,30 +69,31 @@ func generateThresholds(trigger *moira.Trigger, limits plotLimits) []*threshold thresholds = append(thresholds, newThreshold( trigger.TriggerType, "WARN", *trigger.WarnValue, limits.highest)) } - /** - // Trigger has ERROR value and threshold can be drawn - errThresholdRequied := trigger.ErrorValue != nil && limits.formsSetContaining(*trigger.ErrorValue) - if errThresholdRequied { - thresholds = append(thresholds, newThreshold( - trigger.TriggerType, "ERROR", *trigger.ErrorValue, limits.highest)) - } - // Trigger has WARN value and threshold can be drawn when: - warnThresholdRequired := trigger.WarnValue != nil && limits.formsSetContaining(*trigger.WarnValue) - if warnThresholdRequired { + + /* + // Trigger has ERROR value and threshold can be drawn + errThresholdRequied := trigger.ErrorValue != nil && limits.formsSetContaining(*trigger.ErrorValue) if errThresholdRequied { - deltaLimits := math.Abs(limits.highest - limits.lowest) - deltaThresholds := math.Abs(*trigger.ErrorValue - *trigger.WarnValue) - if deltaThresholds > thresholdGapCoefficient*deltaLimits { - //// there is enough place to draw both of ERROR and WARN thresholds + thresholds = append(thresholds, newThreshold( + trigger.TriggerType, "ERROR", *trigger.ErrorValue, limits.highest)) + } + // Trigger has WARN value and threshold can be drawn when: + warnThresholdRequired := trigger.WarnValue != nil && limits.formsSetContaining(*trigger.WarnValue) + if warnThresholdRequired { + if errThresholdRequied { + deltaLimits := math.Abs(limits.highest - limits.lowest) + deltaThresholds := math.Abs(*trigger.ErrorValue - *trigger.WarnValue) + if deltaThresholds > thresholdGapCoefficient*deltaLimits { + //// there is enough place to draw both of ERROR and WARN thresholds + thresholds = append(thresholds, newThreshold( + trigger.TriggerType, "WARN", *trigger.WarnValue, limits.highest)) + } + } else { + //// there is no ERROR threshold required thresholds = append(thresholds, newThreshold( trigger.TriggerType, "WARN", *trigger.WarnValue, limits.highest)) } - } else { - //// there is no ERROR threshold required - thresholds = append(thresholds, newThreshold( - trigger.TriggerType, "WARN", *trigger.WarnValue, limits.highest)) } - } */ return thresholds } @@ -111,7 +112,7 @@ func (threshold *threshold) generateThresholdSeries(theme moira.PlotTheme, limit return thresholdSeries } -/** +/* // generateAnnotationSeries returns threshold annotation series. func (threshold *threshold) generateAnnotationSeries(theme moira.PlotTheme, limits plotLimits) chart.AnnotationSeries { annotationSeries := chart.AnnotationSeries{ diff --git a/senders/discord/init.go b/senders/discord/init.go index e991d089f..2be49cd85 100644 --- a/senders/discord/init.go +++ b/senders/discord/init.go @@ -35,7 +35,7 @@ type Sender struct { } // Init reads the yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/discord/init_test.go b/senders/discord/init_test.go index 73c2609af..0350e7566 100644 --- a/senders/discord/init_test.go +++ b/senders/discord/init_test.go @@ -18,7 +18,7 @@ type MockLock struct { moira.Lock } -func (lock *MockLock) Acquire(stop <-chan struct{}) (lost <-chan struct{}, error error) { +func (lock *MockLock) Acquire(stop <-chan struct{}) (lost <-chan struct{}, err error) { return lost, nil } diff --git a/senders/mail/mail.go b/senders/mail/mail.go index 39ce73344..cad193926 100644 --- a/senders/mail/mail.go +++ b/senders/mail/mail.go @@ -44,7 +44,7 @@ type Sender struct { } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, dateTimeFormat string) error { err := sender.fillSettings(senderSettings, logger, location, dateTimeFormat) if err != nil { return err @@ -57,7 +57,7 @@ func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, loca return err } -func (sender *Sender) fillSettings(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) fillSettings(senderSettings any, logger moira.Logger, location *time.Location, dateTimeFormat string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/mail/send.go b/senders/mail/send.go index 821ed3b88..f3796b30e 100644 --- a/senders/mail/send.go +++ b/senders/mail/send.go @@ -115,8 +115,6 @@ func (sender *Sender) dialAndSend(message *gomail.Message) error { if sender.Password != "" { d.Auth = smtp.PlainAuth("", sender.Username, sender.Password, sender.SMTPHost) } - if err := d.DialAndSend(message); err != nil { - return err - } - return nil + + return d.DialAndSend(message) } diff --git a/senders/mail/send_test.go b/senders/mail/send_test.go index 2c1a4895e..d79f76d26 100644 --- a/senders/mail/send_test.go +++ b/senders/mail/send_test.go @@ -9,7 +9,7 @@ import ( "github.com/moira-alert/moira" logging "github.com/moira-alert/moira/logging/zerolog_adapter" - . "github.com/smartystreets/goconvey/convey" + "github.com/smartystreets/goconvey/convey" ) func TestMakeMessage(t *testing.T) { @@ -47,17 +47,17 @@ some other text _italics text_`, logger: logger, } - Convey("Make message", t, func() { + convey.Convey("Make message", t, func() { message := sender.makeMessage(generateTestEvents(10, trigger.ID), contact, trigger, [][]byte{{1, 0, 1}}, true) - So(message.GetHeader("From")[0], ShouldEqual, sender.From) - So(message.GetHeader("To")[0], ShouldEqual, contact.Value) + convey.So(message.GetHeader("From")[0], convey.ShouldEqual, sender.From) + convey.So(message.GetHeader("To")[0], convey.ShouldEqual, contact.Value) messageStr := new(bytes.Buffer) _, err := message.WriteTo(messageStr) - So(err, ShouldBeNil) - So(messageStr.String(), ShouldContainSubstring, "http://localhost/trigger/triggerID-0000000000001") - So(messageStr.String(), ShouldContainSubstring, "italics text") - So(messageStr.String(), ShouldContainSubstring, "bold text") + convey.So(err, convey.ShouldBeNil) + convey.So(messageStr.String(), convey.ShouldContainSubstring, "http://localhost/trigger/triggerID-0000000000001") + convey.So(messageStr.String(), convey.ShouldContainSubstring, "italics text") + convey.So(messageStr.String(), convey.ShouldContainSubstring, "bold text") }) } @@ -105,14 +105,14 @@ func TestEmptyTriggerID(t *testing.T) { logger: logger, } - Convey("Make message", t, func() { + convey.Convey("Make message", t, func() { message := sender.makeMessage(generateTestEvents(10, trigger.ID), contact, trigger, [][]byte{{1, 0, 1}}, true) - So(message.GetHeader("From")[0], ShouldEqual, sender.From) - So(message.GetHeader("To")[0], ShouldEqual, contact.Value) + convey.So(message.GetHeader("From")[0], convey.ShouldEqual, sender.From) + convey.So(message.GetHeader("To")[0], convey.ShouldEqual, contact.Value) messageStr := new(bytes.Buffer) _, err := message.WriteTo(messageStr) - So(err, ShouldBeNil) - So(messageStr.String(), ShouldNotContainSubstring, "http://localhost/trigger/") - So(messageStr.String(), ShouldNotContainSubstring, "
") + convey.So(err, convey.ShouldBeNil) + convey.So(messageStr.String(), convey.ShouldNotContainSubstring, "http://localhost/trigger/") + convey.So(messageStr.String(), convey.ShouldNotContainSubstring, "") }) } diff --git a/senders/mattermost/client.go b/senders/mattermost/client.go index bf16985ac..538e73956 100644 --- a/senders/mattermost/client.go +++ b/senders/mattermost/client.go @@ -10,5 +10,5 @@ import ( type Client interface { SetToken(token string) CreatePost(ctx context.Context, post *model.Post) (*model.Post, *model.Response, error) - UploadFile(ctx context.Context, data []byte, channelId string, filename string) (*model.FileUploadResponse, *model.Response, error) + UploadFile(ctx context.Context, data []byte, channelID string, filename string) (*model.FileUploadResponse, *model.Response, error) } diff --git a/senders/mattermost/sender.go b/senders/mattermost/sender.go index 2a1687214..511e3ab8d 100644 --- a/senders/mattermost/sender.go +++ b/senders/mattermost/sender.go @@ -18,7 +18,7 @@ import ( // Structure that represents the Mattermost configuration in the YAML file. type config struct { - Url string `mapstructure:"url"` + URL string `mapstructure:"url"` InsecureTLS bool `mapstructure:"insecure_tls"` APIToken string `mapstructure:"api_token"` FrontURI string `mapstructure:"front_uri"` @@ -45,18 +45,18 @@ const ( ) // Init configures Sender. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, _ string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { return fmt.Errorf("failed to decode senderSettings to mattermost config: %w", err) } - if cfg.Url == "" { + if cfg.URL == "" { return fmt.Errorf("can not read Mattermost url from config") } - client := model.NewAPIv4Client(cfg.Url) + client := model.NewAPIv4Client(cfg.URL) client.HTTPClient = &http.Client{ Transport: &http.Transport{ diff --git a/senders/msteams/msteams.go b/senders/msteams/msteams.go index 4bfd282f8..da4c862ed 100644 --- a/senders/msteams/msteams.go +++ b/senders/msteams/msteams.go @@ -55,7 +55,7 @@ type Sender struct { } // Init initialises settings required for full functionality. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { @@ -67,13 +67,13 @@ func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, loca sender.frontURI = cfg.FrontURI sender.maxEvents = cfg.MaxEvents sender.client = &http.Client{ - Timeout: time.Duration(30) * time.Second, //nolint + Timeout: time.Duration(30) * time.Second, } return nil } // SendEvents implements Sender interface Send. -func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) error { +func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, _ [][]byte, throttled bool) error { err := sender.isValidWebhookURL(contact.Value) if err != nil { return err diff --git a/senders/opsgenie/init.go b/senders/opsgenie/init.go index 83c205165..8435f7d6a 100644 --- a/senders/opsgenie/init.go +++ b/senders/opsgenie/init.go @@ -31,7 +31,7 @@ type Sender struct { } // Init initializes the opsgenie sender. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) diff --git a/senders/pagerduty/init.go b/senders/pagerduty/init.go index 0e58afc2c..ca315cb33 100644 --- a/senders/pagerduty/init.go +++ b/senders/pagerduty/init.go @@ -26,7 +26,7 @@ type Sender struct { } // Init loads yaml config, configures the pagerduty client. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/pagerduty/send.go b/senders/pagerduty/send.go index b5a971b77..cf6442e23 100644 --- a/senders/pagerduty/send.go +++ b/senders/pagerduty/send.go @@ -27,7 +27,7 @@ func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira. func (sender *Sender) buildEvent(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) pagerduty.V2Event { summary := sender.buildSummary(events, trigger, throttled) - details := make(map[string]interface{}) + details := make(map[string]any) details["Trigger Name"] = trigger.Name triggerURI := trigger.GetTriggerURI(sender.frontURI) diff --git a/senders/pushover/pushover.go b/senders/pushover/pushover.go index d8f0c4b69..50ce4f956 100644 --- a/senders/pushover/pushover.go +++ b/senders/pushover/pushover.go @@ -7,7 +7,7 @@ import ( "github.com/moira-alert/moira" - pushover_client "github.com/gregdel/pushover" + pushoverclient "github.com/gregdel/pushover" "github.com/mitchellh/mapstructure" ) @@ -27,14 +27,14 @@ type config struct { type Sender struct { logger moira.Logger location *time.Location - client *pushover_client.Pushover + client *pushoverclient.Pushover apiToken string frontURI string } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { @@ -45,7 +45,7 @@ func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, loca if sender.apiToken == "" { return fmt.Errorf("can not read pushover api_token from config") } - sender.client = pushover_client.New(sender.apiToken) + sender.client = pushoverclient.New(sender.apiToken) sender.logger = logger sender.frontURI = cfg.FrontURI sender.location = location @@ -61,7 +61,7 @@ func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira. String("message", pushoverMessage.Message). Msg("Calling pushover with message title") - recipient := pushover_client.NewRecipient(contact.Value) + recipient := pushoverclient.NewRecipient(contact.Value) _, err := sender.client.SendMessage(pushoverMessage, recipient) if err != nil { return fmt.Errorf("failed to send %s event message to pushover user %s: %s", trigger.ID, contact.Value, err.Error()) @@ -69,8 +69,8 @@ func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira. return nil } -func (sender *Sender) makePushoverMessage(events moira.NotificationEvents, trigger moira.TriggerData, plots [][]byte, throttled bool) *pushover_client.Message { - pushoverMessage := &pushover_client.Message{ +func (sender *Sender) makePushoverMessage(events moira.NotificationEvents, trigger moira.TriggerData, plots [][]byte, throttled bool) *pushoverclient.Message { + pushoverMessage := &pushoverclient.Message{ Message: sender.buildMessage(events, throttled), Title: sender.buildTitle(events, trigger, throttled), Priority: sender.getMessagePriority(events), @@ -131,13 +131,13 @@ func (sender *Sender) buildTitle(events moira.NotificationEvents, trigger moira. } func (sender *Sender) getMessagePriority(events moira.NotificationEvents) int { - priority := pushover_client.PriorityNormal + priority := pushoverclient.PriorityNormal for _, event := range events { if event.State == moira.StateERROR || event.State == moira.StateEXCEPTION { - priority = pushover_client.PriorityEmergency + priority = pushoverclient.PriorityEmergency } - if priority != pushover_client.PriorityEmergency && (event.State == moira.StateWARN || event.State == moira.StateNODATA) { - priority = pushover_client.PriorityHigh + if priority != pushoverclient.PriorityEmergency && (event.State == moira.StateWARN || event.State == moira.StateNODATA) { + priority = pushoverclient.PriorityHigh } } return priority diff --git a/senders/read_image_store_config.go b/senders/read_image_store_config.go index 512256de5..0f7cd331c 100644 --- a/senders/read_image_store_config.go +++ b/senders/read_image_store_config.go @@ -7,35 +7,31 @@ import ( // ReadImageStoreConfig reads the image store config for a sender // from its settings and confirms whether that image store // is configured. -func ReadImageStoreConfig(senderSettings interface{}, imageStores map[string]moira.ImageStore, logger moira.Logger) (string, moira.ImageStore, bool) { - settings, ok := senderSettings.(map[string]interface{}) +func ReadImageStoreConfig(senderSettings any, imageStores map[string]moira.ImageStore, logger moira.Logger) (string, moira.ImageStore, bool) { + settings, ok := senderSettings.(map[string]any) if !ok { - logger.Warning().Msg("Failed conversion of senderSettings type to map[string]interface{}") + logger.Warning().Msg("Failed conversion of senderSettings type to map[string]any") return "", nil, false } - IimageStoreID, ok := settings["image_store"] + imageStoreID, ok := settings["image_store"] if !ok { logger.Warning().Msg("Cannot read image_store from the config, will not be able to attach plot images to alerts") return "", nil, false } - imageStoreID, ok := IimageStoreID.(string) + imageStoreIDStr, ok := imageStoreID.(string) if !ok { logger.Warning().Msg("Failed to retrieve image_store from sender settings") return "", nil, false } - imageStore, ok := imageStores[imageStoreID] - imageStoreConfigured := false + imageStore, ok := imageStores[imageStoreIDStr] if ok && imageStore.IsEnabled() { - imageStoreConfigured = true - } else { - logger.Warning(). - String("image_store_id", imageStoreID). - Msg("Image store specified has not been configured") - return "", nil, false + return imageStoreIDStr, imageStore, true } - - return imageStoreID, imageStore, imageStoreConfigured + logger.Warning(). + String("image_store_id", imageStoreIDStr). + Msg("Image store specified has not been configured") + return "", nil, false } diff --git a/senders/script/script.go b/senders/script/script.go index c78e37dde..1aeb330c7 100644 --- a/senders/script/script.go +++ b/senders/script/script.go @@ -33,7 +33,7 @@ type scriptNotification struct { } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, _ *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { @@ -52,7 +52,7 @@ func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, loca } // SendEvents implements Sender interface Send. -func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) error { +func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, _ [][]byte, throttled bool) error { scriptFile, args, scriptBody, err := sender.buildCommandData(events, contact, trigger, throttled) if err != nil { return err diff --git a/senders/selfstate/selfstate.go b/senders/selfstate/selfstate.go index 4e69197dd..a1bbbf0da 100644 --- a/senders/selfstate/selfstate.go +++ b/senders/selfstate/selfstate.go @@ -14,13 +14,13 @@ type Sender struct { } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(_ any, logger moira.Logger, _ *time.Location, _ string) error { sender.logger = logger return nil } // SendEvents implements Sender interface Send. -func (sender *Sender) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) error { +func (sender *Sender) SendEvents(events moira.NotificationEvents, _ moira.ContactData, trigger moira.TriggerData, _ [][]byte, throttled bool) error { selfState, err := sender.Database.GetNotifierState() if err != nil { return fmt.Errorf("failed to get notifier state: %s", err.Error()) diff --git a/senders/slack/slack.go b/senders/slack/slack.go index b5c4f7aac..d6fe50f27 100644 --- a/senders/slack/slack.go +++ b/senders/slack/slack.go @@ -12,7 +12,7 @@ import ( "github.com/moira-alert/moira/senders" "github.com/moira-alert/moira/senders/emoji_provider" - slack_client "github.com/slack-go/slack" + slackclient "github.com/slack-go/slack" ) const ( @@ -41,11 +41,11 @@ type Sender struct { emojiProvider emoji_provider.StateEmojiGetter logger moira.Logger location *time.Location - client *slack_client.Client + client *slackclient.Client } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { @@ -64,7 +64,7 @@ func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, loca sender.logger = logger sender.frontURI = cfg.FrontURI sender.location = location - sender.client = slack_client.New(cfg.APIToken) + sender.client = slackclient.New(cfg.APIToken) return nil } @@ -198,8 +198,12 @@ func (sender *Sender) buildEventsString(events moira.NotificationEvents, charsFo return eventsString } -func (sender *Sender) sendMessage(message string, contact string, triggerID string, useDirectMessaging bool, emoji string) (string, string, error) { - params := slack_client.PostMessageParameters{ +func (sender *Sender) sendMessage( + message, contact, triggerID string, + useDirectMessaging bool, + emoji string, +) (string, string, error) { + params := slackclient.PostMessageParameters{ Username: "Moira", AsUser: useDirectMessaging, IconEmoji: emoji, @@ -210,7 +214,7 @@ func (sender *Sender) sendMessage(message string, contact string, triggerID stri String("message", message). Msg("Calling slack") - channelID, threadTimestamp, err := sender.client.PostMessage(contact, slack_client.MsgOptionText(message, false), slack_client.MsgOptionPostMessageParameters(params)) + channelID, threadTimestamp, err := sender.client.PostMessage(contact, slackclient.MsgOptionText(message, false), slackclient.MsgOptionPostMessageParameters(params)) if err != nil { errorText := err.Error() if errorText == ErrorTextChannelArchived || errorText == ErrorTextNotInChannel || @@ -227,7 +231,7 @@ func (sender *Sender) sendPlots(plots [][]byte, channelID, threadTimestamp, trig filename := fmt.Sprintf("%s.png", triggerID) for _, plot := range plots { reader := bytes.NewReader(plot) - uploadParameters := slack_client.UploadFileV2Parameters{ + uploadParameters := slackclient.UploadFileV2Parameters{ FileSize: len(plot), Reader: reader, Title: filename, diff --git a/senders/telegram/init.go b/senders/telegram/init.go index 5982a0016..1ac129ee4 100644 --- a/senders/telegram/init.go +++ b/senders/telegram/init.go @@ -40,12 +40,12 @@ type config struct { // Bot is abstraction over gopkg.in/telebot.v3#Bot. type Bot interface { - Handle(endpoint interface{}, h telebot.HandlerFunc, m ...telebot.MiddlewareFunc) + Handle(endpoint any, h telebot.HandlerFunc, m ...telebot.MiddlewareFunc) Start() Stop() - Send(to telebot.Recipient, what interface{}, opts ...interface{}) (*telebot.Message, error) - SendAlbum(to telebot.Recipient, a telebot.Album, opts ...interface{}) ([]telebot.Message, error) - Reply(to *telebot.Message, what interface{}, opts ...interface{}) (*telebot.Message, error) + Send(to telebot.Recipient, what any, opts ...any) (*telebot.Message, error) + SendAlbum(to telebot.Recipient, a telebot.Album, opts ...any) ([]telebot.Message, error) + Reply(to *telebot.Message, what any, opts ...any) (*telebot.Message, error) ChatByUsername(name string) (*telebot.Chat, error) } @@ -67,7 +67,7 @@ func (sender *Sender) removeTokenFromError(err error) error { } // Init loads yaml config, configures and starts telegram bot. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/twilio/sms.go b/senders/twilio/sms.go index b3badc53c..549b496f0 100644 --- a/senders/twilio/sms.go +++ b/senders/twilio/sms.go @@ -14,7 +14,7 @@ type twilioSenderSms struct { twilioSender } -func (sender *twilioSenderSms) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) error { +func (sender *twilioSenderSms) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, _ [][]byte, throttled bool) error { message := sender.buildMessage(events, trigger, throttled) sender.logger.Debug(). String("phone", contact.Value). diff --git a/senders/twilio/twilio.go b/senders/twilio/twilio.go index d8fc8a77a..74555ad81 100644 --- a/senders/twilio/twilio.go +++ b/senders/twilio/twilio.go @@ -37,7 +37,7 @@ type twilioSender struct { } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/twilio/voice.go b/senders/twilio/voice.go index 357f83f2c..27e1c3598 100644 --- a/senders/twilio/voice.go +++ b/senders/twilio/voice.go @@ -17,7 +17,7 @@ type twilioSenderVoice struct { twimletsEcho bool } -func (sender *twilioSenderVoice) SendEvents(events moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, plots [][]byte, throttled bool) error { +func (sender *twilioSenderVoice) SendEvents(_ moira.NotificationEvents, contact moira.ContactData, trigger moira.TriggerData, _ [][]byte, _ bool) error { voiceURL := sender.buildVoiceURL(trigger) twilioCall, err := twilio_client.NewCall(sender.client, sender.APIFromPhone, contact.Value, twilio_client.Callback(voiceURL)) if err != nil { diff --git a/senders/victorops/init.go b/senders/victorops/init.go index e47e53485..1598300c6 100644 --- a/senders/victorops/init.go +++ b/senders/victorops/init.go @@ -33,7 +33,7 @@ type Sender struct { } // Init loads yaml config, configures the victorops sender. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, location *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/senders/webhook/webhook.go b/senders/webhook/webhook.go index 3812a8799..c34604214 100644 --- a/senders/webhook/webhook.go +++ b/senders/webhook/webhook.go @@ -35,7 +35,7 @@ type Sender struct { } // Init read yaml config. -func (sender *Sender) Init(senderSettings interface{}, logger moira.Logger, location *time.Location, dateTimeFormat string) error { +func (sender *Sender) Init(senderSettings any, logger moira.Logger, _ *time.Location, _ string) error { var cfg config err := mapstructure.Decode(senderSettings, &cfg) if err != nil { diff --git a/templating/templating.go b/templating/templating.go index d59c88177..efbe866c6 100644 --- a/templating/templating.go +++ b/templating/templating.go @@ -245,13 +245,13 @@ func populate(tmpl string, data any) (populatedTemplate string, err error) { buffer := bytes.Buffer{} - template := template.New("populate-template").Funcs(sprigFuncMap).Funcs(funcMap) + templateFunc := template.New("populate-templateFunc").Funcs(sprigFuncMap).Funcs(funcMap) - if template, err = template.Parse(tmpl); err != nil { + if templateFunc, err = templateFunc.Parse(tmpl); err != nil { return tmpl, err } - if err = template.Execute(&buffer, data); err != nil { + if err = templateFunc.Execute(&buffer, data); err != nil { return tmpl, err } diff --git a/worker/worker.go b/worker/worker.go index 85786ca44..b6d2ea10d 100644 --- a/worker/worker.go +++ b/worker/worker.go @@ -39,7 +39,8 @@ func (worker *Worker) Run(stop <-chan struct{}) { Msg("Worker tries to acquire the lock...") lost, err := worker.lock.Acquire(stop) if err != nil { - switch err { // nolint:errorlint + // nolint:errorlint + switch err { case database.ErrLockAcquireInterrupted: return default: