Documentation
¶
Index ¶
- Variables
- func Process[T event.Event | event.QuickAction](ctx context.Context, db *database.DB, l *logging.Logging, ...) error
- func ReevaluateEscalations(ctx context.Context, db *database.DB, logger *logging.Logger, ...) error
- func Yield(ctx context.Context, db *database.DB, l *logging.Logging, ...) (<-chan Pair, <-chan error)
- func YieldLight(ctx context.Context, db *database.DB, l *logging.Logging, ...) (<-chan Pair, <-chan error)
- func YieldNotificationHistory(ctx context.Context, db *database.DB, since int64) (<-chan NotificationHistoryPair, <-chan error)
- type ContactRow
- type EscalationState
- type HistoryEventType
- type HistoryRow
- type Incident
- func (i *Incident) AddEscalationRecipients(ctx context.Context, tx *sqlx.Tx, escalation *rule.Entry) error
- func (i *Incident) AddEscalationTriggered(ctx context.Context, tx *sqlx.Tx, state *EscalationState) error
- func (i *Incident) AddRuleMatched(ctx context.Context, tx *sqlx.Tx, r *rule.Rule) error
- func (i *Incident) Close(ctx context.Context, tx *sqlx.Tx, recoveredAt types.UnixMilli) error
- func (i *Incident) DoQuickAction(ctx context.Context, qa *event.QuickAction) error
- func (i *Incident) HasManager() bool
- func (i *Incident) IsMuted() bool
- func (i *Incident) IsNew() bool
- func (i *Incident) IsNotifiable(rs RecipientState) bool
- func (i *Incident) Manager() (string, bool)
- func (i *Incident) Object(ctx context.Context) (*object.Object, error)
- func (i *Incident) ProcessEvent(ctx context.Context, ev *event.Event) error
- func (i *Incident) RestoreState(ctx context.Context, tx *sqlx.Tx, restoreAll bool) error
- func (i *Incident) RetriggerEscalations(ctx context.Context, o *object.Object, ev *event.Event) error
- func (i *Incident) SourceName() string
- func (i *Incident) String() string
- func (i *Incident) Sync(ctx context.Context, tx *sqlx.Tx) error
- func (i *Incident) Upsert() any
- type NotificationEntry
- type NotificationHistory
- type NotificationHistoryPair
- type NotificationState
- type Pair
- type ReasonKind
- type RecipientState
- type RuleRow
- type SkippedNotificationHistory
Constants ¶
This section is empty.
Variables ¶
var ( // ErrSeverityChangeWithoutIncidentFlag is returned when an event tries to change the severity of an incident // but does not set the 'incident' flag. ErrSeverityChangeWithoutIncidentFlag = errors.New("cannot change severity of an incident with an event that doesn't set the 'incident' flag") // ErrOpenIncidentWithoutSeverity is returned when an event tries to open a new incident without a severity. ErrOpenIncidentWithoutSeverity = errors.New("cannot open or escalate an incident without a severity") )
Functions ¶
func Process ¶ added in v1.0.0
func Process[T event.Event | event.QuickAction](ctx context.Context, db *database.DB, l *logging.Logging, rc *config.RuntimeConfig, req *T) error
Process processes an [event.Event] or [event.QuickAction] and updates the incident state accordingly.
If [event.Event] is provided, it might return ErrOpenIncidentWithoutSeverity if the event is trying to open an incident without a severity or ErrSeverityChangeWithoutIncidentFlag if the event is trying to change the severity of an incident without the incident flag set. In both cases, the listener should map these errors to a 400 Bad Request response to the source.
func ReevaluateEscalations ¶ added in v1.0.0
func ReevaluateEscalations( ctx context.Context, db *database.DB, logger *logging.Logger, runtimeConfig *config.RuntimeConfig, ) error
ReevaluateEscalations retriggers escalations for every incident where Incident.NextEscalationCheckAt is due.
func Yield ¶ added in v1.0.0
func Yield(ctx context.Context, db *database.DB, l *logging.Logging, rc *config.RuntimeConfig) (<-chan Pair, <-chan error)
Yield returns a channel of Pair for all active incidents (see yield docstring).
func YieldLight ¶ added in v1.0.0
func YieldLight(ctx context.Context, db *database.DB, l *logging.Logging, rc *config.RuntimeConfig) (<-chan Pair, <-chan error)
YieldLight is exactly like Yield but without restoring all the incident's related state.
This is useful for operations that don't require the full incident state, such as listing incidents.
func YieldNotificationHistory ¶ added in v1.0.0
func YieldNotificationHistory( ctx context.Context, db *database.DB, since int64, ) (<-chan NotificationHistoryPair, <-chan error)
YieldNotificationHistory yields all notification_history entries since the given timestamp as a channel of NotificationHistoryPair. The second channel is used to report errors that occur during the query or iteration. The function returns immediately, and the caller should read from the channels until they are closed.
Types ¶
type ContactRow ¶
type ContactRow struct {
ID int64 `db:"id"`
IncidentID int64 `db:"incident_id"`
recipient.Key `db:",inline"`
Role recipient.Role `db:"role"`
EventTypes types.StringList `db:"event_types"`
ChangedAt types.UnixMilli `db:"changed_at"`
}
ContactRow represents a single incident contact database entry.
func (*ContactRow) PgsqlOnConflictConstraint ¶
func (c *ContactRow) PgsqlOnConflictConstraint() string
PgsqlOnConflictConstraint implements the database.PgsqlOnConflictConstrainter interface.
func (*ContactRow) TableName ¶
func (c *ContactRow) TableName() string
TableName implements the contracts.TableNamer interface.
func (*ContactRow) Upsert ¶
func (c *ContactRow) Upsert() any
Upsert implements the contracts.Upserter interface.
type EscalationState ¶
type EscalationState struct {
IncidentID int64 `db:"incident_id"`
RuleEntryID int64 `db:"rule_entry_id"`
TriggeredAt types.UnixMilli `db:"triggered_at"`
// IsNew defines whether the escalation triggered during the current transaction.
//
// Every escalation state loaded from the database isn't new, so IsNew is false. For all other escalations
// added in Incident.triggerEscalations due to the ongoing event, IsNew is set true.
IsNew bool `db:"-"`
}
func (*EscalationState) TableName ¶
func (e *EscalationState) TableName() string
TableName implements the contracts.TableNamer interface.
type HistoryEventType ¶
type HistoryEventType int
const ( HistoryEventTypeNull HistoryEventType = iota Opened Muted Unmuted IncidentSeverityChanged RuleMatched EscalationTriggered RecipientRoleChanged Closed Notified )
func (*HistoryEventType) Scan ¶
func (h *HistoryEventType) Scan(src any) error
Scan implements the sql.Scanner interface. Supports SQL NULL.
func (*HistoryEventType) String ¶
func (h *HistoryEventType) String() string
type HistoryRow ¶
type HistoryRow struct {
ID int64 `db:"id"`
IncidentID int64 `db:"incident_id"`
EventID types.UUID `db:"event_id"`
RuleEntryID types.Int `db:"rule_entry_id"`
recipient.Key `db:",inline"`
RuleID types.Int `db:"rule_id"`
Time types.UnixMilli `db:"time"`
Type HistoryEventType `db:"type"`
ChannelID types.Int `db:"channel_id"`
NewSeverity event.Severity `db:"new_severity"`
OldSeverity event.Severity `db:"old_severity"`
NewRecipientRole recipient.Role `db:"new_recipient_role"`
OldRecipientRole recipient.Role `db:"old_recipient_role"`
Message types.String `db:"message"`
NotificationState NotificationState `db:"notification_state"`
SentAt types.UnixMilli `db:"sent_at"`
}
HistoryRow represents a single incident history database entry.
func (*HistoryRow) Sync ¶
Sync persists the current state of this history to the database and retrieves the just inserted history ID. Returns error when failed to execute the query.
func (*HistoryRow) TableName ¶
func (h *HistoryRow) TableName() string
TableName implements the contracts.TableNamer interface.
type Incident ¶
type Incident struct {
Id int64 `db:"id"`
ObjectID types.Binary `db:"object_id"`
StartedAt types.UnixMilli `db:"started_at"`
RecoveredAt types.UnixMilli `db:"recovered_at"`
Severity baseEv.Severity `db:"severity"`
// MuteReason indicates whether this incident is currently muted; its non-null value contains the mute reason.
MuteReason types.String `db:"mute_reason"`
Summary string `db:"summary"`
Message types.String `db:"message"`
SourceID int64 `db:"source_id"`
// NextEscalationCheckAt stores when this Incident's time-based escalations should be reevaluated next. It is used
// in the ReevaluateEscalations function to reevaluate incident escalations.
//
// For example, if there are escalations configured for incident_age>1h and incident_age>2h.
// - If the incident is less than an hour old, this field contains the incident start time plus one hour.
// - If the incident is between 1h and 2h old, this field contains the incident start time plus two hours.
// - If the incident is already older than 2h, no future escalations can be reached solely based on the incident
// aging, so the field is left nil.
NextEscalationCheckAt types.UnixMilli `db:"next_escalation_check_at"`
EscalationState map[escalationID]*EscalationState `db:"-"`
EscalationRules map[ruleID]struct{} `db:"-"`
Recipients map[recipient.Key]RecipientState `db:"-"`
// NotificationRules is a temporary map of notification rule IDs that matched the ongoing event.
//
// This is not persisted to the database, but is used to temporarily cache matched notification
// rules across multiple method calls during the processing of a single event.
NotificationRules map[ruleID]struct{} `db:"-"`
// contains filtered or unexported fields
}
func (*Incident) AddEscalationRecipients ¶ added in v1.0.0
func (i *Incident) AddEscalationRecipients(ctx context.Context, tx *sqlx.Tx, escalation *rule.Entry) error
AddEscalationRecipients adds the recipients of the given *rule.Entry to the incident's recipients list.
Each recipient is added to the incident's recipients list with the role RoleRecipient, and a new ContactRow is inserted into the incident_contact table. If a recipient already exists in the incident's recipients list, it is skipped and no new ContactRow is inserted for that recipient.
func (*Incident) AddEscalationTriggered ¶
func (*Incident) AddRuleMatched ¶
AddRuleMatched syncs the given *rule.Rule to the database. Returns an error on database failure.
func (*Incident) Close ¶ added in v1.0.0
Close closes the current incident if not already recovered.
If the incident is already recovered, this is a no-op. Returns an error if fails to insert the generated history to the database. You must call [Sync] after this method to persist the incident's recovered state.
func (*Incident) DoQuickAction ¶ added in v1.0.0
DoQuickAction executes the given quick action for the current incident in an own transaction.
func (*Incident) HasManager ¶
func (*Incident) IsMuted ¶ added in v1.0.0
IsMuted returns whether this incident is currently muted.
func (*Incident) IsNew ¶ added in v1.0.0
IsNew returns whether this incident has not yet been persisted to the database.
func (*Incident) IsNotifiable ¶
func (i *Incident) IsNotifiable(rs RecipientState) bool
IsNotifiable returns whether the given recipient state is eligible to be notified for this incident.
For a managed incident, only managers and subscribers should be notified, unless the recipient is new and has not yet been notified. For an unmanaged incident, all recipients are eligible to be notified.
func (*Incident) Manager ¶ added in v1.0.0
Manager returns the full name of the incident's current manager and true, or ("", false) if unmanaged.
func (*Incident) Object ¶
Object fetches the object.Object this incident belongs to from the database.
func (*Incident) ProcessEvent ¶
ProcessEvent processes ev in its own transaction.
Depending on [event.Event.Incident], it opens or updates the incident and evaluates escalation rules (true), evaluates notification rules without changing the incident (false), or only updates an open incident (unset).
See doc/20-HTTP-API.md.
func (*Incident) RestoreState ¶ added in v1.0.0
RestoreState reloads the incident state from the database within the given transaction.
The open incident is looked up by the Incident.ObjectID, which must be set before calling this method. It must be called before processing an event, as another node in an HA setup may have altered the state in the meantime.
The incident row is locked via SELECT ... FOR UPDATE, so that concurrent calls for the same object, whether on this or other nodes, are serialized until the caller commits or rolls back the tx. To avoid lock ordering issues, callers shouldn't lock any other incident rows in the same tx before calling this method.
If restoreAll is true, the incident's matched rules, escalation states, and recipients are also restored from the database, otherwise only the incident row itself is restored.
A caller must not hold a read lock on the Incident.runtimeConfig when calling this method, as it will be acquired internally to restore the incident's escalation states.
If there is no open incident for the object, e.g. because it has recovered in the meantime or has never existed, a sql.ErrNoRows error will be returned.
func (*Incident) RetriggerEscalations ¶
func (i *Incident) RetriggerEscalations(ctx context.Context, o *object.Object, ev *event.Event) error
RetriggerEscalations tries to re-evaluate the escalations and notify contacts.
func (*Incident) SourceName ¶ added in v1.0.0
SourceName returns the configured name of the source that originally opened this incident, or "" if unknown.
type NotificationEntry ¶
type NotificationEntry struct {
HistoryRowID int64 `db:"id"`
ContactID int64 `db:"-"`
ChannelID int64 `db:"-"`
State NotificationState `db:"notification_state"`
SentAt types.UnixMilli `db:"sent_at"`
Reason notifyReason `db:"-"`
HistoryEntry NotificationHistory `db:"-"`
SkippedHistoryEntries []SkippedNotificationHistory `db:"-"`
// IsIncidentRelated marks notifications that belong to the incident.
//
// Only these have an incident_history row (HistoryRowID) and pass the incident to the channel.
IsIncidentRelated bool `db:"-"`
}
NotificationEntry is used to cache a set of incident history fields of type Notified.
The event processing workflow is performed in a separate transaction before trying to send the actual notifications. Thus, all resulting notification entries are marked as pending, and it creates a reference to them of this type. The cached entries are then used to actually notify the contacts and mark the pending notification entries as either NotificationStateSent or NotificationStateFailed.
func (*NotificationEntry) TableName ¶
func (h *NotificationEntry) TableName() string
TableName implements the contracts.TableNamer interface.
type NotificationHistory ¶ added in v1.0.0
type NotificationHistory struct {
ID int64 `db:"id"`
ObjectID types.Binary `db:"object_id"`
EventID types.UUID `db:"event_id"`
ContactID int64 `db:"contact_id"`
ContactgroupID types.Int `db:"contactgroup_id"`
ScheduleID types.Int `db:"schedule_id"`
ChannelID int64 `db:"channel_id"`
IncidentID types.Int `db:"incident_id"`
EventMessage string `db:"event_message"`
EventSummary string `db:"event_summary"`
State NotificationState `db:"state"`
TriggeredAt types.UnixMilli `db:"triggered_at"`
IncidentClosed types.Bool `db:"incident_closed"`
DeliveryResult types.String `db:"delivery_result"`
}
NotificationHistory represents a single notification_history database entry, recording the fact that a notification was triggered for a given incident history entry.
type NotificationHistoryPair ¶ added in v1.0.0
type NotificationState ¶
type NotificationState uint8
NotificationState represents the state of a notification in Icinga notifications. It is an integer type with predefined constants for different notification states.
const ( NotificationStateNull NotificationState = iota NotificationStateSuppressed // suppressed NotificationStatePending // pending NotificationStateSent // sent NotificationStateFailed // failed )
func ParseNotificationState ¶ added in v1.0.0
func ParseNotificationState(name string) (NotificationState, error)
ParseNotificationState parses a string representation of a notification state and returns the corresponding NotificationState value. If the string does not match any known notification state, it returns an error indicating the unknown notification state.
func (NotificationState) MarshalJSON ¶ added in v1.0.0
func (n NotificationState) MarshalJSON() ([]byte, error)
MarshalJSON implements the json.Marshaler interface for NotificationState.
func (*NotificationState) Scan ¶
func (n *NotificationState) Scan(src any) error
Scan implements the sql.Scanner interface. Supports SQL NULL.
func (NotificationState) String ¶
func (i NotificationState) String() string
func (*NotificationState) UnmarshalJSON ¶ added in v1.0.0
func (n *NotificationState) UnmarshalJSON(data []byte) error
UnmarshalJSON implements the json.Unmarshaler interface for NotificationState.
type Pair ¶ added in v1.0.0
Pair is a struct that holds an incident and its related object used for yielding incidents and objects together.
type ReasonKind ¶ added in v1.0.0
type ReasonKind int
ReasonKind classifies why a notification is being sent, driving which default summary/body template is used.
const ( ReasonUpdated ReasonKind = iota ReasonOpened ReasonEscalated ReasonResolved ReasonMuted ReasonUnmuted ReasonManaged ReasonUnmanaged ReasonEvent ReasonIncidentEvent )
type RecipientState ¶
type RecipientState struct {
Role recipient.Role
// EventTypes lists the event types a subscriber or manager wants to be notified about for incident=false events.
// Ignored for RoleRecipient.
EventTypes types.StringList
// IsNew defines whether the associated recipient was added to the incident during the current transaction.
//
// Every recipient loaded from the database isn't new, so IsNew is false. For all other recipients
// added in Incident.AddRecipient due to the ongoing event, IsNew is set true.
IsNew bool
}
type SkippedNotificationHistory ¶ added in v1.0.0
type SkippedNotificationHistory struct {
NotificationID int64 `db:"notification_history_id"`
RuleID int64 `db:"rule_id"`
RuleEntryID int64 `db:"rule_entry_id"`
ContactgroupID types.Int `db:"contactgroup_id"`
ScheduleID types.Int `db:"schedule_id"`
}
SkippedNotificationHistory represents a single skipped_notification_history database entry, recording the path a notification was skipped for a given incident history entry.