Documentation
¶
Index ¶
- Constants
- Variables
- func CheckHeaders(headers string) error
- func EvalExpression(prog Program, env Env) (bool, error)
- func FireWebhook(rule Rule, ctx ActionContext) (string, error)
- func RenderTemplate(tmplStr string, ctx ActionContext) (string, error)
- func SafeEval(prog Program, env Env) (result bool, err error)
- type ActionContext
- type Alert
- type EmailConfig
- type EmailOptions
- type Engine
- func (e *Engine) DisableRule(rule Rule)
- func (e *Engine) EmailOptions() EmailOptions
- func (e *Engine) EnableEmail(cfg EmailConfig)
- func (e *Engine) RecompileRule(ruleID, expression string) error
- func (e *Engine) RemoveRule(ruleID string)
- func (e *Engine) Run(ctx context.Context)
- func (e *Engine) Test(ctx context.Context, rule Rule) ([]TestResult, error)
- func (e *Engine) WithEmailState(rule Rule) Rule
- type Env
- type Program
- type Rule
- type Store
- func (s *Store) AlertSummary() (Summary, error)
- func (s *Store) CreateRule(r Rule) (Rule, error)
- func (s *Store) DeleteAlert(id string) error
- func (s *Store) DeleteRule(id string) error
- func (s *Store) GetAlert(ruleID, service string) (Alert, error)
- func (s *Store) GetRule(id string) (Rule, error)
- func (s *Store) ListAlerts(state, service, ruleID string) ([]Alert, error)
- func (s *Store) ListEnabledRules() ([]Rule, error)
- func (s *Store) ListRules() ([]Rule, error)
- func (s *Store) PruneResolved(days int) (int64, error)
- func (s *Store) ReplaceRule(r Rule) (Rule, error)
- func (s *Store) UpdateDeliveryStatus(id, status, deliveredAt string) error
- func (s *Store) UpsertAlert(a Alert) (Alert, error)
- func (s *Store) UpsertAlertWithEmail(a Alert, recipients []string, content emailContent, now time.Time) (Alert, error)
- type Summary
- type TestResult
Constants ¶
EmailUnavailableMessage explains why email cannot be chosen or delivered.
Variables ¶
var ErrNotFound = errors.New("not found")
ErrNotFound is returned when a requested record does not exist.
Functions ¶
func CheckHeaders ¶
CheckHeaders reports whether headers is empty or a JSON object of valid HTTP header names and string values, naming the first header that is not. A value is never echoed, since it may hold a credential.
func EvalExpression ¶
EvalExpression runs a compiled program with the given environment.
func FireWebhook ¶
func FireWebhook(rule Rule, ctx ActionContext) (string, error)
FireWebhook sends the webhook for the given rule. Returns "skipped" if no URL is configured, "success" on 2xx, or "failed" after exhausting retries.
Custom headers are parsed from rule.WebhookHeaders as a JSON object (e.g. {"Authorization":"Bearer token"}).
Retries: up to 3 attempts with linear backoff (0s, 2s, 4s) for 5xx responses. 4xx responses are not retried.
func RenderTemplate ¶
func RenderTemplate(tmplStr string, ctx ActionContext) (string, error)
RenderTemplate renders tmplStr against ctx using Go text/template. If tmplStr is empty, the defaultTemplate is used.
Types ¶
type ActionContext ¶
type ActionContext struct {
Rule Rule `json:"rule"`
Alert Alert `json:"alert"`
Env Env `json:"env"`
Event string `json:"event"`
Time time.Time `json:"time"`
}
ActionContext is passed to webhook templates and delivery logic.
type Alert ¶
type Alert struct {
ID string `json:"id"`
RuleID string `json:"rule_id"`
Service string `json:"service"`
State string `json:"state"`
Value float64 `json:"value"` // The first variable the rule reads, at the last evaluation
FiredAt string `json:"fired_at,omitempty"`
ResolvedAt string `json:"resolved_at,omitempty"`
RepeatedAt string `json:"repeated_at,omitempty"`
LastEvaluatedAt string `json:"last_evaluated_at,omitempty"`
LastDeliveryStatus string `json:"last_delivery_status,omitempty"`
LastDeliveryAt string `json:"last_delivery_at,omitempty"`
CreatedAt string `json:"created_at"`
}
Alert represents the current state of an alert instance for a (rule, service) pair.
type EmailConfig ¶
type EmailConfig struct {
Send func(context.Context, auth.AlertMail) error
Defaults []string // Addresses for rules with no destination of their own.
HourlyLimit int // Emails per address per rolling hour, across all rules.
}
EmailConfig enables alert email on an Engine.
type EmailOptions ¶
type EmailOptions struct {
Available bool `json:"available"`
Message string `json:"message,omitempty"`
DefaultDestination bool `json:"default_destination"`
MaxRecipients int `json:"max_recipients"`
HourlyLimit int `json:"hourly_limit,omitempty"`
}
EmailOptions describes alert email on this instance to API clients.
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
Engine drives the alert evaluation loop.
func NewEngine ¶
func NewEngine( store *Store, duck *engine.Duck, detector *intelligence.Detector, interval time.Duration, histDays int, ) *Engine
NewEngine creates an Engine ready to Run.
func (*Engine) DisableRule ¶
DisableRule stops evaluating a rule. Its firing alerts resolve, staying in history and notifying as a cleared condition would; pending ones never fired and are dropped. Holding the lock waits out a tick's transitions for the rule, and the tick skips it from then on.
func (*Engine) EmailOptions ¶
func (e *Engine) EmailOptions() EmailOptions
EmailOptions reports whether email can be chosen. A nil engine means alerts are disabled.
func (*Engine) EnableEmail ¶
func (e *Engine) EnableEmail(cfg EmailConfig)
EnableEmail turns on alert email. Call it before Run.
func (*Engine) RecompileRule ¶
RecompileRule compiles an expression and replaces the rule used on future evaluation ticks.
func (*Engine) RemoveRule ¶
RemoveRule removes a compiled program so it is not evaluated on future ticks.
func (*Engine) WithEmailState ¶
WithEmailState adjusts a rule's reported email state for what this instance can do now: saved recipients without SMTP are a standing failure, and a rule with no email destination has no email state.
type Env ¶
type Env struct {
// Mean of minute-rollup span error proportions over the evaluation window,
// from 0 to 1; not a request-weighted whole-window error rate.
ErrorRate float64 `expr:"error_rate" json:"error_rate"`
// Mean of approximate minute-rollup median span latencies in milliseconds.
P50 float64 `expr:"p50" json:"p50"`
// Mean of approximate minute-rollup 95th-percentile span latencies in
// milliseconds; not the whole-window p95. Latency prefers served work,
// falling back to outbound spans when no served work is available.
P95 float64 `expr:"p95" json:"p95"`
// Total span count over the current rollup window, not requests per second.
// Pair it with an error threshold to avoid firing on very little traffic.
Throughput float64 `expr:"throughput" json:"throughput"`
// Log records recorded for the service over the window.
LogCount float64 `expr:"log_count" json:"log_count"`
// How far the service's current behaviour sits from its own recent baseline,
// in standard deviations. Use it to catch a service that has changed without
// committing to an absolute threshold that fits every service.
ZScore float64 `expr:"z_score" json:"z_score"`
// The detector's instance-wide composite 0-100 health score. Every service
// receives the same score; it is not a per-service value.
HealthScore float64 `expr:"health_score" json:"health_score"`
// Relative change in error rate against the preceding rollup window, as a
// percentage; zero when the baseline is missing or zero.
ErrorRateDelta float64 `expr:"error_rate_delta" json:"error_rate_delta"`
// Relative change in p95 latency against the preceding rollup window, as a
// percentage; zero when the baseline is missing or zero.
P95Delta float64 `expr:"p95_delta" json:"p95_delta"`
// Relative change in span count against the preceding rollup window, as a
// percentage. Negative when traffic drops; zero when the baseline is missing
// or zero.
ThroughputDelta float64 `expr:"throughput_delta" json:"throughput_delta"`
// The service name being evaluated, as a string. Compare it when one rule
// needs to behave differently for one service.
Service string `expr:"service" json:"service"`
}
Env holds the metric values available to alert expressions.
The `expr` tag is the name a rule author writes, and each field's doc comment is published as that variable's description by cmd/pitot-docgen. Adding a field here adds a row to the reference; describe it in a sentence a rule author would find useful, not in terms of how it is computed.
type Program ¶
Program is a compiled, ready-to-evaluate alert expression. Aliasing cel.Program keeps the expression engine an implementation detail of this file — the rest of the package (and callers) refer only to alert.Program.
func CompileExpression ¶
CompileExpression compiles a CEL expression against the alert environment and validates that it type-checks to a boolean.
type Rule ¶
type Rule struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Enabled bool `json:"enabled"`
Service string `json:"service,omitempty"`
Namespace string `json:"namespace,omitempty"`
Expression string `json:"expression"`
ForSeconds int `json:"for_seconds"`
CooldownS int `json:"cooldown_s"`
RepeatIntervalS int `json:"repeat_interval_s"`
WebhookURL string `json:"webhook_url,omitempty"`
WebhookHeaders string `json:"webhook_headers,omitempty"`
WebhookTemplate string `json:"webhook_template,omitempty"`
NotifyOnResolve bool `json:"notify_on_resolve"`
// EmailRecipients are this rule's own addresses. Empty means none: the
// default destination then applies if the rule has no webhook either.
EmailRecipients []string `json:"email_recipients,omitempty"`
// EmailStatus reports the rule's latest email notification: sent, retrying,
// failed, suppressed, or unavailable. The server owns these three fields.
EmailStatus string `json:"email_status,omitempty"`
EmailStatusDetail string `json:"email_status_detail,omitempty"`
EmailStatusAt string `json:"email_status_at,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
Rule defines an alert condition evaluated against the observability data.
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store provides CRUD operations for alert rules and alert instances.
func (*Store) AlertSummary ¶
AlertSummary returns counts of alerts grouped by state.
func (*Store) CreateRule ¶
CreateRule inserts a new alert rule and returns the persisted record.
func (*Store) DeleteAlert ¶
DeleteAlert deletes an alert by ID.
func (*Store) DeleteRule ¶
DeleteRule deletes a rule by ID (cascades to alerts).
func (*Store) GetAlert ¶
GetAlert retrieves the latest episode of (rule_id, service): the open one when there is one, else the most recent resolved one.
func (*Store) ListAlerts ¶
ListAlerts returns alerts with optional filters for state, service, and ruleID. For a single filter, a dedicated generated query is used. For combined filters or no filter, all alerts are fetched and filtered in Go (dataset is small).
func (*Store) ListEnabledRules ¶
ListEnabledRules returns only enabled rules.
func (*Store) PruneResolved ¶
PruneResolved deletes resolved alerts older than days days. Returns the number of rows deleted.
func (*Store) ReplaceRule ¶
ReplaceRule replaces a rule by ID and returns the persisted record.
func (*Store) UpdateDeliveryStatus ¶
UpdateDeliveryStatus updates only the delivery status columns of one alert episode. This is used by fireWebhookAsync to avoid overwriting alert state that may have changed between when the goroutine was launched and when the webhook completed.
func (*Store) UpsertAlert ¶
UpsertAlert inserts an alert episode, or updates the one with a.ID. Each episode is its own row; at most one per (rule_id, service) is open.
type Summary ¶
type Summary struct {
Firing int `json:"firing"`
Pending int `json:"pending"`
Resolved int `json:"resolved"`
}
Summary aggregates alert state counts.
type TestResult ¶
type TestResult struct {
Service string `json:"service"`
Triggered bool `json:"triggered"`
Error string `json:"error,omitempty"`
// NoData is set when the service has no recent telemetry, which usually
// means its name is misspelled.
NoData bool `json:"no_data,omitempty"`
Env Env `json:"env"`
}
TestResult is one service's dry run of a rule.