alerts

package
v0.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package alerts evaluates alert rules (§9) every 30 seconds and notifies channels when an alert fires and when it resolves. Rules watch metrics (resource use, request rates, errors, latency, any PromQL), log lines, service health and nodes; failed deployments, builds and jobs notify once each.

Index

Constants

View Source
const (
	// Interval between evaluations.
	Interval = 30 * time.Second
	// TopicAlert carries a store.AlertEvent for every notification.
	TopicAlert = "alert.event"
)
View Source
const (

	// AdminsChannel is the email channel the default rules notify.
	AdminsChannel = "Admins"
)

Variables

View Source
var (
	RuleTypes = map[string]string{
		"metric": "a service metric crosses a threshold", "promql": "a PromQL expression crosses a threshold",
		"log": "log lines matching a pattern", "health": "a service is degraded or down", "node": "a node stops reporting",
		"deployment": "a deployment fails", "build": "a build fails", "job": "a job run fails",
		"node_overload": "a node's CPU, memory or disk is above a threshold", "database_failover": "a managed database gets a new primary",
		"database_health": "a managed database is degraded or down", "system_component": "a system component (Traefik, registry, …) is not running",
		"backup": "controller backups fail or stop", "certificate": "a certificate is about to expire or can't be renewed",
		"controller_disk": "the controller's data disk is filling up",
	}
	RuleMetrics = map[string]string{
		"cpu": "CPU % of one core (average per task)", "memory": "memory % of the limit (busiest task)",
		"rps": "requests per second", "error_rate": "5xx responses, % of requests", "latency": "p95 latency, ms",
	}
)

Types and metrics, with what they measure.

View Source
var ChannelTypes = []string{"webhook", "slack", "discord", "telegram", "email"}

ChannelTypes lists the supported channels.

View Source
var ErrNoSMTP = errors.New("email is not set up: add an SMTP server under Settings → Email")

ErrNoSMTP means email can't be sent until SMTP is set up.

View Source
var TelegramAPI = "https://api.telegram.org"

TelegramAPI is the Bot API base URL (a variable for tests).

Functions

func Send

Send delivers n through one channel.

Types

type BackupState added in v0.2.0

type BackupState struct {
	Configured    bool
	LastRunAt     *time.Time
	LastSuccessAt *time.Time
	LastError     string
}

type Channel

type Channel struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	Summary   string    `json:"summary"`
	CreatedAt time.Time `json:"createdAt"`
}

Channel is a notification channel as the API shows it (no secrets).

type ChannelConfig

type ChannelConfig struct {
	// webhook, slack, discord
	URL string `json:"url,omitempty"`
	// telegram
	BotToken string `json:"botToken,omitempty"`
	ChatID   string `json:"chatId,omitempty"`
	// email
	SMTPHost string   `json:"smtpHost,omitempty"`
	SMTPPort int      `json:"smtpPort,omitempty"`
	Username string   `json:"username,omitempty"`
	Password string   `json:"password,omitempty"`
	From     string   `json:"from,omitempty"`
	To       []string `json:"to,omitempty"`
}

ChannelConfig holds every channel type's settings; only the type's fields are used. URLs and tokens are secrets: they are sealed at rest and never returned by the API.

func (*ChannelConfig) Validate

func (c *ChannelConfig) Validate(typ string) (string, error)

Validate checks a channel's settings and returns a summary safe to show.

type ComponentState added in v0.2.0

type ComponentState struct {
	ID, Name, State, Error string
}

type DatabaseState added in v0.2.0

type DatabaseState struct {
	ID, Name, Project, Environment, Engine string
	Health                                 string // healthy | degraded | starting | down | deleting
	Reason                                 string
}

type ErrInvalid

type ErrInvalid struct{ Err error }

ErrInvalid wraps validation errors.

func (ErrInvalid) Error

func (e ErrInvalid) Error() string

type HealthSource

type HealthSource interface {
	List(ctx context.Context) ([]health.ServiceHealth, error)
}

HealthSource lists service health (health.Monitor).

type LogsSource

type LogsSource interface {
	Count(ctx context.Context, f logs.Filter, level string, window time.Duration) ([]logs.Count, error)
}

LogsSource counts log lines (logs.Store).

type Manager

type Manager struct {

	// DashboardURL links notifications to the dashboard.
	DashboardURL func() string
	// Brand returns the workspace name and logo (PNG) for emails (Phase 21).
	Brand func() (name string, logo []byte)
	// Sources of the system rule types (Phase 20b); nil skips a type.
	Sources Sources
	// contains filtered or unexported fields
}

func New

func New(st *store.Store, box *secrets.Box, m MetricsSource, l LogsSource, h HealthSource, bus *events.Bus, log *slog.Logger) *Manager

func (*Manager) Active

func (m *Manager) Active(ctx context.Context) ([]store.AlertState, error)

Active returns the alerts whose condition holds, firing first.

func (*Manager) Channels

func (m *Manager) Channels(ctx context.Context) ([]Channel, error)

func (*Manager) DeleteChannel

func (m *Manager) DeleteChannel(ctx context.Context, id string) error

func (*Manager) DeleteRule

func (m *Manager) DeleteRule(ctx context.Context, id string) error

func (*Manager) DeleteSMTP added in v0.2.0

func (m *Manager) DeleteSMTP(ctx context.Context) error

DeleteSMTP turns email off (channels with their own server keep working).

func (*Manager) EnsureDefaults added in v0.2.0

func (m *Manager) EnsureDefaults(ctx context.Context, email string) error

EnsureDefaults creates the Admins email channel (to email) and the System rules once per install. Later calls do nothing, so deleted rules stay deleted; RestoreDefaults brings them back.

func (*Manager) Evaluate

func (m *Manager) Evaluate(ctx context.Context)

Evaluate checks every enabled rule once.

func (*Manager) PutChannel

func (m *Manager) PutChannel(ctx context.Context, id, name, typ string, cfg ChannelConfig) (Channel, error)

PutChannel creates (empty id) or replaces a channel.

func (*Manager) PutRule

func (m *Manager) PutRule(ctx context.Context, r Rule) (Rule, error)

PutRule creates (empty ID) or replaces a rule.

func (*Manager) RestoreDefaults added in v0.2.0

func (m *Manager) RestoreDefaults(ctx context.Context, email string) (int, error)

RestoreDefaults recreates missing System rules (by name) and the Admins channel, and returns how many rules it added.

func (*Manager) Rules

func (m *Manager) Rules(ctx context.Context) ([]Rule, error)

func (*Manager) Run

func (m *Manager) Run(ctx context.Context)

Run evaluates every rule each Interval until ctx ends.

func (*Manager) SMTP added in v0.2.0

func (m *Manager) SMTP(ctx context.Context) (SMTPView, error)

SMTP returns the platform SMTP settings without the password.

func (*Manager) SetSMTP added in v0.2.0

func (m *Manager) SetSMTP(ctx context.Context, in SMTP) (SMTPView, error)

SetSMTP saves the platform SMTP settings. An empty password keeps the stored one while the username is unchanged.

func (*Manager) TestChannel

func (m *Manager) TestChannel(ctx context.Context, id string) error

TestChannel sends a test notification and returns the delivery error.

func (*Manager) TestSMTP added in v0.2.0

func (m *Manager) TestSMTP(ctx context.Context, to string) error

TestSMTP sends a test email to one address and returns the server's error.

type MetricsSource

type MetricsSource interface {
	Instant(ctx context.Context, q string) ([]metrics.Sample, error)
}

MetricsSource reads metrics (metrics.Store).

type Notification

type Notification struct {
	Kind     string    `json:"status"` // firing | reminder | resolved | event | test
	Rule     string    `json:"rule"`
	Severity string    `json:"severity"`
	Instance string    `json:"instance"` // e.g. shop/production/web or node w2
	Message  string    `json:"message"`
	Value    *float64  `json:"value,omitempty"`
	At       time.Time `json:"at"`
	URL      string    `json:"url,omitempty"` // the dashboard
}

Notification is what a channel delivers.

func (Notification) Text

func (n Notification) Text() string

Text is the plain-text body used by chat channels and email.

func (Notification) Title

func (n Notification) Title() string

Title is a one-line summary.

type Rule

type Rule struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Enabled  bool   `json:"enabled"`
	Type     string `json:"type"`     // metric | promql | log | health | node | deployment | build | job, or a system type (system.go)
	Severity string `json:"severity"` // info | warning | critical
	// Scope: empty matches every project, environment or service.
	Project     string `json:"project,omitempty"`
	Environment string `json:"environment,omitempty"`
	Service     string `json:"service,omitempty"`
	// metric: cpu | memory | rps | error_rate | latency.
	Metric string `json:"metric,omitempty"`
	// promql: any query; each series is an instance.
	Query string `json:"query,omitempty"`
	// log: lines containing Text (case-insensitive) and/or with Level.
	Text  string `json:"text,omitempty"`
	Level string `json:"level,omitempty"`
	// metric, promql, log: value Op Threshold over WindowSeconds.
	Op            string  `json:"op,omitempty"`
	Threshold     float64 `json:"threshold"`
	WindowSeconds int     `json:"windowSeconds,omitempty"`
	// ForSeconds is how long the condition must hold before firing.
	ForSeconds int `json:"forSeconds"`
	// RepeatHours re-sends a firing alert this often (0 = never).
	RepeatHours int `json:"repeatHours"`
	// System marks the default rules (Phase 20c); they can be edited,
	// disabled or deleted, and restored.
	System    bool      `json:"system,omitempty"`
	Channels  []string  `json:"channels"`
	CreatedAt time.Time `json:"createdAt"`
	UpdatedAt time.Time `json:"updatedAt"`
}

Rule is an alert rule as the API shows and accepts it.

func DefaultRules added in v0.2.0

func DefaultRules() []Rule

DefaultRules are the System rules a new install starts with.

func (*Rule) Validate

func (r *Rule) Validate() error

Validate checks a rule and fills in defaults.

type SMTP added in v0.2.0

type SMTP struct {
	Host     string `json:"host"`
	Port     int    `json:"port"`
	Security string `json:"security"` // starttls | tls | none
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
	From     string `json:"from"`
	FromName string `json:"fromName,omitempty"` // default: the workspace name
}

SMTP is the platform's mail server (Phase 20a). Email channels use it unless they carry their own server.

func (*SMTP) Validate added in v0.2.0

func (c *SMTP) Validate() error

Validate checks the settings and fills in defaults.

type SMTPView added in v0.2.0

type SMTPView struct {
	Configured  bool   `json:"configured"`
	Host        string `json:"host"`
	Port        int    `json:"port"`
	Security    string `json:"security"`
	Username    string `json:"username"`
	HasPassword bool   `json:"hasPassword"`
	From        string `json:"from"`
	FromName    string `json:"fromName"`
}

SMTPView is the SMTP configuration as the API shows it (no password).

type Sources added in v0.2.0

type Sources struct {
	// Databases lists managed databases with their health.
	Databases func(ctx context.Context) ([]DatabaseState, error)
	// Components lists the system tasks (Traefik, registry, …).
	Components func() []ComponentState
	// Backup is the controller backup status.
	Backup func() BackupState
	// ControllerDisk is the controller data disk's usage.
	ControllerDisk func() (used, total uint64, err error)
}

Sources feed the system rule types; a nil source skips its type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL