Documentation
¶
Overview ¶
Package ingest is the ingestion of C-05 on the ingest listener: it takes a webhook with an Integration token, stores its body exactly as received as a pending Stored Snapshot in one short insert-only transaction and answers 202 once it committed (ADR-0002). It reads the Stored Snapshots for the API. Processing them is C-06.
Index ¶
- Constants
- Variables
- func AlertmanagerRoutePath(groupKey string) string
- func Backlog(ctx context.Context, q ProcessQueries, orgs []int64) error
- func DeletedReasonText(name string) string
- func EffectiveClock(clockMs int64, state string, lastSignal *time.Time, timeout time.Duration, ...) int64
- func Fingerprint(labels map[string]string) string
- func NewHandler(cfg HandlerConfig) http.Handler
- func PruneAlerts(ctx context.Context, q ProcessQueries, orgID int64, now time.Time) (int64, error)
- func RouteSnippet(routePath string, learned time.Duration) string
- func StaleAfter(learned *time.Duration) time.Duration
- type AlertChange
- type AlertFilter
- type AlertGroupRef
- type AlertPage
- type AlertPosition
- type AlertmanagerRoute
- type AlertsView
- type Authenticator
- type ChangeKind
- type Claimed
- type FiringAlert
- type FiringRead
- type HandlerConfig
- type ListFilter
- type Notification
- type Page
- type Payload
- type PayloadAlert
- type PayloadError
- type Position
- type ProcessQueries
- type ProcessStore
- type Processor
- type ProcessorConfig
- type Queries
- type Received
- type Ref
- type Replay
- type ReplayQueries
- type ReplayStore
- type Replayed
- type Replayer
- type RouteRef
- type Routed
- type Service
- func (s *Service) Firing(ctx context.Context, since time.Time, visit func([]FiringAlert) bool) (FiringRead, error)
- func (s *Service) Get(ctx context.Context, publicID string) (Snapshot, error)
- func (s *Service) List(ctx context.Context, f ListFilter) (Page, error)
- func (s *Service) Retention(ctx context.Context) (time.Duration, error)
- func (s *Service) Store(ctx context.Context, r Received) (Stored, error)
- type Sink
- type Snapshot
- type Stats
- type Store
- type Stored
- type Storer
- type Summary
- type ViewAlert
- type Worker
Constants ¶
const ( SortLastSeen = "last_seen_at" SortLastSeenDesc = "-last_seen_at" SortStarts = "starts_at" SortStartsDesc = "-starts_at" )
The sorts of the Alerts view; a leading - sorts descending.
const ( RouteHeader = "/api/v1/ingest" RoutePath = "/api/v1/ingest/{ingest_token}" )
The routes of ingestion, as log lines name them: never the path, which may carry the token (C-05.FR-3).
const ( OutcomeAccepted = "accepted" OutcomeTooLarge = "too_large" )
The outcomes of muster_ingest_requests_total.
const ( ReasonRepeat = "repeat interval elapsed" ReasonAllResolved = "all alerts resolved" )
The values of notification_reason that processing reads (Alertmanager v0.32 and later, F-050).
const ( StatusFiring = "firing" StatusResolved = "resolved" )
The statuses of a Snapshot and of its Alerts.
const ( PresenceListed = "listed" PresenceMissed = "missed" PresenceGone = "gone" PresenceStale = "stale" )
The states of an Alert's presence in a groupKey.
const ( SourceWebhook = "webhook" SourceInternal = "internal" )
The sources of a Stored Snapshot: a webhook received on the ingest listener, or a synthetic one that raises or resolves an Internal alert or marks the deletion of an Integration.
const ( ResolveResolved = "resolved" ResolveGone = "gone" ResolveStale = "stale" ResolveIntegrationDeleted = "integration_deleted" )
The reasons an Alert resolves (NullableResolveReason).
const ( // RepeatSamples is processing.repeat_samples: the learned repeat interval is the median of the last 9 gaps. RepeatSamples = 9 // StaleAfterFactor is processing.stale_after_factor and StaleAfterUnlearned processing.stale_after_unlearned. StaleAfterFactor = 3 StaleAfterUnlearned = 25 * time.Hour )
The repeat settings of defaults.md.
const ( StatePending = "pending" StateProcessed = "processed" StateFailed = "failed" )
The processing states of a Stored Snapshot.
const ( // Poll is how often the worker looks for pending Stored Snapshots when no notification woke it. Poll = 5 * time.Second // Lease is how long a claim holds an Integration on the real clock; the worker that holds it renews it every // renewEvery while it processes. Lease = 30 * time.Second // Concurrency is how many Integrations one replica processes at the same time, so that a backlog of one never // holds up the others. Concurrency = 4 // ParallelGroups is processing.parallel_groups (P-49): how many Alertmanager groups of one Integration are // processed at the same time, each in arrival order (C-06.FR-1). ParallelGroups = 2 )
The pace of the processing worker (C-06.FR-1).
const ActionReplayed = "ingest.replayed"
ActionReplayed is the Audit log action of muster ingest replay.
const BodyLimit = 16 << 20
BodyLimit is ingest.body_limit: the largest body ingestion stores.
const GoneMinAbsence = 5 * time.Minute
GoneMinAbsence is processing.gone_min_absence: an Alert missing from consecutive Snapshots of its groupKey is Gone there once a Snapshot arrives this long after the first that missed it.
const GoneReasonText = "Alertmanager no longer reports this alert — it resolved without notice, was silenced or " +
"inhibited in Alertmanager, or the Alertmanager routing changed"
GoneReasonText is the reason of an Alert resolved as Gone or Stale (C-06.FR-10).
const RetentionBatch = 5000
RetentionBatch is the most Alerts one delete of the Alerts view retention removes, so that each statement holds its row locks briefly.
const SnapshotChannel = "muster_snapshots"
SnapshotChannel is the LISTEN/NOTIFY channel that wakes the processing workers when a Stored Snapshot was stored; the payload is a Notification.
Variables ¶
var ErrNotFound = errors.New("no such stored snapshot")
ErrNotFound is a Stored Snapshot that does not exist in the Organization or is older than retention.stored_snapshots.
var ErrUnknownIntegration = errors.New("no integration has this name")
ErrUnknownIntegration is a --integration that names no Integration that is not deleted.
var ResolveReasons = []string{ResolveResolved, ResolveGone, ResolveStale, ResolveIntegrationDeleted}
ResolveReasons are every reason, as muster_alerts_resolved_total declares them.
Functions ¶
func AlertmanagerRoutePath ¶
AlertmanagerRoutePath is the Alertmanager route of a groupKey: the part before the group labels, `{}/{team="db"}` of `{}/{team="db"}:{alertname="DiskFull"}`. A colon inside a quoted value or inside braces does not count; a groupKey without a separating colon is its own route path.
func Backlog ¶
func Backlog(ctx context.Context, q ProcessQueries, orgs []int64) error
Backlog sets muster_ingest_backlog to the pending Stored Snapshots of the Organizations, as a Leader task.
func DeletedReasonText ¶
DeletedReasonText is the reason of an Alert resolved because its Integration was deleted (C-06.FR-16).
func EffectiveClock ¶
func EffectiveClock(clockMs int64, state string, lastSignal *time.Time, timeout time.Duration, at time.Time) int64
EffectiveClock is the liveness clock of an Integration at the business time at (schema.md 4.7): the stored clock, plus the time since the last Heartbeat signal while the Heartbeat is live and that time is at most the timeout. Time with the Heartbeat lost or off, and a gap longer than the timeout — Muster's own downtime among them — never counts (C-06.FR-9, C-07.FR-5). A time before the last signal takes the stored clock, which then runs slightly ahead.
func Fingerprint ¶
Fingerprint is the fingerprint Alertmanager gives a label set: FNV-1a over the label names in order, each name and value followed by the byte 0xff, written as 16 hexadecimal digits.
func NewHandler ¶
func NewHandler(cfg HandlerConfig) http.Handler
NewHandler is the handler of the ingest listener: the two ingestion routes with POST, and 404 for every other request, as the API answers a path or a method it has no operation for, until the Heartbeat and the messenger callbacks arrive.
func PruneAlerts ¶
PruneAlerts deletes, in batches of at most RetentionBatch, the Alerts of the Organization orgID resolved longer than retention.alert_details before now, their presences going with them (C-06.FR-19, design/db/schema.md §6), and returns how many it deleted. A Leader task runs it hourly; running it twice deletes nothing more, because each delete only takes rows that already qualify.
func RouteSnippet ¶
RouteSnippet is the Alertmanager route fragment that sets snippet.repeat_interval on the route of routePath, with the matchers of each level below the top-level route, for a route whose learned repeat interval is learned. The route path comes from a received groupKey, so it and every matcher are written as double-quoted YAML scalars in ASCII with escapes: no character of the groupKey can end a comment or a scalar.
Types ¶
type AlertChange ¶
type AlertChange struct {
Kind ChangeKind
AlertID int64
Fingerprint string
Episode int64
StoredSnapshotID int64
// Reason and ReasonText are set on a ChangeResolved.
Reason string
ReasonText string
}
AlertChange is one change of an Alert, made by the Stored Snapshot StoredSnapshotID.
type AlertFilter ¶
type AlertFilter struct {
Integration string
State string
Matchers []matchers.Matcher
Query string
Sort string
After *AlertPosition
Limit int
}
AlertFilter selects a page of the Alerts view of the Integration whose public_id is Integration: in State when it is set, matching every Matcher, with a label value containing Query (case-insensitive) when it is set, sorted by Sort, after the position After when it is set.
type AlertGroupRef ¶
AlertGroupRef names an Alert Group by its public_id and #N.
type AlertPage ¶
type AlertPage struct {
Alerts []ViewAlert
Next *AlertPosition
}
AlertPage is a page of the Alerts view; Next, the position to continue after, is nil on the last page.
type AlertPosition ¶
AlertPosition is the sort key of an Alert in the view: the sorted time and the id.
type AlertmanagerRoute ¶
type AlertmanagerRoute struct {
RoutePath string
// LearnedRepeatInterval is nil before an interval is learned, and in whole seconds; ResolveByAbsenceAfter is
// stale_after of that interval.
LearnedRepeatInterval *time.Duration
ResolveByAbsenceAfter time.Duration
TruncatedGroupCount int64
// LongIntervalWarning is a learned interval above processing.long_repeat_warning; RecommendedSnippet, set with it,
// is the route with snippet.repeat_interval.
LongIntervalWarning bool
RecommendedSnippet string
}
AlertmanagerRoute is an Alertmanager route Muster learned from the groupKeys of an Integration (C-06.FR-18).
type AlertsView ¶
type AlertsView struct {
// contains filtered or unexported fields
}
AlertsView reads the Alerts view of the Integrations of an Organization (C-06.FR-19) and their learned Alertmanager routes (C-06.FR-18).
func NewAlertsView ¶
func NewAlertsView(orgID int64, store ProcessQueries, business clock.Clock) *AlertsView
NewAlertsView returns the Alerts view of the Organization orgID; business is the business clock, which decides the retention of resolved Alerts.
func (*AlertsView) List ¶
func (v *AlertsView) List(ctx context.Context, f AlertFilter) (AlertPage, error)
List lists the Alerts of an Integration that is not deleted: firing ones and those resolved within retention.alert_details. Matchers with = and a value are given to the database to narrow the scan; every Matcher and the text are then matched against each Alert's labels, the batches continuing until the page is full.
func (*AlertsView) Routes ¶
func (v *AlertsView) Routes(ctx context.Context, integration string) ([]AlertmanagerRoute, error)
Routes lists the Alertmanager routes of the Integration integration, which is not deleted, in the order of their paths; an unknown Integration is integrations.ErrNotFound. The built-in Integration has none: its synthetic Snapshots are never resolved by absence and teach nothing.
type Authenticator ¶
type Authenticator interface {
Authenticate(ctx context.Context, value string) (integrations.Caller, error)
}
Authenticator finds who sends an ingestion request by its token: internal/integrations.
type ChangeKind ¶
type ChangeKind string
ChangeKind is the kind of an Alert change (C-06.FR-3).
const ( // ChangeFired is a new firing: a fingerprint not seen before, or one that fires again after it resolved. ChangeFired ChangeKind = "fired" // ChangeResolved is a resolution, with its reason and text. ChangeResolved ChangeKind = "resolved" // ChangeContinued is a Continuation: a new startsAt without a resolve in between (C-06.FR-11). ChangeContinued ChangeKind = "continued" // ChangeAnnotations is a change in the annotations of a firing Alert (C-06.FR-12). ChangeAnnotations ChangeKind = "annotations_changed" // ChangeListed is no change: a firing Alert that the Snapshot lists without firing it. It is handed over so that // every firing Alert gets its Route and its Alert Group, also one that fired before routing or grouping took it, // or whose grouping a failure or a configuration change left undone; Alerts that have both ignore it. ChangeListed ChangeKind = "listed" )
The Alert changes processing emits.
type FiringAlert ¶
FiringAlert is an Alert reported firing in a Stored Snapshot, with the current Static labels of its Integration applied as processing applies them.
type FiringRead ¶
FiringRead is how a read of the firing Alerts ended: Bodies is how many distinct bodies it read, and Unread whether it stopped with Stored Snapshots of the period left unread.
type HandlerConfig ¶
type HandlerConfig struct {
Auth Authenticator
Snapshots Storer
Log *logging.Logger
// Real is the real clock, for the request durations.
Real clock.Clock
// TrustedProxies are MUSTER_TRUSTED_PROXIES, for the client address.
TrustedProxies []netip.Prefix
// BodyLimit is ingest.body_limit; zero takes BodyLimit.
BodyLimit int64
}
HandlerConfig is what the ingestion handler serves with.
type ListFilter ¶
type ListFilter struct {
Integration string
From, To *time.Time
States []string
After *Position
Limit int
}
ListFilter selects a page of the Stored Snapshots of the Integration whose public_id is Integration, received in [From, To) and in States when they are set, after the position After when it is set.
type Notification ¶
type Notification struct {
OrgID int64 `json:"org_id"`
IntegrationID int64 `json:"integration_id"`
}
Notification is the payload of a notification on SnapshotChannel: the Integration whose pending Stored Snapshots grew.
type Page ¶
Page is a page of Stored Snapshots, newest first; Next, the position to continue after, is nil on the last page.
type Payload ¶
type Payload struct {
GroupKey string
Status string
TruncatedAlerts int64
// Reason is notification_reason; HasReason is false for an Alertmanager that does not send it, and for Grafana.
Reason string
HasReason bool
// Grafana marks a Snapshot from Grafana: its body has a top-level orgId that is not null, which Grafana always
// sends and Alertmanager never does (C-06.FR-21).
Grafana bool
Alerts []PayloadAlert
}
Payload is an Alertmanager webhook as processing reads it (AlertmanagerWebhook in the API specification), from Alertmanager or from the webhook contact point of Grafana Alerting, whose built-in Alertmanager sends the same format with additions (F-105).
func ParsePayload ¶
ParsePayload reads an Alertmanager webhook. groupKey, status and alerts are required, and every Alert needs labels, status and startsAt; truncatedAlerts, notification_reason and fingerprint are optional (C-06.FR-20). Anything else is a *PayloadError that names what is wrong.
The parser is tolerant, so that Grafana's webhook contact point is read as it is (F-105): version is not read ("4" from Alertmanager, "1" from Grafana), and unknown fields are ignored — Grafana's top-level title, message, state and appVersion, and per alert values (an object or null), valueString, silenceURL, dashboardURL, panelURL, ruleUID, orgId and imageURL included. Grafana sends no notification_reason and no routeLabels, so HasReason is false and repeats are learned from identical Snapshots (C-06.FR-8, F-108). The top-level orgId is read as raw JSON, so that its type never fails a body. fingerprint is taken from the body: Grafana's covers the hidden label __alert_rule_uid__ (F-107), so Fingerprint, used only for a body without one, never stands in for it. generatorURL is kept as it is, for Grafana the rule's page.
type PayloadAlert ¶
type PayloadAlert struct {
Fingerprint string
Status string
Labels map[string]string
Annotations map[string]string
StartsAt time.Time
EndsAt *time.Time
GeneratorURL string
}
PayloadAlert is one Alert of a Payload. Fingerprint is the payload's, or computed from the labels as received.
type PayloadError ¶
type PayloadError struct {
// contains filtered or unexported fields
}
PayloadError is a body that is not an Alertmanager webhook; its text is the processing_error of the failed Stored Snapshot.
func (*PayloadError) Error ¶
func (e *PayloadError) Error() string
type Position ¶
Position is the sort key of a Stored Snapshot in the list: newest first by receipt time, then by id.
type ProcessQueries ¶
type ProcessQueries interface {
GetRetention(ctx context.Context, orgID int64) (int64, error)
ListPendingIntegrations(ctx context.Context, arg dbgen.ListPendingIntegrationsParams) ([]int64, error)
EnsureIngestClaims(ctx context.Context, arg dbgen.EnsureIngestClaimsParams) error
ReleaseIngestClaim(ctx context.Context, arg dbgen.ReleaseIngestClaimParams) error
RenewIngestLease(ctx context.Context, arg dbgen.RenewIngestLeaseParams) (dbgen.RenewIngestLeaseRow, error)
CheckIngestLease(ctx context.Context, arg dbgen.CheckIngestLeaseParams) (dbgen.CheckIngestLeaseRow, error)
ListPendingSnapshots(ctx context.Context, arg dbgen.ListPendingSnapshotsParams) ([]dbgen.ListPendingSnapshotsRow,
error)
FinishSnapshot(ctx context.Context, arg dbgen.FinishSnapshotParams) (bool, error)
CountSnapshot(ctx context.Context, arg dbgen.CountSnapshotParams) error
UpsertAlertmanagerRoute(ctx context.Context, arg dbgen.UpsertAlertmanagerRouteParams) (int64, error)
TouchAlertmanagerRoute(ctx context.Context, arg dbgen.TouchAlertmanagerRouteParams) error
LockAlertmanagerRoute(ctx context.Context, arg dbgen.LockAlertmanagerRouteParams) (dbgen.LockAlertmanagerRouteRow,
error)
UpsertAlertmanagerGroup(ctx context.Context, arg dbgen.UpsertAlertmanagerGroupParams) (
dbgen.UpsertAlertmanagerGroupRow, error)
UpdateAlertmanagerGroup(ctx context.Context, arg dbgen.UpdateAlertmanagerGroupParams) error
UpdateRepeatInterval(ctx context.Context, arg dbgen.UpdateRepeatIntervalParams) error
ListSnapshotAlerts(ctx context.Context, arg dbgen.ListSnapshotAlertsParams) ([]dbgen.ListSnapshotAlertsRow, error)
ListActivePresences(ctx context.Context, arg dbgen.ListActivePresencesParams) ([]dbgen.ListActivePresencesRow,
error)
InsertAlerts(ctx context.Context, arg dbgen.InsertAlertsParams) ([]dbgen.InsertAlertsRow, error)
UpdateAlerts(ctx context.Context, arg dbgen.UpdateAlertsParams) error
UpsertListedPresences(ctx context.Context, arg dbgen.UpsertListedPresencesParams) error
MarkPresencesMissed(ctx context.Context, arg dbgen.MarkPresencesMissedParams) error
EndPresences(ctx context.Context, arg dbgen.EndPresencesParams) error
CountPendingSnapshots(ctx context.Context, orgID int64) (int64, error)
CountTruncatedGroups(ctx context.Context, arg dbgen.CountTruncatedGroupsParams) (int64, error)
ResolveIntegrationAlerts(ctx context.Context, arg dbgen.ResolveIntegrationAlertsParams) (
[]dbgen.ResolveIntegrationAlertsRow, error)
ClearTruncation(ctx context.Context, arg dbgen.ClearTruncationParams) (int64, error)
LockIntegrationName(ctx context.Context, arg dbgen.LockIntegrationNameParams) (string, error)
ListLiveIntegrations(ctx context.Context, orgID int64) ([]int64, error)
HasPendingSnapshots(ctx context.Context, arg dbgen.HasPendingSnapshotsParams) (bool, error)
ListStalePresences(ctx context.Context, arg dbgen.ListStalePresencesParams) ([]dbgen.ListStalePresencesRow, error)
MarkPresencesStale(ctx context.Context, arg dbgen.MarkPresencesStaleParams) error
ResolveStaleAlerts(ctx context.Context, arg dbgen.ResolveStaleAlertsParams) ([]dbgen.ResolveStaleAlertsRow, error)
ExpireTruncation(ctx context.Context, arg dbgen.ExpireTruncationParams) (int64, error)
internalalerts.Store
// contains filtered or unexported methods
}
ProcessQueries are the queries of processing and of the Alerts view; *dbgen.Queries implements them.
type ProcessStore ¶
type ProcessStore interface {
ProcessQueries
// InTx runs f in one transaction; tx is the transaction itself, for the Sink.
InTx(ctx context.Context, f func(q ProcessQueries, tx dbgen.DBTX) error) error
// ClaimIntegrations leases at most limit of the Integrations ids of the Organization orgID with the shared claim
// of internal/db and returns those it leased.
ClaimIntegrations(ctx context.Context, l db.Lease, orgID int64, ids []int64, limit int32) ([]Claimed, error)
}
ProcessStore runs the queries of processing alone or in one transaction, and claims Integrations.
func NewProcessStore ¶
func NewProcessStore(pool *pgxpool.Pool) ProcessStore
NewProcessStore is the ProcessStore over the main pool.
type Processor ¶
type Processor struct {
// contains filtered or unexported fields
}
Processor processes the Stored Snapshots of one Organization (C-06.FR-1): per Integration under a lease, in arrival order per Alertmanager group, up to lanes Alertmanager groups at the same time, one transaction per Snapshot.
func NewProcessor ¶
func NewProcessor(cfg ProcessorConfig) *Processor
NewProcessor returns the Processor of an Organization.
func (*Processor) Drain ¶
Drain processes every pending Stored Snapshot of the Organization that this replica can claim, one Integration after the other, and returns once none is left; tests and the worker's rounds use it.
func (*Processor) ProcessPending ¶
ProcessPending processes the pending Stored Snapshots of an Integration whose lease this replica holds until none is left, the lease is lost or ctx ends, and returns how many it processed or marked failed. Snapshots of one Alertmanager group are processed oldest first and one at a time, up to p.lanes Alertmanager groups at the same time (C-06.FR-1); a Snapshot that cannot be processed is marked failed and does not stop the ones behind it (C-06.FR-20); a lost connection leaves it pending. It renews the lease while it runs.
func (*Processor) StaleScan ¶
StaleScan is the Leader's Stale scan of the Organization (C-06.FR-6 to FR-10, C-07.FR-5), in the Processor's Organization: for each Integration whose Heartbeat is live, one after the other, it takes the Integration's ingestion claim, so that it never runs beside the Integration's processing, and in one transaction makes Stale every active presence whose reference is more than stale_after of its Alertmanager route behind the liveness clock, resolves as Stale the Alerts left without an active presence, and ends the truncation of the groupKeys whose last Snapshot is as far behind. An Integration claimed by its processing, or with Stored Snapshots still waiting for it, waits for the next scan. Running it twice changes nothing more.
type ProcessorConfig ¶
type ProcessorConfig struct {
OrgID int64
Store ProcessStore
// Business is the business clock: receipt times, processing times and retention.
Business clock.Clock
// Lease names this replica and holds a claimed Integration on the real clock.
Lease db.Lease
Log *logging.Logger
// Sink takes the Alert changes; nil records them on the Alerts only.
Sink Sink
// RunbookBase is MUSTER_RUNBOOK_BASE_URL, the base of the runbook_url of the Internal alerts processing raises.
RunbookBase string
// Lanes is how many Alertmanager groups of one Integration are processed at the same time; 0 is ParallelGroups.
Lanes int
}
ProcessorConfig is what a Processor works with.
type Queries ¶
type Queries interface {
InsertSnapshotBody(ctx context.Context, arg dbgen.InsertSnapshotBodyParams) error
InsertStoredSnapshot(ctx context.Context, arg dbgen.InsertStoredSnapshotParams) error
NotifySnapshot(ctx context.Context, arg dbgen.NotifySnapshotParams) error
GetRetention(ctx context.Context, orgID int64) (int64, error)
FindSnapshotIntegration(ctx context.Context, arg dbgen.FindSnapshotIntegrationParams) (
dbgen.FindSnapshotIntegrationRow, error)
ListStoredSnapshots(ctx context.Context, arg dbgen.ListStoredSnapshotsParams) ([]dbgen.ListStoredSnapshotsRow, error)
GetStoredSnapshot(ctx context.Context, arg dbgen.GetStoredSnapshotParams) (dbgen.GetStoredSnapshotRow, error)
ListPreviewIntegrations(ctx context.Context, orgID int64) ([]dbgen.ListPreviewIntegrationsRow, error)
ListPreviewBodies(ctx context.Context, arg dbgen.ListPreviewBodiesParams) ([]dbgen.ListPreviewBodiesRow, error)
ListPreviewSnapshotBodies(ctx context.Context, arg dbgen.ListPreviewSnapshotBodiesParams) (
[]dbgen.ListPreviewSnapshotBodiesRow, error)
}
Queries are the queries of the package.
type Received ¶
Received is a webhook body to store for an Integration, with the request's Content-Type, if any.
type Replay ¶
Replay is what muster ingest replay asks for: the period back from now, as given and as a duration, the name of one Integration or empty for all, and the --actor name.
type ReplayQueries ¶
type ReplayQueries interface {
GetRetention(ctx context.Context, orgID int64) (int64, error)
FindReplayIntegration(ctx context.Context, arg dbgen.FindReplayIntegrationParams) (
dbgen.FindReplayIntegrationRow, error)
ReplaySnapshots(ctx context.Context, arg dbgen.ReplaySnapshotsParams) ([]int64, error)
NotifySnapshot(ctx context.Context, arg dbgen.NotifySnapshotParams) error
audit.Store
}
ReplayQueries are the queries of a replay, with the insert of the Audit log.
type ReplayStore ¶
type ReplayStore interface {
InTx(ctx context.Context, f func(ReplayQueries) error) error
}
ReplayStore runs a replay in one transaction.
func NewReplayStore ¶
func NewReplayStore(pool *pgxpool.Pool) ReplayStore
NewReplayStore is the ReplayStore over the main pool.
type Replayed ¶
Replayed is what a replay did: how many Stored Snapshots it set back to pending, and the Integration when it was limited to one.
type Replayer ¶
type Replayer struct {
OrgID int64
Store ReplayStore
Audit *audit.Writer
Log *logging.Logger
// Business is the business clock: the period counts back from its now.
Business clock.Clock
}
Replayer replays the Stored Snapshots of an Organization (C-06.FR-17).
func (*Replayer) Replay ¶
Replay sets the Stored Snapshots received within the period and within retention.stored_snapshots, of one Integration or of all, back to pending in one transaction: it clears processed_at and processing_error, marks them replayed so that processing does not count them on their Integration again, wakes the workers and records ingest.replayed in the Audit log. The workers then process them in arrival order as late Snapshots, so those already processed change nothing and one that failed is processed with the current code.
type Routed ¶
type Routed struct {
IDs []int64
PublicIDs []string
AlertGroups []int64
Committed func(ctx context.Context)
}
Routed names the Routes that took Alerts of the changes: their ids, which the Stored Snapshot keeps in route_ids, and their public_ids, which its log line carries, in evaluation order. AlertGroups are the #N of the Alert Groups that grouping created or changed, and Committed, when set, counts and logs what the changes did once the transaction committed.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service stores and reads the Stored Snapshots of the Organization.
func New ¶
New returns the Service of the Organization orgID; business is the business clock, which dates the Stored Snapshots and decides their retention.
func (*Service) Firing ¶
func (s *Service) Firing(ctx context.Context, since time.Time, visit func([]FiringAlert) bool) (FiringRead, error)
Firing reads the webhook Stored Snapshots received since since that did not fail, newest first and each distinct body of an Integration once, and calls visit with the Alerts each reports firing, the Integration's current Static labels applied; a body that does not parse, or that has none firing, is skipped. visit returns false to stop the read. It reads a bounded number of rows and bodies at a time, whatever the period holds.
func (*Service) Get ¶
Get reads the Stored Snapshot publicID with its body; one older than retention.stored_snapshots is ErrNotFound.
func (*Service) List ¶
List lists the Stored Snapshots of an Integration, a deleted one included, newest first; an unknown Integration has none.
func (*Service) Retention ¶
Retention is retention.stored_snapshots: how long the Organization keeps its Stored Snapshots.
func (*Service) Store ¶
Store stores a body as a pending Stored Snapshot in one transaction: the body once per Organization and UTC day, the Stored Snapshot received now on the business clock, and the notification that wakes processing, sent at the commit. It parses nothing and updates no other row.
type Sink ¶
type Sink interface {
AlertChanges(ctx context.Context, tx dbgen.DBTX, changes []AlertChange) (Routed, error)
}
Sink takes the Alert changes of a Snapshot inside the Snapshot's transaction, tx, which it may write through; an error rolls the Snapshot back. Routing (C-08) attaches here and says which Routes took the newly firing Alerts; grouping (C-09) follows it. A Snapshot also hands over its firing Alerts that did not fire in it, as ChangeListed.
type Snapshot ¶
Snapshot is a Stored Snapshot with its body exactly as received and the request's Content-Type, if any.
type Stats ¶
type Stats struct {
Alerts, Fired, Resolved, Gone, Continued, Dropped, Deleted int
Truncated int64
}
Stats count what one Snapshot did, for its log line and the metrics; Deleted are the Alerts the deletion of their Integration resolved.
type Stored ¶
type Stored struct {
PublicID string
}
Stored is what storing a body made: the public_id of the Stored Snapshot.
type Summary ¶
type Summary struct {
ID int64
PublicID string
Integration Ref
ReceivedAt time.Time
ProcessedAt *time.Time
SizeBytes int64
State string
ProcessingError *string
GroupKey *string
AlertCount *int64
TruncatedAlerts *int64
}
Summary is a Stored Snapshot as the list shows it.
type ViewAlert ¶
type ViewAlert struct {
ID int64
Fingerprint string
Labels map[string]string
Annotations map[string]string
State string
Reason *string
ReasonText *string
StartsAt time.Time
ResolvedAt *time.Time
LastSeenAt time.Time
// GroupKeys are the groupKeys that listed it during its current or last firing; Warnings the Static labels it
// already carried.
GroupKeys []string
Warnings []string
// Route is the Route that took its current or last firing, nil before routing; SeverityLevel its Severity level
// and SeverityRaw the severity value as received when it has no mapping (C-06.FR-19, C-08.FR-13).
Route *RouteRef
SeverityLevel *string
SeverityRaw *string
// AlertGroup is the Alert Group it fires in, or last fired in; nil before grouping (C-06.FR-19).
AlertGroup *AlertGroupRef
}
ViewAlert is an Alert as the view shows it (IntegrationAlert).
type Worker ¶
type Worker struct {
// Organizations lists the Organizations; Processor is the Processor of one, false to skip it.
Organizations func(ctx context.Context) ([]int64, error)
Processor func(orgID int64) (*Processor, bool)
Log *logging.Logger
// Poll and Concurrency default to Poll and Concurrency.
Poll time.Duration
Concurrency int
// Real is the real clock that paces the retries of an Integration whose processing failed; nil is the system
// time.
Real clock.Clock
// contains filtered or unexported fields
}
Worker is the processing worker of a replica (C-06.FR-1): woken by the notification of each stored Snapshot and polling every Poll as a fallback, it claims Integrations with pending Stored Snapshots in every Organization and processes up to Concurrency of them at the same time, each until its pending Snapshots are done; then it releases the lease. Shutdown stops the claims and releases the leases it holds.