Documentation
¶
Overview ¶
Package alert delivers notifications: Shoutrrr and webhook senders, the JSON-safe webhook templates, secret masking and the leader's outbox dispatcher (ADR 0014, FA-ALR-*).
Index ¶
- Constants
- Variables
- func BundleText(ps []cluster.AlertPayload) string
- func BundleTitle(ps []cluster.AlertPayload) string
- func EncryptHeaders(kr Keyring, channelID string, plain, previous map[string]string, keep string) (map[string]string, error)
- func EncryptURL(kr Keyring, channelID, plainURL string) (string, error)
- func MaskURL(raw string) string
- func Redact(msg string, secrets ...string) string
- func Render(tpl string, p cluster.AlertPayload) ([]byte, error)
- func Text(p cluster.AlertPayload) string
- func ValidateTemplate(tpl string) error
- type Applier
- type BundleDeliverer
- type Deliverer
- type DeliveryError
- type Dispatcher
- type DispatcherOptions
- type FlappingWatcher
- type FlappingWatcherOptions
- type Keyring
- type LocalDelivery
- type LocalDispatcher
- type LocalDispatcherOptions
- type Sender
- type Target
Constants ¶
const ( LocalOutcomeSent = "sent" LocalOutcomeFailed = "failed" )
Outcomes reported to LocalDelivery.Done (ADR 0024, section 3). Suppressed alerts never reach the dispatcher.
const ( OutcomeSent = LocalOutcomeSent OutcomeFailed = LocalOutcomeFailed )
OutcomeFailed and OutcomeSent name the outcome of one delivery attempt for OnOutcome (ADR 0025, section 7).
const DefaultTemplate = `{"alertId":"{{alertId}}","event":"{{event}}","status":"{{status}}",` +
`"previousStatus":"{{previousStatus}}","since":"{{since}}","monitor":{"id":"{{monitor.id}}",` +
`"name":"{{monitor.name}}","type":"{{monitor.type}}"},"cause":"{{cause}}","errorClass":"{{errorClass}}",` +
`"incidentId":"{{incidentId}}","reminder":"{{reminder}}","confirmed":"{{confirmed}}",` +
`"verdict":"{{verdict}}","sender":{"nodeId":"{{sender.nodeId}}",` +
`"reachableVoters":"{{sender.reachableVoters}}","totalVoters":"{{sender.totalVoters}}"},` +
`"flapping":"{{flapping}}","changeCount":"{{changeCount}}",` +
`"channel":{"id":"{{channel.id}}","name":"{{channel.name}}","error":"{{channel.error}}"},` +
`"system":{"kind":"{{system.kind}}","subject":"{{system.subject}}","active":"{{system.active}}",` +
`"level":"{{system.level}}"},` +
`"probe":{"id":"{{probe.id}}","name":"{{probe.name}}","active":"{{probe.active}}"},` +
`"message":"{{message}}"}`
DefaultTemplate is used when a webhook has no template.
const Mask = "***"
Mask replaces secrets in display, logs and API responses; in an update it means "keep the stored value".
const OutcomeThrottled = "throttled"
OutcomeThrottled is the outcome of an attempt that the receiver answered with a wait (HTTP 429, Retry-After). It is reported to OnOutcome only.
const SendTimeout = 10 * time.Second
SendTimeout bounds one delivery (ADR 0014).
Variables ¶
var Variables = []string{
"alertId", "event", "status", "previousStatus", "since", "sinceMs", "cause", "errorClass",
"incidentId", "reminder", "confirmed", "message", "monitor.id", "monitor.name", "monitor.type", "tenant.id",
"flapping", "changeCount", "channel.id", "channel.name", "channel.error",
"verdict", "sender.nodeId", "sender.reachableVoters", "sender.totalVoters",
"system.kind", "system.subject", "system.active", "system.level",
"probe.id", "probe.name", "probe.active",
}
Variables lists the placeholders a webhook template may use.
Functions ¶
func BundleText ¶
func BundleText(ps []cluster.AlertPayload) string
BundleText renders several alerts of one Shoutrrr channel as one message: a header and one line per alert with monitor, status or event, and time.
func BundleTitle ¶
func BundleTitle(ps []cluster.AlertPayload) string
BundleTitle is the header and Shoutrrr title of a bundle of alerts (ADR 0023).
func EncryptHeaders ¶
func EncryptHeaders(kr Keyring, channelID string, plain, previous map[string]string, keep string) (map[string]string, error)
EncryptHeaders encrypts webhook header values. Values equal to keep are taken from previous (already encrypted), so an update can leave masked headers unchanged.
func EncryptURL ¶
EncryptURL encrypts a channel URL for the channel ID.
func MaskURL ¶
MaskURL hides credentials of a channel URL for display and logs (FA-ALR-09): user info and path become *** and query values are masked unless they are known to be harmless. Unparsable input is masked completely.
func Redact ¶
Redact removes every secret (at least 4 characters long) and its URL-escaped form from msg, longest first.
func Render ¶
func Render(tpl string, p cluster.AlertPayload) ([]byte, error)
Render fills the template. Placeholders only exist inside JSON strings; a string that is exactly one placeholder becomes the typed value, otherwise the value is inserted as text. The result is re-encoded, so it is valid JSON whatever the values contain (FA-ALR-07, PF-27).
func Text ¶
func Text(p cluster.AlertPayload) string
Text is the human-readable alert used by Shoutrrr and the {{message}} placeholder.
func ValidateTemplate ¶
ValidateTemplate checks that a template is JSON and uses known placeholders only (FA-ALR-07: invalid templates are rejected when saving).
Types ¶
type BundleDeliverer ¶
type BundleDeliverer interface {
SendBundle(ctx context.Context, t Target, ps []cluster.AlertPayload) error
}
BundleDeliverer sends several alerts as one message (ADR 0023). A dispatcher whose sender lacks it never bundles. *Sender satisfies it.
type DeliveryError ¶
type DeliveryError struct {
// Permanent failures are not retried (FA-ALR-05).
Permanent bool
// RetryAfter is the earliest retry requested by the receiver (HTTP 429,
// ADR 0023). Zero means none.
RetryAfter time.Duration
Msg string
}
DeliveryError is a failed delivery. Its message is free of secrets.
func (*DeliveryError) Error ¶
func (e *DeliveryError) Error() string
type Dispatcher ¶
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher delivers due outbox entries and repeats DOWN alerts (ADR 0014). It runs on the leader only; the FSM records every outcome.
func NewDispatcher ¶
func NewDispatcher(opts DispatcherOptions) *Dispatcher
NewDispatcher creates a dispatcher with defaults applied to opts.
func (*Dispatcher) DeliverDue ¶
func (d *Dispatcher) DeliverDue(ctx context.Context) error
DeliverDue sends the outbox entries that are due and records each attempt. It returns after all of them are finished. Entries that the rate limit or a bundling window holds back stay due for a later round.
Entries of suspended tenants are not sent (ADR 0029). They stay pending, so the outbox keeps them, and they are read again in the next round. Because they take up slots of the batch, the next round reads as many more entries as this round skipped; otherwise a suspended tenant with many pending entries would starve the other tenants.
func (*Dispatcher) EnqueueReminders ¶
func (d *Dispatcher) EnqueueReminders(ctx context.Context) error
EnqueueReminders proposes the repeated DOWN alert of every monitor that is still DOWN longer than its resend interval (FA-ALR-02). Each reminder number is proposed once per DOWN period; the FSM ignores duplicates anyway, so proposing again after a restart is safe.
func (*Dispatcher) Run ¶
func (d *Dispatcher) Run(ctx context.Context)
Run calls DeliverDue and EnqueueReminders on their intervals while this node is the leader, until ctx ends.
type DispatcherOptions ¶
type DispatcherOptions struct {
State store.State
Cluster Applier
Keyring Keyring
Sender Deliverer
// IsLeader reports whether this node may propose commands; only the leader dispatches.
IsLeader func() bool
// MaxAttempts is the number of delivery attempts before an alert gives up (default 10).
MaxAttempts int
Logger *slog.Logger
// Now is the clock of the leader (default time.Now). Deliveries and backoff use it.
Now func() time.Time
// Jitter returns a value in [0,1) that spreads retries (default math/rand/v2).
Jitter func() float64
// Interval is the period of DeliverDue (default 2 s).
Interval time.Duration
// ReminderInterval is the period of EnqueueReminders (default 30 s).
ReminderInterval time.Duration
// Concurrency bounds the parallel deliveries (default 4).
Concurrency int
// BatchSize bounds the outbox entries read per DeliverDue (default 50).
BatchSize int
// BundleWindow bundles the alerts of one Shoutrrr channel (ADR 0023). The
// alerts due in the window after a send wait and go out as one message at
// its end. A DOWN alert due in the window does not wait: it sends the due
// alerts at once and leaves the window end as it is (ADR 0026). Zero
// disables bundling.
BundleWindow time.Duration
// OnOutcome is called once per delivery attempt with the kind of the
// channel and the outcome (OutcomeSent, OutcomeThrottled or OutcomeFailed),
// for the delivery metrics (ADR 0025). It may be called concurrently. Nil
// means none.
OnOutcome func(kind, outcome string)
}
DispatcherOptions configures the leader's outbox dispatcher. Zero values select the defaults, except for State, Cluster, Keyring, Sender and IsLeader, which are required.
type FlappingWatcher ¶
type FlappingWatcher struct {
// contains filtered or unexported fields
}
FlappingWatcher proposes ClearMonitorFlapping for monitors that have been quiet for flappingQuiet. The FSM records the end, so a leader change does not lose it (ADR 0023, 4).
func NewFlappingWatcher ¶
func NewFlappingWatcher(opts FlappingWatcherOptions) *FlappingWatcher
NewFlappingWatcher creates a watcher with defaults applied to opts.
func (*FlappingWatcher) Check ¶
func (w *FlappingWatcher) Check(ctx context.Context) error
Check proposes the end of every flapping period that has been quiet long enough. A conflict means the period changed meanwhile, and not_enabled means the cluster is below command level 4; both are normal and not errors.
func (*FlappingWatcher) Run ¶
func (w *FlappingWatcher) Run(ctx context.Context)
Run calls Check on every interval while this node is the leader, until ctx ends.
type FlappingWatcherOptions ¶
type FlappingWatcherOptions struct {
State store.State
// Cluster proposes the commands; a *cluster.Node satisfies it.
Cluster Applier
// IsLeader reports whether this node may propose commands; only the leader runs the check.
IsLeader func() bool
// Now is the clock of the leader (default time.Now).
Now func() time.Time
Logger *slog.Logger
// Interval is the period of Check (default 1 min).
Interval time.Duration
}
FlappingWatcherOptions configures the leader job that ends flapping periods.
type Keyring ¶
type Keyring interface {
Encrypt(plaintext []byte, aad string) (string, error)
Decrypt(ctx context.Context, ciphertext, aad string) ([]byte, error)
}
Keyring encrypts and decrypts channel secrets (*secrets.Keyring, ADR 0011).
type LocalDelivery ¶
type LocalDelivery struct {
// TenantID and ChannelID identify the channel for rate limit and bundling.
TenantID string
ChannelID string
Target Target
Payload cluster.AlertPayload
// Done is called exactly once with LocalOutcomeSent or LocalOutcomeFailed.
// It may be nil.
Done func(outcome string, err error)
}
LocalDelivery is one alert of the degraded mode. It lives in memory only; the caller records the outcome in its own log.
type LocalDispatcher ¶
type LocalDispatcher struct {
// contains filtered or unexported fields
}
LocalDispatcher delivers the alerts of the degraded mode (ADR 0024). It keeps everything in memory and shares the rate limit, Retry-After block, bundling and backoff of the Dispatcher (ADR 0014, 0023, 0026). Deliveries are not at-least-once: a delivery pending at shutdown fails.
func NewLocalDispatcher ¶
func NewLocalDispatcher(opts LocalDispatcherOptions) *LocalDispatcher
NewLocalDispatcher creates a dispatcher with defaults applied to opts.
func (*LocalDispatcher) Enqueue ¶
func (d *LocalDispatcher) Enqueue(del LocalDelivery)
Enqueue adds a delivery. It returns at once; the outcome arrives through Done. A delivery enqueued after Run has ended fails at once.
func (*LocalDispatcher) Run ¶
func (d *LocalDispatcher) Run(ctx context.Context)
Run delivers the pending alerts until ctx ends. On the end, every pending delivery fails with ctx.Err(). Run is meant to be called once.
type LocalDispatcherOptions ¶
type LocalDispatcherOptions struct {
// Sender delivers the alerts. If it also implements BundleDeliverer,
// Shoutrrr alerts can be bundled.
Sender Deliverer
// BundleWindow bundles the Shoutrrr alerts of one channel as in the
// Dispatcher (ADR 0023). A DOWN alert due in the window flushes the due
// alerts at once without moving the window end (ADR 0026). Zero disables
// bundling.
BundleWindow time.Duration
// MaxAttempts is the number of attempts before a delivery fails (default 5).
MaxAttempts int
// Now is the clock (default time.Now).
Now func() time.Time
// Jitter returns a value in [0,1) that spreads retries (default math/rand/v2).
Jitter func() float64
// Interval is the period in which due deliveries are checked (default 500 ms).
Interval time.Duration
// OnOutcome is called once per delivery attempt with the kind of the
// channel and the outcome (see DispatcherOptions.OnOutcome). Nil means none.
OnOutcome func(kind, outcome string)
// Suspended reports whether a tenant is suspended (ADR 0029). Pending
// deliveries of suspended tenants are dropped without a send. Nil means none.
Suspended func(tenantID string) bool
Logger *slog.Logger
}
LocalDispatcherOptions configures a LocalDispatcher. Zero values select the defaults, except for Sender, which is required.
type Sender ¶
type Sender struct {
// contains filtered or unexported fields
}
Sender delivers alerts through the central dialer, so check and notification targets share the SSRF policy (FA-ALR-12).
func (*Sender) SendBundle ¶
SendBundle delivers several alerts as one message (ADR 0023). Only Shoutrrr channels are bundled; webhooks get one request per alert.
type Target ¶
type Target struct {
Kind string
URL string
Method string
Headers map[string]string
Template string
}
Target is a decrypted channel. It only lives in memory during a delivery.
func DecryptTarget ¶
DecryptTarget turns a stored channel into a Target with plaintext secrets. The result must only be used for one delivery and never be logged.