Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade version and add new linters #1000

Merged
merged 2 commits into from
Mar 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,5 @@ jobs:
- name: Run linter
uses: golangci/golangci-lint-action@v3
with:
version: v1.55.2
only-new-issues: true
version: v1.56.2

11 changes: 10 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,20 @@ linters:
- dogsled
- errcheck
- errorlint
- exportloopref
- goconst
- gocheckcompilerdirectives
- gocyclo
- goconst
- godot
- gofmt
- gofumpt
- goheader
- goimports
- gomnd
- gosimple
- govet
- grouper
- ineffassign
- loggercheck
- makezero
Expand All @@ -53,16 +60,18 @@ linters:
- unparam
- unused
- whitespace
- godot

issues:
exclude-rules:
- path: _test\.go
linters:
- gomnd
- errcheck
- goconst

run:
timeout: 5m
skip-files:
- notifier/registrator.go
skip-dirs:
- vendor
3 changes: 1 addition & 2 deletions api/controller/contact_events.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,11 @@ import (

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))
}

var eventsList = dto.ContactEventItemList{
eventsList := dto.ContactEventItemList{
List: make([]dto.ContactEventItem, 0),
}
for _, i := range events {
Expand Down
2 changes: 0 additions & 2 deletions api/controller/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ func CreateTeam(dataBase moira.Database, team dto.TeamModel, userID string) (dto
// GetTeam is a controller function that returns a team by it's ID.
func GetTeam(dataBase moira.Database, teamID string) (dto.TeamModel, *api.ErrorResponse) {
team, err := dataBase.GetTeam(teamID)

if err != nil {
if errors.Is(err, database.ErrNil) {
return dto.TeamModel{}, api.ErrorNotFound(fmt.Sprintf("cannot find team: %s", teamID))
Expand Down Expand Up @@ -106,7 +105,6 @@ func GetUserTeams(dataBase moira.Database, userID string) (dto.UserTeams, *api.E
// GetTeamUsers is a controller function that returns a users of team by team ID.
func GetTeamUsers(dataBase moira.Database, teamID string) (dto.TeamMembers, *api.ErrorResponse) {
users, err := dataBase.GetTeamUsers(teamID)

if err != nil {
if errors.Is(err, database.ErrNil) {
return dto.TeamMembers{}, api.ErrorNotFound(fmt.Sprintf("cannot find team users: %s", teamID))
Expand Down
1 change: 0 additions & 1 deletion api/dto/target.go
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,6 @@ func funcIsSupported(funcName string) bool {
// checks if a seriesByTag expression has at least one argument with a strict equality.
func validateSeriesByTag(target string) (bool, error) {
tagArgs, err := filter.ParseSeriesByTag(target)

if err != nil {
return false, err
}
Expand Down
12 changes: 8 additions & 4 deletions api/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,15 @@ import (
_ "github.com/moira-alert/moira/docs" // docs is generated by Swag CLI, you have to import it.
)

var database moira.Database
var searchIndex moira.Searcher
var (
database moira.Database
searchIndex moira.Searcher
)

const contactKey moiramiddle.ContextKey = "contact"
const subscriptionKey moiramiddle.ContextKey = "subscription"
const (
contactKey moiramiddle.ContextKey = "contact"
subscriptionKey moiramiddle.ContextKey = "subscription"
)

// NewHandler creates new api handler request uris based on github.com/go-chi/chi.
func NewHandler(
Expand Down
2 changes: 0 additions & 2 deletions api/handler/trigger.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ func updateTrigger(writer http.ResponseWriter, request *http.Request) {
var problems []dto.TreeOfProblems
if needValidate(request) {
problems, err = validateTargets(request, trigger)

if err != nil {
render.Render(writer, request, err) //nolint
return
Expand Down Expand Up @@ -101,7 +100,6 @@ func validateTargets(request *http.Request, trigger *dto.Trigger) ([]dto.TreeOfP
}

treesOfProblems, err := dto.TargetVerification(trigger.Targets, ttl, trigger.TriggerSource)

if err != nil {
return nil, api.ErrorInvalidRequest(err)
}
Expand Down
1 change: 0 additions & 1 deletion api/handler/triggers.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,6 @@ func triggerCheck(writer http.ResponseWriter, request *http.Request) {
if len(trigger.Targets) > 0 {
var err error
response.Targets, err = dto.TargetVerification(trigger.Targets, ttl, trigger.TriggerSource)

if err != nil {
render.Render(writer, request, api.ErrorInvalidRequest(err)) //nolint
return
Expand Down
2 changes: 1 addition & 1 deletion api/middleware/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func RequestLogger(logger moira.Logger) func(next http.Handler) http.Handler {

func getErrorResponseIfItHas(writer http.ResponseWriter) *api.ErrorResponse {
writerWithBody := writer.(*responseWriterWithBody)
var errResp = &api.ErrorResponse{}
errResp := &api.ErrorResponse{}
if err := json.NewDecoder(&writerWithBody.body).Decode(errResp); err != nil {
return &api.ErrorResponse{
HTTPStatusCode: http.StatusInternalServerError,
Expand Down
9 changes: 6 additions & 3 deletions checker/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,8 @@ func TestTriggerChecker_PrepareMetrics(t *testing.T) {
"first": {Values: map[string]float64{"t1": 0}},
"second": {Values: map[string]float64{"t1": 0}},
"third": {Values: map[string]float64{"t1": 0}},
}}
},
}
Convey("last check has aloneMetrics", func() {
triggerChecker.trigger.AloneMetrics = map[string]bool{"t2": true}
triggerChecker.lastCheck = &moira.CheckData{
Expand All @@ -227,7 +228,8 @@ func TestTriggerChecker_PrepareMetrics(t *testing.T) {
"first": {Values: map[string]float64{"t1": 0, "t2": 0}},
"second": {Values: map[string]float64{"t1": 0, "t2": 0}},
"third": {Values: map[string]float64{"t1": 0, "t2": 0}},
}}
},
}
Convey("fetched metrics is empty", func() {
triggerChecker.trigger.AloneMetrics = map[string]bool{"t2": true}
prepared, alone, err := triggerChecker.prepareMetrics(map[string][]metricSource.MetricData{})
Expand Down Expand Up @@ -1214,7 +1216,8 @@ func TestHandleTrigger(t *testing.T) {
OldState: moira.StateOK,
Metric: metric,
Values: map[string]float64{},
Message: nil}, true).Return(nil)
Message: nil,
}, true).Return(nil)
aloneMetrics := map[string]metricSource.MetricData{"t1": *metricSource.MakeMetricData(metric, []float64{}, retention, triggerChecker.from)}
lastCheck.MetricsToTargetRelation = conversion.GetRelations(aloneMetrics, triggerChecker.trigger.AloneMetrics)
checkData := newCheckData(&lastCheck, triggerChecker.until)
Expand Down
4 changes: 2 additions & 2 deletions checker/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ func TestTriggerMaintenance(t *testing.T) {

func TestIsStateChanged(t *testing.T) {
Convey("isStateChanged tests", t, func() {
var lastCheckTest = moira.CheckData{
lastCheckTest := moira.CheckData{
Score: 6000,
State: moira.StateOK,
Suppressed: true,
Expand All @@ -655,7 +655,7 @@ func TestIsStateChanged(t *testing.T) {
Maintenance: 1000,
}

var currentCheckTest = moira.CheckData{
currentCheckTest := moira.CheckData{
State: moira.StateWARN,
Timestamp: 1504509981,
}
Expand Down
1 change: 1 addition & 0 deletions checker/metrics/conversion/trigger_metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ func TestTriggerTargetMetrics_Populate(t *testing.T) {
}
})
}

func TestNewTriggerMetricsWithCapacity(t *testing.T) {
Convey("NewTriggerMetricsWithCapacity", t, func() {
capacity := 10
Expand Down
2 changes: 1 addition & 1 deletion checker/trigger_checker.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func MakeTriggerChecker(

triggerLogger := logger.Clone().String(moira.LogFieldNameTriggerID, triggerID)
if logLevel, ok := config.LogTriggersToLevel[triggerID]; ok {
if _, err := triggerLogger.Level(logLevel); err != nil {
if _, err = triggerLogger.Level(logLevel); err != nil {
triggerLogger.Warning().
String("log_level", logLevel).
Msg("Incorrect log level")
Expand Down
1 change: 0 additions & 1 deletion checker/worker/trigger_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ func (manager *WorkerManager) handleTrigger(triggerID string, metrics *metrics.C

func (manager *WorkerManager) handleTriggerInLock(triggerID string, metrics *metrics.CheckMetrics) error {
acquired, err := manager.Database.SetTriggerCheckLock(triggerID)

if err != nil {
return err
}
Expand Down
1 change: 0 additions & 1 deletion cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ func main() {
)

logger, err := logging.ConfigureLog(applicationConfig.Logger.LogFile, applicationConfig.Logger.LogLevel, serviceName, applicationConfig.Logger.LogPrettyFormat)

if err != nil {
fmt.Fprintf(os.Stderr, "Can not configure log: %s\n", err.Error())
os.Exit(1)
Expand Down
22 changes: 12 additions & 10 deletions cmd/cli/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ import (
"github.com/moira-alert/moira/database/redis"
)

var anyTagsSubscriptionsKeyOld = "moira-any-tags-subscriptions"
var anyTagsSubscriptionsKeyNew = "{moira-tag-subscriptions}:moira-any-tags-subscriptions"
var triggersListKeyOld = "moira-triggers-list"
var triggersListKeyNew = "{moira-triggers-list}:moira-triggers-list"
var remoteTriggersListKeyOld = "moira-remote-triggers-list"
var remoteTriggersListKeyNew = "{moira-triggers-list}:moira-remote-triggers-list"
var tagSubscriptionsKeyPrefixOld = "moira-tag-subscriptions:"
var tagSubscriptionsKeyPrefixNew = "{moira-tag-subscriptions}:"
var tagTriggersKeyKeyPrefixOld = "moira-tag-triggers:"
var tagTriggersKeyKeyPrefixNew = "{moira-tag-triggers}:"
var (
anyTagsSubscriptionsKeyOld = "moira-any-tags-subscriptions"
anyTagsSubscriptionsKeyNew = "{moira-tag-subscriptions}:moira-any-tags-subscriptions"
triggersListKeyOld = "moira-triggers-list"
triggersListKeyNew = "{moira-triggers-list}:moira-triggers-list"
remoteTriggersListKeyOld = "moira-remote-triggers-list"
remoteTriggersListKeyNew = "{moira-triggers-list}:moira-remote-triggers-list"
tagSubscriptionsKeyPrefixOld = "moira-tag-subscriptions:"
tagSubscriptionsKeyPrefixNew = "{moira-tag-subscriptions}:"
tagTriggersKeyKeyPrefixOld = "moira-tag-triggers:"
tagTriggersKeyKeyPrefixNew = "{moira-tag-triggers}:"
)

func renameKey(database moira.Database, oldValue, newValue string) error {
switch d := database.(type) {
Expand Down
10 changes: 6 additions & 4 deletions cmd/cli/from_2.9_to_2.10.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,12 @@ func downgradeTo29(logger moira.Logger, database moira.Database) error {
return nil
}

var triggersListKey = "{moira-triggers-list}:moira-triggers-list"
var localTriggersListKey = "{moira-triggers-list}:moira-local-triggers-list"
var remoteTriggersListKey = "{moira-triggers-list}:moira-remote-triggers-list"
var prometheusTriggersListKey = "{moira-triggers-list}:moira-prometheus-triggers-list"
var (
triggersListKey = "{moira-triggers-list}:moira-triggers-list"
localTriggersListKey = "{moira-triggers-list}:moira-local-triggers-list"
remoteTriggersListKey = "{moira-triggers-list}:moira-remote-triggers-list"
prometheusTriggersListKey = "{moira-triggers-list}:moira-prometheus-triggers-list"
)

func createKeyForLocalTriggers(ctx context.Context, logger moira.Logger, database moira.Database) error {
logger.Info().Msg("Start createKeyForLocalTriggers")
Expand Down
10 changes: 3 additions & 7 deletions cmd/cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,9 @@ var (
downgradeToVersion = flag.String("to-version", "", "determines Moira version, TO which need to DOWNGRADE database structures")
)

var (
plotting = flag.Bool("plotting", false, "enable images in all notifications")
)
var plotting = flag.Bool("plotting", false, "enable images in all notifications")

var (
removeSubscriptions = flag.String("remove-subscriptions", "", "Remove given subscriptions separated by semicolons.")
)
var removeSubscriptions = flag.String("remove-subscriptions", "", "Remove given subscriptions separated by semicolons.")

var (
cleanupUsers = flag.Bool("cleanup-users", false, "Disable/delete contacts and subscriptions of missing users")
Expand Down Expand Up @@ -421,7 +417,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, 0666)
file, err := os.OpenFile(filePath, mode, 0666) //nolint:gofumpt
if err != nil {
return nil, fmt.Errorf("cannot open file: %w", err)
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/cli/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,8 @@ func createDefaultData(database moira.Database) error {
}

subscriptions = append(subscriptions,
&moira.SubscriptionData{ID: "subscription_" + contact.ID,
&moira.SubscriptionData{
ID: "subscription_" + contact.ID,
User: contact.User,
Enabled: true,
Tags: []string{"Tag" + contact.User},
Expand Down
8 changes: 5 additions & 3 deletions database/redis/bot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ func TestBotDataStoringErrorConnection(t *testing.T) {
})
}

var messenger1 = "messenger1"
var messenger2 = "messenger2"
var messenger3 = "messenger3"
var (
messenger1 = "messenger1"
messenger2 = "messenger2"
messenger3 = "messenger3"
)
1 change: 0 additions & 1 deletion database/redis/contact.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ func getContactsKeysOnRedisNode(ctx context.Context, client redis.UniversalClien
var keysResult []string
var err error
keysResult, cursor, err = client.Scan(ctx, cursor, contactKey("*"), scanCount).Result()

if err != nil {
return nil, err
}
Expand Down
6 changes: 2 additions & 4 deletions database/redis/contact_notification_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,12 @@ func (connector *DbConnector) GetNotificationsByContactIdWithLimit(contactID str
Max: strconv.FormatInt(to, 10),
Count: int64(connector.notificationHistory.NotificationHistoryQueryLimit),
}).Result()

if err != nil {
return notifications, err
}

for _, notification := range notificationStings {
notificationObj, err := getNotificationStruct(notification)

if err != nil {
return notifications, err
}
Expand Down Expand Up @@ -85,7 +83,8 @@ func (connector *DbConnector) PushContactNotificationToHistory(notification *moi
contactNotificationKey,
&redis.Z{
Score: float64(notification.Timestamp),
Member: notificationBytes})
Member: notificationBytes,
})

pipe.ZRemRangeByScore(
connector.context,
Expand All @@ -95,7 +94,6 @@ func (connector *DbConnector) PushContactNotificationToHistory(notification *moi
)

_, err := pipe.Exec(connector.Context())

if err != nil {
return fmt.Errorf("failed to push contact event history item: %s", err.Error())
}
Expand Down
10 changes: 6 additions & 4 deletions database/redis/contact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ import (
. "github.com/smartystreets/goconvey/convey"
)

const user1 = "user1"
const user2 = "user2"
const team1 = "team1"
const team2 = "team2"
const (
user1 = "user1"
user2 = "user2"
team1 = "team1"
team2 = "team2"
)

func TestContacts(t *testing.T) {
logger, _ := logging.GetLogger("dataBase")
Expand Down
3 changes: 3 additions & 0 deletions database/redis/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ func NewTestDatabaseWithIncorrectConfig(logger moira.Logger) *DbConnector {
}

// Flush deletes all the keys of the DB, use it only for tests.
// nolint:unused
func (connector *DbConnector) Flush() {
err := connector.callFunc(func(connector *DbConnector, client redis.UniversalClient) error {
return client.FlushDB(connector.context).Err()
Expand All @@ -134,11 +135,13 @@ func (connector *DbConnector) Flush() {
}

// Get key ttl, use it only for tests.
// nolint:unused
func (connector *DbConnector) getTTL(key string) time.Duration {
return (*connector.client).PTTL(connector.context, key).Val()
}

// Delete the key, use it only for tests.
// nolint:unused
func (connector *DbConnector) delete(key string) {
(*connector.client).Del(connector.context, key)
}
Expand Down
Loading
Loading