diff --git a/cmd/channel/email/main.go b/cmd/channel/email/main.go index 1f7a7516a..b1b87062a 100644 --- a/cmd/channel/email/main.go +++ b/cmd/channel/email/main.go @@ -34,7 +34,7 @@ func (ch *Email) SendNotification(req *plugin.NotificationRequest) error { } if len(to) == 0 { - return fmt.Errorf("contact user %s doesn't have an e-mail address", req.Contact.FullName) + return fmt.Errorf("contact user %s does not have an e-mail address", req.Contact.FullName) } var msg bytes.Buffer @@ -68,12 +68,12 @@ func (ch *Email) SetConfig(jsonStr json.RawMessage) error { if ch.From == "" { hostname, err := os.Hostname() if err != nil { - return fmt.Errorf("failed to get the os's hostname: %w", err) + return fmt.Errorf("failed to get the OS hostname: %w", err) } usr, err := user.Current() if err != nil { - return fmt.Errorf("failed to get the os's current user: %w", err) + return fmt.Errorf("failed to get the OS current user: %w", err) } ch.From = usr.Username + "@" + hostname diff --git a/cmd/channel/rocketchat/main.go b/cmd/channel/rocketchat/main.go index 3c951bed7..7658d9cac 100644 --- a/cmd/channel/rocketchat/main.go +++ b/cmd/channel/rocketchat/main.go @@ -36,7 +36,7 @@ func (ch *RocketChat) SendNotification(req *plugin.NotificationRequest) error { } if roomId == "" { - return fmt.Errorf("contact user %s doesn't specify a rocketchat channel or username", req.Contact.FullName) + return fmt.Errorf("contact user %s does not specify a rocketchat channel or username", req.Contact.FullName) } message := struct { @@ -64,7 +64,7 @@ func (ch *RocketChat) SendNotification(req *plugin.NotificationRequest) error { client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(request) if err != nil { - return fmt.Errorf("error while sending http request to rocketchat server: %s", err) + return fmt.Errorf("error while sending http request to rocketchat server: %w", err) } defer resp.Body.Close() diff --git a/cmd/icinga-notifications-daemon/main.go b/cmd/icinga-notifications-daemon/main.go index b0f8f438c..e793d68ae 100644 --- a/cmd/icinga-notifications-daemon/main.go +++ b/cmd/icinga-notifications-daemon/main.go @@ -70,13 +70,13 @@ func main() { logger.Infof("Starting Icinga Notifications daemon (%s)", internal.Version.Version) db, err := conf.Database.Open(logs.GetChildLogger("database")) if err != nil { - logger.Fatalw("cannot create database connection from config", zap.Error(err)) + logger.Fatalw("Cannot create database connection from config", zap.Error(err)) } defer db.Close() { logger.Infof("Connecting to database at '%s'", utils.JoinHostPort(conf.Database.Host, conf.Database.Port)) if err := db.Ping(); err != nil { - logger.Fatalw("cannot connect to database", zap.Error(err)) + logger.Fatalw("Cannot connect to database", zap.Error(err)) } } @@ -87,14 +87,14 @@ func main() { runtimeConfig := config.NewRuntimeConfig(db, logs) if err := runtimeConfig.UpdateFromDatabase(ctx); err != nil { - logger.Fatalw("failed to load config from database", zap.Error(err)) + logger.Fatalw("Failed to load config from database", zap.Error(err)) } go runtimeConfig.PeriodicUpdates(ctx, 1*time.Second) err = incident.LoadOpenIncidents(ctx, db, logs.GetChildLogger("incident"), runtimeConfig) if err != nil { - logger.Fatalw("Can't load incidents from database", zap.Error(err)) + logger.Fatalw("Cannot load incidents from database", zap.Error(err)) } if err := listener.NewListener(db, runtimeConfig, logs).Run(ctx); err != nil { diff --git a/internal/config/channel.go b/internal/config/channel.go index 769a919f3..3e19251c7 100644 --- a/internal/config/channel.go +++ b/internal/config/channel.go @@ -26,13 +26,13 @@ func (r *RuntimeConfig) fetchChannels(ctx context.Context, tx *sqlx.Tx) error { zap.String("type", c.Type), ) if channelsById[c.ID] != nil { - channelLogger.Warnw("ignoring duplicate config for channel type") + channelLogger.Warnw("Ignoring duplicate config for channel type") } else if err := channel.ValidateType(c.Type); err != nil { channelLogger.Errorw("Cannot load channel config", zap.Error(err)) } else { channelsById[c.ID] = c - channelLogger.Debugw("loaded channel config") + channelLogger.Debugw("Successfully loaded channel config") } } diff --git a/internal/config/contact.go b/internal/config/contact.go index bb72efad4..4fb2c854a 100644 --- a/internal/config/contact.go +++ b/internal/config/contact.go @@ -22,7 +22,7 @@ func (r *RuntimeConfig) fetchContacts(ctx context.Context, tx *sqlx.Tx) error { for _, c := range contacts { contactsByID[c.ID] = c - r.logger.Debugw("loaded contact config", + r.logger.Debugw("Successfully loaded contact config", zap.Int64("id", c.ID), zap.String("name", c.FullName)) } diff --git a/internal/config/contact_address.go b/internal/config/contact_address.go index 538771b3b..7d498a956 100644 --- a/internal/config/contact_address.go +++ b/internal/config/contact_address.go @@ -22,7 +22,7 @@ func (r *RuntimeConfig) fetchContactAddresses(ctx context.Context, tx *sqlx.Tx) addressesById := make(map[int64]*recipient.Address) for _, a := range addresses { addressesById[a.ID] = a - r.logger.Debugw("loaded contact_address config", + r.logger.Debugw("Successfully loaded contact_address config", zap.Int64("id", a.ID), zap.Int64("contact_id", a.ContactID), zap.String("type", a.Type), @@ -70,7 +70,7 @@ func (r *RuntimeConfig) addContactAddress(addr *recipient.Address) { if i := slices.Index(contact.Addresses, addr); i < 0 { contact.Addresses = append(contact.Addresses, addr) - r.logger.Debugw("added new address to contact", + r.logger.Debugw("Successfully added new address to contact", zap.Any("contact", contact), zap.Any("address", addr)) } diff --git a/internal/config/group.go b/internal/config/group.go index 433162aaf..ebac01218 100644 --- a/internal/config/group.go +++ b/internal/config/group.go @@ -22,7 +22,7 @@ func (r *RuntimeConfig) fetchGroups(ctx context.Context, tx *sqlx.Tx) error { for _, g := range groups { groupsById[g.ID] = g - r.logger.Debugw("loaded group config", + r.logger.Debugw("Successfully loaded group config", zap.Int64("id", g.ID), zap.String("name", g.Name)) } @@ -49,11 +49,11 @@ func (r *RuntimeConfig) fetchGroups(ctx context.Context, tx *sqlx.Tx) error { ) if g := groupsById[m.GroupId]; g == nil { - memberLogger.Warnw("ignoring member for unknown contactgroup_id") + memberLogger.Warnw("Ignoring member for unknown contactgroup_id") } else { g.MemberIDs = append(g.MemberIDs, m.ContactId) - memberLogger.Debugw("loaded contact group member", + memberLogger.Debugw("Successfully loaded contact group member", zap.String("contactgroup_name", g.Name)) } } diff --git a/internal/config/rule.go b/internal/config/rule.go index 2ebb9c97d..5cd77f0f5 100644 --- a/internal/config/rule.go +++ b/internal/config/rule.go @@ -32,7 +32,7 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { if ru.ObjectFilterExpr.Valid { f, err := filter.Parse(ru.ObjectFilterExpr.String) if err != nil { - ruleLogger.Warnw("ignoring rule as parsing object_filter failed", zap.Error(err)) + ruleLogger.Warnw("Ignoring rule as parsing object_filter failed", zap.Error(err)) continue } @@ -42,7 +42,7 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { ru.Escalations = make(map[int64]*rule.Escalation) rulesByID[ru.ID] = ru - ruleLogger.Debugw("loaded rule config") + ruleLogger.Debugw("Successfully loaded rule config") } var escalationPtr *rule.Escalation @@ -67,14 +67,14 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { rule := rulesByID[escalation.RuleID] if rule == nil { - escalationLogger.Warnw("ignoring escalation for unknown rule_id") + escalationLogger.Warnw("Ignoring escalation for unknown rule_id") continue } if escalation.ConditionExpr.Valid { cond, err := filter.Parse(escalation.ConditionExpr.String) if err != nil { - escalationLogger.Warnw("ignoring escalation, failed to parse condition", zap.Error(err)) + escalationLogger.Warnw("Ignoring escalation, failed to parse condition", zap.Error(err)) continue } @@ -83,7 +83,7 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { if escalation.FallbackForID.Valid { // TODO: implement fallbacks (needs extra validation: mismatching rule_id, cycles) - escalationLogger.Warnw("ignoring fallback escalation (not yet implemented)") + escalationLogger.Warnw("Ignoring fallback escalation (not yet implemented)") continue } @@ -93,7 +93,7 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { rule.Escalations[escalation.ID] = escalation escalationsByID[escalation.ID] = escalation - escalationLogger.Debugw("loaded escalation config") + escalationLogger.Debugw("Successfully loaded escalation config") } var recipientPtr *rule.EscalationRecipient @@ -114,10 +114,10 @@ func (r *RuntimeConfig) fetchRules(ctx context.Context, tx *sqlx.Tx) error { escalation := escalationsByID[recipient.EscalationID] if escalation == nil { - recipientLogger.Warnw("ignoring recipient for unknown escalation") + recipientLogger.Warnw("Ignoring recipient for unknown escalation") } else { escalation.Recipients = append(escalation.Recipients, recipient) - recipientLogger.Debugw("loaded escalation recipient config") + recipientLogger.Debugw("Successfully loaded escalation recipient config") } } @@ -153,7 +153,7 @@ func (r *RuntimeConfig) applyPendingRules() { if pendingRule.TimePeriodID.Valid { if p := r.TimePeriods[pendingRule.TimePeriodID.Int64]; p == nil { - ruleLogger.Warnw("ignoring rule with unknown timeperiod_id") + ruleLogger.Warnw("Ignoring rule with unknown timeperiod_id") continue } else { pendingRule.TimePeriod = p @@ -173,7 +173,7 @@ func (r *RuntimeConfig) applyPendingRules() { if c := r.Contacts[id]; c != nil { recipient.Recipient = c } else { - recipientLogger.Warnw("ignoring unknown escalation recipient") + recipientLogger.Warnw("Ignoring unknown escalation recipient") escalation.Recipients[i] = nil } } else if recipient.GroupID.Valid { @@ -182,7 +182,7 @@ func (r *RuntimeConfig) applyPendingRules() { if g := r.Groups[id]; g != nil { recipient.Recipient = g } else { - recipientLogger.Warnw("ignoring unknown escalation recipient") + recipientLogger.Warnw("Ignoring unknown escalation recipient") escalation.Recipients[i] = nil } } else if recipient.ScheduleID.Valid { @@ -191,11 +191,11 @@ func (r *RuntimeConfig) applyPendingRules() { if s := r.Schedules[id]; s != nil { recipient.Recipient = s } else { - recipientLogger.Warnw("ignoring unknown escalation recipient") + recipientLogger.Warnw("Ignoring unknown escalation recipient") escalation.Recipients[i] = nil } } else { - recipientLogger.Warnw("ignoring unknown escalation recipient") + recipientLogger.Warnw("Ignoring unknown escalation recipient") escalation.Recipients[i] = nil } } diff --git a/internal/config/runtime.go b/internal/config/runtime.go index ad6dd2e35..d92b123c4 100644 --- a/internal/config/runtime.go +++ b/internal/config/runtime.go @@ -74,10 +74,10 @@ func (r *RuntimeConfig) PeriodicUpdates(ctx context.Context, interval time.Durat for { select { case <-ticker.C: - r.logger.Debug("periodically updating config") + r.logger.Debug("Periodically updating config") err := r.UpdateFromDatabase(ctx) if err != nil { - r.logger.Errorw("periodic config update failed, continuing with previous config", zap.Error(err)) + r.logger.Errorw("Failed periodic config update, continuing with previous config", zap.Error(err)) } case <-ctx.Done(): return @@ -182,7 +182,7 @@ func (r *RuntimeConfig) GetSourceFromCredentials(user, pass string, logger *logg } func (r *RuntimeConfig) fetchFromDatabase(ctx context.Context) error { - r.logger.Debug("fetching configuration from database") + r.logger.Debug("Fetching configuration from database") start := time.Now() // Reset all pending state to start from a clean state. @@ -214,7 +214,7 @@ func (r *RuntimeConfig) fetchFromDatabase(ctx context.Context) error { } } - r.logger.Debugw("fetched configuration from database", zap.Duration("took", time.Since(start))) + r.logger.Debugw("Fetched configuration from database", zap.Duration("took", time.Since(start))) return nil } @@ -223,7 +223,7 @@ func (r *RuntimeConfig) applyPending() { r.mu.Lock() defer r.mu.Unlock() - r.logger.Debug("applying pending configuration") + r.logger.Debug("Applying pending configuration") start := time.Now() r.applyPendingChannels() @@ -235,5 +235,5 @@ func (r *RuntimeConfig) applyPending() { r.applyPendingRules() r.applyPendingSources() - r.logger.Debugw("applied pending configuration", zap.Duration("took", time.Since(start))) + r.logger.Debugw("Successfully applied pending configuration", zap.Duration("took", time.Since(start))) } diff --git a/internal/config/schedule.go b/internal/config/schedule.go index b43af6475..073838668 100644 --- a/internal/config/schedule.go +++ b/internal/config/schedule.go @@ -22,7 +22,7 @@ func (r *RuntimeConfig) fetchSchedules(ctx context.Context, tx *sqlx.Tx) error { for _, g := range schedules { schedulesById[g.ID] = g - r.logger.Debugw("loaded schedule config", + r.logger.Debugw("Successfully loaded schedule config", zap.Int64("id", g.ID), zap.String("name", g.Name)) } @@ -41,11 +41,11 @@ func (r *RuntimeConfig) fetchSchedules(ctx context.Context, tx *sqlx.Tx) error { memberLogger := makeScheduleMemberLogger(r.logger.SugaredLogger, member) if s := schedulesById[member.ScheduleID]; s == nil { - memberLogger.Warnw("ignoring schedule member for unknown schedule_id") + memberLogger.Warnw("Ignoring schedule member for unknown schedule_id") } else { s.MemberRows = append(s.MemberRows, member) - memberLogger.Debugw("member") + memberLogger.Debugw("Found member") } } @@ -77,7 +77,7 @@ func (r *RuntimeConfig) applyPendingSchedules() { period := r.TimePeriods[memberRow.TimePeriodID] if period == nil { - memberLogger.Warnw("ignoring schedule member for unknown timeperiod_id") + memberLogger.Warnw("Ignoring schedule member for unknown timeperiod_id") continue } @@ -85,7 +85,7 @@ func (r *RuntimeConfig) applyPendingSchedules() { if memberRow.ContactID.Valid { contact = r.Contacts[memberRow.ContactID.Int64] if contact == nil { - memberLogger.Warnw("ignoring schedule member for unknown contact_id") + memberLogger.Warnw("Ignoring schedule member for unknown contact_id") continue } } @@ -94,7 +94,7 @@ func (r *RuntimeConfig) applyPendingSchedules() { if memberRow.GroupID.Valid { group = r.Groups[memberRow.GroupID.Int64] if group == nil { - memberLogger.Warnw("ignoring schedule member for unknown contactgroup_id") + memberLogger.Warnw("Ignoring schedule member for unknown contactgroup_id") continue } } diff --git a/internal/config/source.go b/internal/config/source.go index a851980fb..d376dcf91 100644 --- a/internal/config/source.go +++ b/internal/config/source.go @@ -34,11 +34,11 @@ func (r *RuntimeConfig) fetchSources(ctx context.Context, tx *sqlx.Tx) error { zap.String("type", s.Type), ) if sourcesById[s.ID] != nil { - sourceLogger.Warnw("ignoring duplicate config for source ID") + sourceLogger.Warnw("Ignoring duplicate config for source ID") } else { sourcesById[s.ID] = s - sourceLogger.Debugw("loaded source config") + sourceLogger.Debugw("Successfully loaded source config") } } diff --git a/internal/config/timeperiod.go b/internal/config/timeperiod.go index 9acb6576b..74835776d 100644 --- a/internal/config/timeperiod.go +++ b/internal/config/timeperiod.go @@ -49,7 +49,7 @@ func (r *RuntimeConfig) fetchTimePeriods(ctx context.Context, tx *sqlx.Tx) error for _, row := range entries { p := timePeriodsById[row.TimePeriodID] if p == nil { - r.logger.Warnw("ignoring entry for unknown timeperiod_id", + r.logger.Warnw("Ignoring entry for unknown timeperiod_id", zap.Int64("timeperiod_entry_id", row.ID), zap.Int64("timeperiod_id", row.TimePeriodID)) continue @@ -64,7 +64,7 @@ func (r *RuntimeConfig) fetchTimePeriods(ctx context.Context, tx *sqlx.Tx) error loc, err := time.LoadLocation(row.Timezone) if err != nil { - r.logger.Warnw("ignoring time period entry with unknown timezone", + r.logger.Warnw("Ignoring time period entry with unknown timezone", zap.Int64("timeperiod_entry_id", row.ID), zap.String("timezone", row.Timezone), zap.Error(err)) @@ -83,7 +83,7 @@ func (r *RuntimeConfig) fetchTimePeriods(ctx context.Context, tx *sqlx.Tx) error err = entry.Init() if err != nil { - r.logger.Warnw("ignoring time period entry", + r.logger.Warnw("Ignoring time period entry", zap.Int64("timeperiod_entry_id", row.ID), zap.String("rrule", entry.RecurrenceRule), zap.Error(err)) @@ -92,7 +92,7 @@ func (r *RuntimeConfig) fetchTimePeriods(ctx context.Context, tx *sqlx.Tx) error p.Entries = append(p.Entries, entry) - r.logger.Debugw("loaded time period entry", + r.logger.Debugw("Successfully loaded time period entry", zap.String("timeperiod", p.Name), zap.Time("start", entry.Start), zap.Time("end", entry.End), diff --git a/internal/filter/parser_test.go b/internal/filter/parser_test.go index b23a79557..ca386f67b 100644 --- a/internal/filter/parser_test.go +++ b/internal/filter/parser_test.go @@ -141,7 +141,7 @@ func TestFilter(t *testing.T) { assert.Nil(t, err, "There should be no errors but got: %s", err) expected := &Condition{op: Equal, column: "foo", value: "bar"} - assert.Equal(t, expected, rule, "Parser doesn't parse single condition correctly") + assert.Equal(t, expected, rule, "Parser does not parse single condition correctly") }) t.Run("UrlEncodedFilterExpression", func(t *testing.T) { diff --git a/internal/incident/db_types.go b/internal/incident/db_types.go index c037f7a0d..a114ff5e3 100644 --- a/internal/incident/db_types.go +++ b/internal/incident/db_types.go @@ -40,7 +40,7 @@ func (i *IncidentRow) Sync(ctx context.Context, tx *sqlx.Tx, db *icingadb.DB, up stmt, _ := db.BuildUpsertStmt(i) _, err := tx.NamedExecContext(ctx, stmt, i) if err != nil { - return fmt.Errorf("failed to upsert incident: %s", err) + return fmt.Errorf("failed to upsert incident: %w", err) } } else { incidentId, err := utils.InsertAndFetchId(ctx, tx, utils.BuildInsertStmtWithout(db, i, "id"), i) diff --git a/internal/incident/incident.go b/internal/incident/incident.go index b0d60aa64..7e02ec5c5 100644 --- a/internal/incident/incident.go +++ b/internal/incident/incident.go @@ -2,7 +2,6 @@ package incident import ( "context" - "errors" "fmt" "github.com/icinga/icinga-notifications/internal/config" "github.com/icinga/icinga-notifications/internal/contracts" @@ -112,16 +111,14 @@ func (i *Incident) ProcessEvent(ctx context.Context, ev *event.Event, created bo tx, err := i.db.BeginTxx(ctx, nil) if err != nil { - i.logger.Errorw("Can't start a db transaction", zap.Error(err)) - - return errors.New("can't start a db transaction") + i.logger.Errorw("Cannot start a db transaction", zap.Error(err)) + return err } defer func() { _ = tx.Rollback() }() if err = ev.Sync(ctx, tx, i.db, i.Object.ID); err != nil { i.logger.Errorw("Failed to insert event and fetch its ID", zap.String("event", ev.String()), zap.Error(err)) - - return errors.New("can't insert event and fetch its ID") + return err } if created { @@ -134,9 +131,8 @@ func (i *Incident) ProcessEvent(ctx context.Context, ev *event.Event, created bo } if err = i.AddEvent(ctx, tx, ev); err != nil { - i.logger.Errorw("Can't insert incident event to the database", zap.Error(err)) - - return errors.New("can't insert incident event to the database") + i.logger.Errorw("Cannot insert incident event to the database", zap.Error(err)) + return err } if ev.Type == event.TypeAcknowledgement { @@ -174,9 +170,8 @@ func (i *Incident) ProcessEvent(ctx context.Context, ev *event.Event, created bo } if err = tx.Commit(); err != nil { - i.logger.Errorw("Can't commit db transaction", zap.Error(err)) - - return errors.New("can't commit db transaction") + i.logger.Errorw("Cannot commit db transaction", zap.Error(err)) + return err } return i.notifyContacts(ctx, ev, notifications) @@ -229,7 +224,6 @@ func (i *Incident) RetriggerEscalations(ev *event.Event) { } notifications, err = i.addPendingNotifications(ctx, tx, ev, channels, types.Int{}) - return err }) if err != nil { @@ -249,10 +243,9 @@ func (i *Incident) processSeverityChangedEvent(ctx context.Context, tx *sqlx.Tx, oldSeverity := i.Severity newSeverity := ev.Severity if oldSeverity == newSeverity { - msg := fmt.Sprintf("Ignoring superfluous %q state event from source %d", ev.Severity.String(), ev.SourceId) - i.logger.Warnln(msg) + i.logger.Warnf("Ignoring superfluous %q state event from source %d", ev.Severity.String(), ev.SourceId) - return causedByHistoryId, errors.New(msg) + return causedByHistoryId, fmt.Errorf("ignoring superfluous %q state event from source %d", ev.Severity.String(), ev.SourceId) } i.logger.Infof("Incident severity changed from %s to %s", oldSeverity.String(), newSeverity.String()) @@ -269,8 +262,7 @@ func (i *Incident) processSeverityChangedEvent(ctx context.Context, tx *sqlx.Tx, historyId, err := i.AddHistory(ctx, tx, history, true) if err != nil { i.logger.Errorw("Failed to insert incident severity changed history", zap.Error(err)) - - return causedByHistoryId, errors.New("failed to insert incident severity changed history") + return causedByHistoryId, err } causedByHistoryId = historyId @@ -289,9 +281,8 @@ func (i *Incident) processSeverityChangedEvent(ctx context.Context, tx *sqlx.Tx, _, err = i.AddHistory(ctx, tx, history, false) if err != nil { - i.logger.Errorw("Can't insert incident closed history to the database", zap.Error(err)) - - return types.Int{}, errors.New("can't insert incident closed history to the database") + i.logger.Errorw("Cannot insert incident closed history to the database", zap.Error(err)) + return types.Int{}, err } if i.timer != nil { @@ -302,8 +293,7 @@ func (i *Incident) processSeverityChangedEvent(ctx context.Context, tx *sqlx.Tx, i.Severity = newSeverity if err := i.Sync(ctx, tx); err != nil { i.logger.Errorw("Failed to update incident severity", zap.Error(err)) - - return causedByHistoryId, errors.New("failed to update incident severity") + return causedByHistoryId, err } return causedByHistoryId, nil @@ -313,9 +303,8 @@ func (i *Incident) processIncidentOpenedEvent(ctx context.Context, tx *sqlx.Tx, i.StartedAt = ev.Time i.Severity = ev.Severity if err := i.Sync(ctx, tx); err != nil { - i.logger.Errorw("Can't insert incident to the database", zap.Error(err)) - - return errors.New("can't insert incident to the database") + i.logger.Errorw("Cannot insert incident to the database", zap.Error(err)) + return err } i.logger.Infow(fmt.Sprintf("Source %d opened incident at severity %q", ev.SourceId, i.Severity.String()), zap.String("message", ev.Message)) @@ -329,9 +318,8 @@ func (i *Incident) processIncidentOpenedEvent(ctx context.Context, tx *sqlx.Tx, } if _, err := i.AddHistory(ctx, tx, historyRow, false); err != nil { - i.logger.Errorw("Can't insert incident opened history event", zap.Error(err)) - - return errors.New("can't insert incident opened history event") + i.logger.Errorw("Cannot insert incident opened history event", zap.Error(err)) + return err } return nil @@ -368,8 +356,7 @@ func (i *Incident) evaluateRules(ctx context.Context, tx *sqlx.Tx, eventID int64 err := i.AddRuleMatched(ctx, tx, r) if err != nil { i.logger.Errorw("Failed to upsert incident rule", zap.String("rule", r.Name), zap.Error(err)) - - return types.Int{}, errors.New("failed to insert incident rule") + return types.Int{}, err } history := &HistoryRow{ @@ -382,8 +369,7 @@ func (i *Incident) evaluateRules(ctx context.Context, tx *sqlx.Tx, eventID int64 insertedID, err := i.AddHistory(ctx, tx, history, true) if err != nil { i.logger.Errorw("Failed to insert rule matched incident history", zap.String("rule", r.Name), zap.Error(err)) - - return types.Int{}, errors.New("failed to insert rule matched incident history") + return types.Int{}, err } if insertedID.Valid && !causedBy.Valid { @@ -489,8 +475,7 @@ func (i *Incident) triggerEscalations(ctx context.Context, tx *sqlx.Tx, ev *even "Failed to upsert escalation state", zap.String("rule", r.Name), zap.String("escalation", escalation.DisplayName()), zap.Error(err), ) - - return errors.New("failed to upsert escalation state") + return err } history := &HistoryRow{ @@ -507,8 +492,7 @@ func (i *Incident) triggerEscalations(ctx context.Context, tx *sqlx.Tx, ev *even "Failed to insert escalation triggered incident history", zap.String("rule", r.Name), zap.String("escalation", escalation.DisplayName()), zap.Error(err), ) - - return errors.New("failed to insert escalation triggered incident history") + return err } if err := i.AddRecipient(ctx, tx, escalation, ev.ID); err != nil { @@ -612,11 +596,8 @@ func (i *Incident) processAcknowledgementEvent(ctx context.Context, tx *sqlx.Tx, _, err := i.AddHistory(ctx, tx, hr, false) if err != nil { - i.logger.Errorw( - "Failed to add recipient role changed history", zap.String("recipient", contact.String()), zap.Error(err), - ) - - return errors.New("failed to add recipient role changed history") + i.logger.Errorw("Failed to add recipient role changed history", zap.String("recipient", contact.String()), zap.Error(err)) + return err } cr := &ContactRow{IncidentID: hr.IncidentID, Key: recipientKey, Role: newRole} @@ -624,11 +605,8 @@ func (i *Incident) processAcknowledgementEvent(ctx context.Context, tx *sqlx.Tx, stmt, _ := i.db.BuildUpsertStmt(cr) _, err = tx.NamedExecContext(ctx, stmt, cr) if err != nil { - i.logger.Errorw( - "Failed to upsert incident contact", zap.String("contact", contact.String()), zap.Error(err), - ) - - return errors.New("failed to upsert incident contact") + i.logger.Errorw("Failed to upsert incident contact", zap.String("contact", contact.String()), zap.Error(err)) + return err } return nil @@ -691,8 +669,7 @@ func (i *Incident) restoreRecipients(ctx context.Context) error { "Failed to restore incident recipients from the database", zap.String("object", i.IncidentObject().DisplayName()), zap.String("incident", i.String()), zap.Error(err), ) - - return errors.New("failed to restore incident recipients") + return err } recipients := make(map[recipient.Key]*RecipientState) @@ -713,8 +690,7 @@ func (i *Incident) restoreEscalationsState(ctx context.Context) error { err := i.db.SelectContext(ctx, &states, i.db.Rebind(i.db.BuildSelectStmt(state, state)+` WHERE "incident_id" = ?`), i.ID()) if err != nil { i.logger.Errorw("Failed to restore incident rule escalation states", zap.Error(err)) - - return errors.New("failed to restore incident rule escalation states") + return err } for _, state := range states { diff --git a/internal/incident/incidents.go b/internal/incident/incidents.go index 56d0b1663..b91c7be3f 100644 --- a/internal/incident/incidents.go +++ b/internal/incident/incidents.go @@ -29,8 +29,7 @@ func LoadOpenIncidents(ctx context.Context, db *icingadb.DB, logger *logging.Log err := db.SelectContext(ctx, &objectIDs, `SELECT object_id FROM incident WHERE "recovered_at" IS NULL`) if err != nil { logger.Errorw("Failed to load active incidents from database", zap.Error(err)) - - return errors.New("failed to fetch open incidents") + return err } for _, objectID := range objectIDs { @@ -73,8 +72,7 @@ func GetCurrent( err := db.QueryRowxContext(ctx, db.Rebind(db.BuildSelectStmt(ir, ir)+` WHERE "object_id" = ? AND "recovered_at" IS NULL`), obj.ID).StructScan(ir) if err != nil && !errors.Is(err, sql.ErrNoRows) { logger.Errorw("Failed to load incident from database", zap.String("object", obj.DisplayName()), zap.Error(err)) - - return nil, false, errors.New("failed to load incident from database") + return nil, false, err } else if err == nil { incident.incidentRowID = ir.ID incident.StartedAt = ir.StartedAt.Time() diff --git a/internal/incident/sync.go b/internal/incident/sync.go index b29969dc9..2a51c9cdf 100644 --- a/internal/incident/sync.go +++ b/internal/incident/sync.go @@ -2,7 +2,6 @@ package incident import ( "context" - "errors" "github.com/icinga/icinga-notifications/internal/event" "github.com/icinga/icinga-notifications/internal/recipient" "github.com/icinga/icinga-notifications/internal/rule" @@ -115,8 +114,7 @@ func (i *Incident) AddRecipient(ctx context.Context, tx *sqlx.Tx, escalation *ru "Failed to insert recipient role changed incident history", zap.String("escalation", escalation.DisplayName()), zap.String("recipients", r.String()), zap.Error(err), ) - - return errors.New("failed to insert recipient role changed incident history") + return err } } cr.Role = state.Role @@ -129,8 +127,7 @@ func (i *Incident) AddRecipient(ctx context.Context, tx *sqlx.Tx, escalation *ru "Failed to upsert incident recipient", zap.String("escalation", escalation.DisplayName()), zap.String("recipient", r.String()), zap.Error(err), ) - - return errors.New("failed to upsert incident recipient") + return err } } @@ -170,8 +167,7 @@ func (i *Incident) addPendingNotifications( "Failed to insert contact pending notification incident history", zap.String("contact", contact.String()), zap.Error(err), ) - - return nil, errors.New("can't insert contact pending notification incident history") + return nil, err } hr.ID = id.Int64 diff --git a/internal/listener/listener.go b/internal/listener/listener.go index 6ee5b41ee..3476429ff 100644 --- a/internal/listener/listener.go +++ b/internal/listener/listener.go @@ -151,7 +151,7 @@ func (l *Listener) ProcessEvent(w http.ResponseWriter, req *http.Request) { ctx := context.Background() obj, err := object.FromEvent(ctx, l.db, &ev) if err != nil { - l.logger.Errorw("Can't sync object", zap.Error(err)) + l.logger.Errorw("Cannot sync object", zap.Error(err)) abort(http.StatusInternalServerError, &ev, err.Error()) return } @@ -167,7 +167,7 @@ func (l *Listener) ProcessEvent(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusNotAcceptable) if ev.Type == event.TypeAcknowledgement { - msg := fmt.Sprintf("%q doesn't have active incident. Ignoring acknowledgement event from source %d", obj.DisplayName(), ev.SourceId) + msg := fmt.Sprintf("%q does not have active incident. Ignoring acknowledgement event from source %d", obj.DisplayName(), ev.SourceId) _, _ = fmt.Fprintln(w, msg) l.logger.Warnln(msg) @@ -187,14 +187,13 @@ func (l *Listener) ProcessEvent(w http.ResponseWriter, req *http.Request) { l.logger.Infow("Processing event", zap.String("event", ev.String())) - err = currentIncident.ProcessEvent(ctx, &ev, created) - if err != nil { - abort(http.StatusInternalServerError, &ev, err.Error()) + if currentIncident.ProcessEvent(ctx, &ev, created) != nil { + abort(http.StatusInternalServerError, &ev, "Error while processing HTTP request, check server logs for details") return } w.WriteHeader(http.StatusOK) - _, _ = fmt.Fprintln(w, "event processed successfully") + _, _ = fmt.Fprintln(w, "Successfully processed event") _, _ = fmt.Fprintln(w) } diff --git a/internal/object/object.go b/internal/object/object.go index 4b1ec42d5..024faf3d5 100644 --- a/internal/object/object.go +++ b/internal/object/object.go @@ -102,7 +102,7 @@ func FromEvent(ctx context.Context, db *icingadb.DB, ev *event.Event) (*Object, } if err = tx.Commit(); err != nil { - return nil, fmt.Errorf("can't commit object database transaction: %w", err) + return nil, fmt.Errorf("cannot commit object database transaction: %w", err) } object.ExtraTags = ev.ExtraTags diff --git a/internal/rule/condition.go b/internal/rule/condition.go index 9bf4db3b6..97368e44b 100644 --- a/internal/rule/condition.go +++ b/internal/rule/condition.go @@ -84,7 +84,7 @@ func (e *EscalationFilter) EvalLess(key string, value string) (bool, error) { } func (e *EscalationFilter) EvalLike(key string, value string) (bool, error) { - return false, fmt.Errorf("escalation filter doesn't support wildcard matches") + return false, fmt.Errorf("escalation filter does not support wildcard matches") } func (e *EscalationFilter) EvalLessOrEqual(key string, value string) (bool, error) { diff --git a/internal/utils/utils.go b/internal/utils/utils.go index a809bbe3b..771078ce7 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -62,17 +62,17 @@ func InsertAndFetchId(ctx context.Context, tx *sqlx.Tx, stmt string, args any) ( err = preparedStmt.Get(&lastInsertId, args) if err != nil { - return 0, fmt.Errorf("failed to insert entry for type %T: %s", args, err) + return 0, fmt.Errorf("failed to insert entry for type %T: %w", args, err) } } else { result, err := tx.NamedExecContext(ctx, stmt, args) if err != nil { - return 0, fmt.Errorf("failed to insert entry for type %T: %s", args, err) + return 0, fmt.Errorf("failed to insert entry for type %T: %w", args, err) } lastInsertId, err = result.LastInsertId() if err != nil { - return 0, fmt.Errorf("failed to fetch last insert id for type %T: %s", args, err) + return 0, fmt.Errorf("failed to fetch last insert id for type %T: %w", args, err) } }