rule

package
v1.122.21 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ParamGroupID is group id key in url parameter
	ParamGroupID = "group_id"
	// ParamAlertID is alert id key in url parameter
	ParamAlertID = "alert_id"
	// ParamRuleID is rule id key in url parameter
	ParamRuleID = "rule_id"

	// TypeRecording is a RecordingRule type
	TypeRecording = "recording"
	// TypeAlerting is an AlertingRule type
	TypeAlerting = "alerting"
)

Variables

View Source
var SkipRandSleepOnGroupStart bool

SkipRandSleepOnGroupStart will skip random sleep delay in group first evaluation

Functions

func CompareRules

func CompareRules(t *testing.T, a, b Rule) error

CompareRules is a test helper func for other tests

Types

type AlertingRule

type AlertingRule struct {
	Type          config.Type
	RuleID        uint64
	Name          string
	Expr          string
	For           time.Duration
	KeepFiringFor time.Duration
	Labels        map[string]string
	Annotations   map[string]string
	GroupID       uint64
	GroupName     string
	File          string
	EvalInterval  time.Duration
	Debug         bool
	// contains filtered or unexported fields
}

AlertingRule is basic alert entity

func NewAlertingRule

func NewAlertingRule(qb datasource.QuerierBuilder, group *Group, cfg config.Rule) *AlertingRule

NewAlertingRule creates a new AlertingRule

func (*AlertingRule) AlertsToAPI added in v1.110.18

func (ar *AlertingRule) AlertsToAPI() []*ApiAlert

AlertsToAPI returns list of ApiAlert objects from existing alerts

func (*AlertingRule) GetAlerts

func (ar *AlertingRule) GetAlerts() []*notifier.Alert

GetAlerts returns active alerts of rule

func (*AlertingRule) ID

func (ar *AlertingRule) ID() uint64

ID returns unique Rule ID within the parent Group.

func (*AlertingRule) String

func (ar *AlertingRule) String() string

String implements Stringer interface

func (*AlertingRule) ToAPI added in v1.110.18

func (ar *AlertingRule) ToAPI() ApiRule

ToAPI returns ApiRule representation of ar

type ApiAlert added in v1.110.18

type ApiAlert struct {
	State       string            `json:"state"`
	Name        string            `json:"name"`
	Value       string            `json:"value"`
	Labels      map[string]string `json:"labels,omitempty"`
	Annotations map[string]string `json:"annotations"`
	ActiveAt    time.Time         `json:"activeAt"`

	// ID is an unique Alert's ID within a group
	ID string `json:"id"`
	// RuleID is an unique Rule's ID within a group
	RuleID string `json:"rule_id"`
	// GroupID is an unique Group's ID
	GroupID string `json:"group_id"`
	// Expression contains the PromQL/MetricsQL expression
	// for Rule's evaluation
	Expression string `json:"expression"`
	// SourceLink contains a link to a system which should show
	// why Alert was generated
	SourceLink string `json:"source"`
	// Restored shows whether Alert's state was restored on restart
	Restored bool `json:"restored"`
	// Stabilizing shows when firing state is kept because of
	// `keep_firing_for` instead of real alert
	Stabilizing bool `json:"stabilizing"`
}

ApiAlert represents a notifier.AlertingRule state for WEB view https://github.com/prometheus/compliance/blob/main/alert_generator/specification.md#get-apiv1rules

func NewAlertAPI added in v1.110.18

func NewAlertAPI(ar *AlertingRule, a *notifier.Alert) *ApiAlert

NewAlertAPI creates apiAlert for notifier.Alert

func (aa *ApiAlert) APILink() string

APILink returns a link to the alert's JSON representation.

func (aa *ApiAlert) WebLink() string

WebLink returns a link to the alert which can be used in UI.

type ApiGroup added in v1.110.18

type ApiGroup struct {
	// Name is the group name as present in the config
	Name string `json:"name"`
	// Rules contains both recording and alerting rules
	Rules []ApiRule `json:"rules"`
	// Interval is the Group's evaluation interval in float seconds as present in the file.
	Interval float64 `json:"interval"`
	// LastEvaluation is the timestamp of the last time the Group was executed
	LastEvaluation time.Time `json:"lastEvaluation"`

	// Type shows the datasource type (prometheus or graphite) of the Group
	Type string `json:"type"`
	// ID is a unique Group ID
	ID string `json:"id"`
	// File contains a path to the file with Group's config
	File string `json:"file"`
	// Concurrency shows how many rules may be evaluated simultaneously
	Concurrency int `json:"concurrency"`
	// Params contains HTTP URL parameters added to each Rule's request
	Params []string `json:"params,omitempty"`
	// Headers contains HTTP headers added to each Rule's request
	Headers []string `json:"headers,omitempty"`
	// NotifierHeaders contains HTTP headers added to each alert request which will send to notifier
	NotifierHeaders []string `json:"notifier_headers,omitempty"`
	// Labels is a set of label value pairs, that will be added to every rule.
	Labels map[string]string `json:"labels,omitempty"`
	// EvalOffset Group will be evaluated at the exact time offset on the range of [0...evaluationInterval]
	EvalOffset float64 `json:"eval_offset,omitempty"`
	// EvalDelay will adjust the `time` parameter of rule evaluation requests to compensate intentional query delay from datasource.
	EvalDelay float64 `json:"eval_delay,omitempty"`
	// States represents counts per each rule state
	States map[string]int `json:"states"`
}

ApiGroup represents a Group for web view

func (ag *ApiGroup) APILink() string

APILink returns a link to the group's JSON representation.

type ApiRule added in v1.110.18

type ApiRule struct {
	// State must be one of these under following scenarios
	//  "pending": at least 1 alert in the rule in pending state and no other alert in firing ruleState.
	//  "firing": at least 1 alert in the rule in firing state.
	//  "inactive": no alert in the rule in firing or pending state.
	State string `json:"state"`
	Name  string `json:"name"`
	// Query represents Rule's `expression` field
	Query string `json:"query"`
	// Duration represents Rule's `for` field
	Duration float64 `json:"duration"`
	// Alert will continue firing for this long even when the alerting expression no longer has results.
	KeepFiringFor float64           `json:"keep_firing_for"`
	Labels        map[string]string `json:"labels,omitempty"`
	Annotations   map[string]string `json:"annotations,omitempty"`
	// LastError contains the error faced while executing the rule.
	LastError string `json:"lastError"`
	// EvaluationTime is the time taken to completely evaluate the rule in float seconds.
	EvaluationTime float64 `json:"evaluationTime"`
	// LastEvaluation is the timestamp of the last time the rule was executed
	LastEvaluation time.Time `json:"lastEvaluation"`
	// Alerts  is the list of all the alerts in this rule that are currently pending or firing
	Alerts []*ApiAlert `json:"alerts,omitempty"`
	// Health is the health of rule evaluation.
	// It MUST be one of "ok", "err", "unknown"
	Health string `json:"health"`
	// Type of the rule: recording or alerting
	Type string `json:"type"`

	// DatasourceType of the rule: prometheus or graphite
	DatasourceType string `json:"datasourceType"`
	// LastSamples stores the amount of data samples received on last evaluation
	LastSamples int `json:"lastSamples"`
	// LastSeriesFetched stores the amount of time series fetched by datasource
	// during the last evaluation
	LastSeriesFetched *int `json:"lastSeriesFetched,omitempty"`

	// ID is a unique Alert's ID within a group
	ID string `json:"id"`
	// GroupID is an unique Group's ID
	GroupID string `json:"group_id"`
	// GroupName is Group name rule belong to
	GroupName string `json:"group_name"`
	// File is file name where rule is defined
	File string `json:"file"`
	// Debug shows whether debug mode is enabled
	Debug bool `json:"debug"`

	// MaxUpdates is the max number of recorded ruleStateEntry objects
	MaxUpdates int `json:"max_updates_entries"`
	// Updates contains the ordered list of recorded ruleStateEntry objects
	Updates []StateEntry `json:"-"`
}

ApiRule represents a Rule for web view see https://github.com/prometheus/compliance/blob/main/alert_generator/specification.md#get-apiv1rules

func (ar ApiRule) APILink() string

APILink returns a link to the rule's JSON representation.

func (*ApiRule) ExtendState added in v1.122.18

func (r *ApiRule) ExtendState()

func (*ApiRule) IsNoMatch added in v1.122.18

func (r *ApiRule) IsNoMatch() bool

IsNoMatch returns true if rule is in nomatch state

func (ar ApiRule) WebLink() string

WebLink returns a link to the alert which can be used in UI.

type ApiRuleWithUpdates added in v1.110.18

type ApiRuleWithUpdates struct {
	ApiRule
	// Updates contains the ordered list of recorded ruleStateEntry objects
	StateUpdates []StateEntry `json:"updates,omitempty"`
}

ApiRuleWithUpdates represents ApiRule but with extra fields for marshalling

type Group

type Group struct {
	Name       string
	File       string
	Rules      []Rule
	Type       config.Type
	Interval   time.Duration
	EvalOffset *time.Duration
	// EvalDelay will adjust timestamp for rule evaluation requests to compensate intentional query delay from datasource.
	// see https://github.com/VictoriaMetrics/VictoriaMetrics/issues/5155
	EvalDelay   *time.Duration
	Limit       int
	Concurrency int

	LastEvaluation time.Time
	Debug          bool

	Labels          map[string]string
	Params          url.Values
	Headers         map[string]string
	NotifierHeaders map[string]string
	// contains filtered or unexported fields
}

Group is an entity for grouping rules

func NewGroup

func NewGroup(cfg config.Group, qb datasource.QuerierBuilder, defaultInterval time.Duration, labels map[string]string) *Group

NewGroup returns a new group

func (*Group) Close

func (g *Group) Close()

Close stops the group and its rules, unregisters group metrics

func (*Group) CreateID added in v1.102.17

func (g *Group) CreateID() uint64

CreateID returns the unique ID based on group basic fields. Should only be called when creating new group, and use GetID() afterward.

func (*Group) ExecOnce

func (g *Group) ExecOnce(ctx context.Context, rw remotewrite.RWClient, evalTS time.Time) chan error

ExecOnce evaluates all the rules under group for once with given timestamp.

func (*Group) GetCheckSum added in v1.102.17

func (g *Group) GetCheckSum() string

GetCheckSum returns group checksum

func (*Group) GetID added in v1.102.17

func (g *Group) GetID() uint64

GetID returns the unique group ID

func (*Group) Init added in v1.102.17

func (g *Group) Init()

Init must be called before group Start()

func (*Group) InterruptEval

func (g *Group) InterruptEval()

InterruptEval interrupts in-flight rules evaluations within the group. It is expected that g.evalCancel will be repopulated after the call.

func (*Group) Replay

func (g *Group) Replay(start, end time.Time, rw remotewrite.RWClient, maxDataPoint, replayRuleRetryAttempts int, replayDelay time.Duration, disableProgressBar bool, ruleEvaluationConcurrency int) int

Replay performs group replay

func (*Group) Start

Start starts group's evaluation

func (*Group) ToAPI added in v1.110.18

func (g *Group) ToAPI() *ApiGroup

ToAPI returns ApiGroup representation of g

func (*Group) UpdateWith

func (g *Group) UpdateWith(newGroup *Group)

UpdateWith inserts new group to updateCh

type GroupAlerts added in v1.110.18

type GroupAlerts struct {
	Group  *ApiGroup
	Alerts []*ApiAlert
}

GroupAlerts represents a Group with its Alerts for web view

type RecordingRule

type RecordingRule struct {
	Type      config.Type
	RuleID    uint64
	Name      string
	Expr      string
	Labels    map[string]string
	GroupID   uint64
	GroupName string
	File      string
	Debug     bool
	// contains filtered or unexported fields
}

RecordingRule is a Rule that supposed to evaluate configured Expression and return TimeSeries as result.

func NewRecordingRule

func NewRecordingRule(qb datasource.QuerierBuilder, group *Group, cfg config.Rule) *RecordingRule

NewRecordingRule creates a new RecordingRule

func (*RecordingRule) ID

func (rr *RecordingRule) ID() uint64

ID returns unique Rule ID within the parent Group.

func (*RecordingRule) String

func (rr *RecordingRule) String() string

String implements Stringer interface

func (*RecordingRule) ToAPI added in v1.110.18

func (rr *RecordingRule) ToAPI() ApiRule

ToAPI returns ApiRule representation of rr

type Rule

type Rule interface {
	// ID returns unique ID that may be used for
	// identifying this Rule among others.
	ID() uint64
	// ToAPI returns ApiRule representation of Rule
	ToAPI() ApiRule
	// contains filtered or unexported methods
}

Rule represents alerting or recording rule that has unique ID, can be Executed and updated with other Rule.

type StateEntry

type StateEntry struct {
	// stores last moment of time rule.Exec was called
	Time time.Time `json:"time"`
	// stores the timesteamp with which rule.Exec was called
	At time.Time `json:"at"`
	// stores the duration of the last rule.Exec call
	Duration time.Duration `json:"duration"`
	// stores last error that happened in Exec func
	// resets on every successful Exec
	// may be used as Health ruleState
	Err error `json:"error"`
	// stores the number of samples returned during
	// the last evaluation
	Samples int `json:"samples"`
	// stores the number of time series fetched during
	// the last evaluation.
	// Is supported by VictoriaMetrics only, starting from v1.90.0
	// If seriesFetched == nil, then this attribute was missing in
	// datasource response (unsupported).
	SeriesFetched *int `json:"series_fetched"`
	// stores the curl command reflecting the HTTP request used during rule.Exec
	Curl string `json:"curl"`
}

StateEntry stores rule's execution states

Jump to

Keyboard shortcuts

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