templates

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: AGPL-3.0 Imports: 23 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 templates is the template sandbox of ADR-0012 (C-12.FR-4): Go text/template with the sprout registries strings, lists, maps, conversions and regular expressions (RE2) registered explicitly, Alertmanager's template functions under their Alertmanager names, and `now` from Muster's business clock. Anything else is unknown_function. A running template cannot be interrupted, so its execution is bounded instead: `until`, `seq`, `repeat` and a range over an integer are capped at LoopCap items, every range and every template call counts against a budget per execution, a function result longer than OutputCap characters or ResultItems items is an error, output stops at OutputCap characters, and the range and template guards stop an execution that ran for longer than ExecutionLimit on the real clock. One sandbox serves messages, Link rules and outgoing webhooks: `lookup` reads one cell of a Lookup table through the Env of an execution, and `mention` writes a trusted Mention token that only an adapter turns into a Mention (C-12.FR-8, FR-9). A key that a map of labels or annotations does not have is empty text, as in Alertmanager, whose templates set missingkey=zero: `.Labels.cluster` without the label prints nothing and passes "" to a function such as `lookup`, while a field the data does not have is still an error.

Index

Constants

View Source
const (
	StatusFiring   = "firing"
	StatusResolved = "resolved"
)

The Alertmanager statuses of the template data.

View Source
const (
	OutputCap      = 50_000
	LoopCap        = 1_000
	ResultItems    = 10_000
	RangeBudget    = 100_000
	CallBudget     = 10_000
	ExecutionLimit = 2 * time.Second
)

The limits of the sandbox: template.output_cap, the cap of the functions that produce loops, the largest list or map a function may return, the items all the ranges of one execution may visit, the template calls of one execution, and how long an execution may run before its next range or template call stops it.

View Source
const (
	CodeSyntax          = "template_syntax"
	CodeUnknownFunction = "unknown_function"
)

The codes of Error, as the API names them (ProblemError).

View Source
const (
	MentionAll     = "all"
	MentionChannel = "channel"
	MentionHere    = "here"
	MentionOwner   = "owner"
	MentionGroup   = "group"
)

The Mentions a template may write with `mention`: everyone in the chat as all, channel or here, the Owner, or a messenger group by its name.

Variables

View Source
var ErrNotWebhook = errors.New("the body is not an alertmanager webhook")

ErrNotWebhook is a Stored Snapshot whose body is not an Alertmanager webhook.

Functions

func MentionToken

func MentionToken(tk Token) string

MentionToken is the token of tk.

func ReplaceTokens

func ReplaceTokens(s string, f func(Token) string) string

ReplaceTokens replaces every Mention token of s with what f returns for it; the token characters that form no token are dropped.

func SafeURL

func SafeURL(u string) string

SafeURL is u, trimmed, when it is an absolute http or https link without user information, spaces, control or format characters or the characters of Mention tokens, and empty otherwise (C-12.FR-7): links are http(s) only.

func StripTokens

func StripTokens(s string) string

StripTokens removes the characters of Mention tokens from s: alert data never carry a token.

Types

type Alert

type Alert struct {
	Status       string
	Labels       KV
	Annotations  KV
	StartsAt     time.Time
	EndsAt       time.Time
	GeneratorURL string
	Fingerprint  string
}

Alert is one Alert of the template data.

type AlertGroup

type AlertGroup struct {
	Number        int64
	Title         string
	Summary       string
	Status        string
	Route         string
	SeverityLevel string
	Urgent        bool
	StartedAt     time.Time
	URL           string
	ReopenCount   int64
	Owner         string
}

AlertGroup is the Alert Group of the template data.

type Alerts

type Alerts []Alert

Alerts is a list of Alerts, with Alertmanager's Firing and Resolved.

func (Alerts) Firing

func (as Alerts) Firing() []Alert

Firing are the firing Alerts.

func (Alerts) Resolved

func (as Alerts) Resolved() []Alert

Resolved are the resolved Alerts.

type Data

type Data struct {
	Receiver          string
	Status            string
	Alerts            Alerts
	GroupLabels       KV
	CommonLabels      KV
	CommonAnnotations KV
	ExternalURL       string
	AlertGroup        AlertGroup
}

Data is what a Root message template sees: Alertmanager's template data — Status, Alerts, GroupLabels, CommonLabels, CommonAnnotations and ExternalURL — and the Alert Group. Label and annotation values arrive escaped for the target markup, with `@` neutralized and cut to message.value_cap, so safeHtml returns its argument unchanged.

func FromWebhook

func FromWebhook(body []byte) (Data, error)

FromWebhook is the template data of an Alertmanager webhook as Alertmanager sent it, without the Alert Group; the values are as received, not yet made safe for a markup.

type Env

type Env struct {
	Lookup  func(table, key, column string) (string, error)
	Mention func(target any) (string, error)
}

Env is what one execution reads besides its data: Lookup reads one cell of a Lookup table, the empty string for a missing table, key or column (C-12.FR-9); nil reads nothing. Mention, when set, stands for `mention` in the execution: an outgoing webhook renders a Mention target of its data as plain text instead of a trusted token (C-15.FR-11).

type Error

type Error struct {
	Code   string
	Line   int
	Column int
	Detail string
}

Error is a template that does not parse, calls a function the sandbox does not have, or fails while it runs: its code, its 1-based position when known, and what went wrong.

func (*Error) Error

func (e *Error) Error() string

type KV

type KV map[string]string

KV is a set of labels or annotations, with Alertmanager's SortedPairs, Names, Values and Remove.

func (KV) Names

func (kv KV) Names() []string

Names are the sorted names.

func (KV) Remove

func (kv KV) Remove(names []string) KV

Remove is a copy without the names given.

func (KV) SortedPairs

func (kv KV) SortedPairs() Pairs

SortedPairs are the pairs sorted by name, alertname first, as Alertmanager sorts them.

func (KV) Values

func (kv KV) Values() []string

Values are the values in the order of the sorted names.

type LineData

type LineData struct {
	Alert
	AlertGroup AlertGroup
}

LineData is what a line template sees: one Alert, whose fields it reads directly (`.Labels.pod`), and the Alert Group.

type Pair

type Pair struct {
	Name, Value string
}

Pair is a label or annotation with its name and value.

type Pairs

type Pairs []Pair

Pairs is a list of Pairs, with Alertmanager's Names and Values.

func (Pairs) Names

func (ps Pairs) Names() []string

Names are the names of the pairs.

func (Pairs) Values

func (ps Pairs) Values() []string

Values are the values of the pairs.

type Sandbox

type Sandbox struct {
	// contains filtered or unexported fields
}

Sandbox parses and runs templates. Business is the clock of `now` and `since`, Real the clock of ExecutionLimit.

func New

func New(business, realClock clock.Clock) *Sandbox

New is the sandbox whose `now` follows business and whose execution limit follows real.

func (*Sandbox) Names

func (s *Sandbox) Names() []string

Names are the names of the functions a template may call besides those of text/template, sorted.

func (*Sandbox) Parse

func (s *Sandbox) Parse(name, src string) (*Template, error)

Parse parses src as the template name. A syntax error is CodeSyntax with its line, a call of a function the sandbox does not have is CodeUnknownFunction with its line and column.

type Template

type Template struct {
	// contains filtered or unexported fields
}

Template is a parsed template.

func (*Template) Execute

func (t *Template) Execute(data any) (string, error)

Execute runs the template on data with a fresh budget and returns its output. Any failure is an Error with the code CodeSyntax and the position text/template reports.

func (*Template) ExecuteIn

func (t *Template) ExecuteIn(env Env, data any) (out string, err error)

ExecuteIn runs the template on data with a fresh budget and the Env env, as Execute does.

func (*Template) LookupTables

func (t *Template) LookupTables() []string

LookupTables are the Lookup tables the template reads by a literal name, `lookup "grafana" …`, sorted and without duplicates.

func (*Template) Source

func (t *Template) Source() string

Source is the template's text.

type Token

type Token struct {
	Name  string
	Group string
}

Token is a trusted Mention in a text: its name and, for a group, the group's name.

func Tokens

func Tokens(s string) []Token

Tokens are the Mention tokens of s in order.

Jump to

Keyboard shortcuts

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