models

package
v0.0.1-test Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2022 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RuleUIDLabel      = "__alert_rule_uid__"
	NamespaceUIDLabel = "__alert_rule_namespace_uid__"

	// Annotations are actually a set of labels, so technically this is the label name of an annotation.
	DashboardUIDAnnotation = "__dashboardUid__"
	PanelIDAnnotation      = "__panelId__"

	// This isn't a hard-coded secret token, hence the nolint.
	//nolint:gosec
	ImageTokenAnnotation = "__alertImageToken__"

	// GrafanaReservedLabelPrefix contains the prefix for Grafana reserved labels. These differ from "__<label>__" labels
	// in that they are not meant for internal-use only and will be passed-through to AMs and available to users in the same
	// way as manually configured labels.
	GrafanaReservedLabelPrefix = "grafana_"

	// FolderTitleLabel is the label that will contain the title of an alert's folder/namespace.
	FolderTitleLabel = GrafanaReservedLabelPrefix + "folder"

	// StateReasonAnnotation is the name of the annotation that explains the difference between evaluation state and alert state (i.e. changing state when NoData or Error).
	StateReasonAnnotation = GrafanaReservedLabelPrefix + "state_reason"
)
View Source
const AlertConfigurationVersion = 1

Variables

View Source
var (
	// ErrAlertRuleNotFound is an error for an unknown alert rule.
	ErrAlertRuleNotFound = fmt.Errorf("could not find alert rule")
	// ErrAlertRuleFailedGenerateUniqueUID is an error for failure to generate alert rule UID
	ErrAlertRuleFailedGenerateUniqueUID = errors.New("failed to generate alert rule UID")
	// ErrCannotEditNamespace is an error returned if the user does not have permissions to edit the namespace
	ErrCannotEditNamespace                = errors.New("user does not have permissions to edit the namespace")
	ErrRuleGroupNamespaceNotFound         = errors.New("rule group not found under this namespace")
	ErrAlertRuleFailedValidation          = errors.New("invalid alert rule")
	ErrAlertRuleUniqueConstraintViolation = errors.New("a conflicting alert rule is found: rule title under the same organisation and folder should be unique")
	ErrQuotaReached                       = errors.New("quota has been exceeded")
)
View Source
var (
	// InternalLabelNameSet are labels that grafana automatically include as part of the labelset.
	InternalLabelNameSet = map[string]struct{}{
		RuleUIDLabel:      {},
		NamespaceUIDLabel: {},
	}
	InternalAnnotationNameSet = map[string]struct{}{
		DashboardUIDAnnotation: {},
		PanelIDAnnotation:      {},
		ImageTokenAnnotation:   {},
	}
)
View Source
var (
	// ErrImageNotFound is returned when the image does not exist.
	ErrImageNotFound = errors.New("image not found")
)
View Source
var ErrNoQuery = errors.New("no `expr` property in the query model")
View Source
var (
	StateReasonMissingSeries = "MissingSeries"
)

Functions

func AlertRuleGen

func AlertRuleGen(mutators ...AlertRuleMutator) func() *AlertRule

AlertRuleGen provides a factory function that generates a random AlertRule. The mutators arguments allows changing fields of the resulting structure

func GenerateAlertLabels

func GenerateAlertLabels(count int, prefix string) data.Labels

func PatchPartialAlertRule

func PatchPartialAlertRule(existingRule *AlertRule, ruleToPatch *AlertRule)

PatchPartialAlertRule patches `ruleToPatch` by `existingRule` following the rule that if a field of `ruleToPatch` is empty or has the default value, it is populated by the value of the corresponding field from `existingRule`. There are several exceptions: 1. Following fields are not patched and therefore will be ignored: AlertRule.ID, AlertRule.OrgID, AlertRule.Updated, AlertRule.Version, AlertRule.UID, AlertRule.DashboardUID, AlertRule.PanelID, AlertRule.Annotations and AlertRule.Labels 2. There are fields that are patched together:

  • AlertRule.Condition and AlertRule.Data

If either of the pair is specified, neither is patched.

func ValidateAlertInstance

func ValidateAlertInstance(alertInstance AlertInstance) error

ValidateAlertInstance validates that the alert instance contains an alert rule id, and state.

func ValidateRuleGroupInterval

func ValidateRuleGroupInterval(intervalSeconds, baseIntervalSeconds int64) error

Types

type AdminConfiguration

type AdminConfiguration struct {
	ID    int64 `xorm:"pk autoincr 'id'"`
	OrgID int64 `xorm:"org_id"`

	// List of Alertmanager(s) URL to push alerts to.
	Alertmanagers []string

	// SendAlertsTo indicates which set of alertmanagers will handle the alert.
	SendAlertsTo AlertmanagersChoice `xorm:"send_alerts_to"`

	CreatedAt int64 `xorm:"created"`
	UpdatedAt int64 `xorm:"updated"`
}

AdminConfiguration represents the ngalert administration configuration settings.

func (*AdminConfiguration) AsSHA256

func (ac *AdminConfiguration) AsSHA256() string

func (*AdminConfiguration) Validate

func (ac *AdminConfiguration) Validate() error

type AlertConfiguration

type AlertConfiguration struct {
	ID int64 `xorm:"pk autoincr 'id'"`

	AlertmanagerConfiguration string
	ConfigurationHash         string
	ConfigurationVersion      string
	CreatedAt                 int64 `xorm:"created"`
	Default                   bool
	OrgID                     int64 `xorm:"org_id"`
}

AlertConfiguration represents a single version of the Alerting Engine Configuration.

type AlertInstance

type AlertInstance struct {
	AlertInstanceKey  `xorm:"extends"`
	Labels            InstanceLabels
	CurrentState      InstanceStateType
	CurrentReason     string
	CurrentStateSince time.Time
	CurrentStateEnd   time.Time
	LastEvalTime      time.Time
}

AlertInstance represents a single alert instance.

type AlertInstanceKey

type AlertInstanceKey struct {
	RuleOrgID  int64  `xorm:"rule_org_id"`
	RuleUID    string `xorm:"rule_uid"`
	LabelsHash string
}

type AlertQuery

type AlertQuery struct {
	// RefID is the unique identifier of the query, set by the frontend call.
	RefID string `json:"refId"`

	// QueryType is an optional identifier for the type of query.
	// It can be used to distinguish different types of queries.
	QueryType string `json:"queryType"`

	// RelativeTimeRange is the relative Start and End of the query as sent by the frontend.
	RelativeTimeRange RelativeTimeRange `json:"relativeTimeRange"`

	// Grafana data source unique identifier; it should be '-100' for a Server Side Expression operation.
	DatasourceUID string `json:"datasourceUid"`

	// JSON is the raw JSON query and includes the above properties as well as custom properties.
	Model json.RawMessage `json:"model"`
	// contains filtered or unexported fields
}

AlertQuery represents a single query associated with an alert definition.

func CreateClassicConditionExpression

func CreateClassicConditionExpression(refID string, inputRefID string, reducer string, operation string, threshold int) AlertQuery

func GenerateAlertQuery

func GenerateAlertQuery() AlertQuery

func (*AlertQuery) GetDatasource

func (aq *AlertQuery) GetDatasource() (string, error)

GetDatasource returns the query datasource identifier.

func (*AlertQuery) GetIntervalDuration

func (aq *AlertQuery) GetIntervalDuration() (time.Duration, error)

func (*AlertQuery) GetMaxDatapoints

func (aq *AlertQuery) GetMaxDatapoints() (int64, error)

func (*AlertQuery) GetModel

func (aq *AlertQuery) GetModel() ([]byte, error)

func (*AlertQuery) GetQuery

func (aq *AlertQuery) GetQuery() (string, error)

GetQuery returns the query defined by `expr` within the model. Returns an ErrNoQuery if it is unable to find the query. Returns an error if it is not able to cast the query to a string.

func (*AlertQuery) IsExpression

func (aq *AlertQuery) IsExpression() (bool, error)

IsExpression returns true if the alert query is an expression.

func (*AlertQuery) PreSave

func (aq *AlertQuery) PreSave() error

PreSave sets query's properties. It should be called before being saved.

type AlertRule

type AlertRule struct {
	ID              int64 `xorm:"pk autoincr 'id'"`
	OrgID           int64 `xorm:"org_id"`
	Title           string
	Condition       string
	Data            []AlertQuery
	Updated         time.Time
	IntervalSeconds int64
	Version         int64   `xorm:"version"` // this tag makes xorm add optimistic lock (see https://xorm.io/docs/chapter-06/1.lock/)
	UID             string  `xorm:"uid"`
	NamespaceUID    string  `xorm:"namespace_uid"`
	DashboardUID    *string `xorm:"dashboard_uid"`
	PanelID         *int64  `xorm:"panel_id"`
	RuleGroup       string
	RuleGroupIndex  int `xorm:"rule_group_idx"`
	NoDataState     NoDataState
	ExecErrState    ExecutionErrorState
	// ideally this field should have been apimodels.ApiDuration
	// but this is currently not possible because of circular dependencies
	For         time.Duration
	Annotations map[string]string
	Labels      map[string]string
}

AlertRule is the model for alert rules in unified alerting.

func CopyRule

func CopyRule(r *AlertRule) *AlertRule

CopyRule creates a deep copy of AlertRule

func GenerateAlertRules

func GenerateAlertRules(count int, f func() *AlertRule) []*AlertRule

GenerateAlertRules generates many random alert rules. Does not guarantee that rules are unique (by UID)

func GenerateAlertRulesSmallNonEmpty

func GenerateAlertRulesSmallNonEmpty(f func() *AlertRule) []*AlertRule

GenerateAlertRulesSmallNonEmpty generates 1 to 5 rules using the provided generator

func GenerateUniqueAlertRules

func GenerateUniqueAlertRules(count int, f func() *AlertRule) (map[string]*AlertRule, []*AlertRule)

GenerateUniqueAlertRules generates many random alert rules and makes sure that they have unique UID. It returns a tuple where first element is a map where keys are UID of alert rule and the second element is a slice of the same rules

func (*AlertRule) Diff

func (alertRule *AlertRule) Diff(rule *AlertRule, ignore ...string) cmputil.DiffReport

Diff calculates diff between two alert rules. Returns nil if two rules are equal. Otherwise, returns cmputil.DiffReport

func (*AlertRule) GetEvalCondition

func (alertRule *AlertRule) GetEvalCondition() Condition

func (*AlertRule) GetGroupKey

func (alertRule *AlertRule) GetGroupKey() AlertRuleGroupKey

GetGroupKey returns the identifier of a group the rule belongs to

func (*AlertRule) GetKey

func (alertRule *AlertRule) GetKey() AlertRuleKey

GetKey returns the alert definitions identifier

func (*AlertRule) GetLabels

func (alertRule *AlertRule) GetLabels(opts ...LabelOption) map[string]string

GetLabels returns the labels specified as part of the alert rule.

func (*AlertRule) PreSave

func (alertRule *AlertRule) PreSave(timeNow func() time.Time) error

PreSave sets default values and loads the updated model for each alert query.

func (*AlertRule) ResourceID

func (alertRule *AlertRule) ResourceID() string

func (*AlertRule) ResourceOrgID

func (alertRule *AlertRule) ResourceOrgID() int64

func (*AlertRule) ResourceType

func (alertRule *AlertRule) ResourceType() string

func (*AlertRule) SetDashboardAndPanel

func (alertRule *AlertRule) SetDashboardAndPanel() error

SetDashboardAndPanel will set the DashboardUID and PanlID field be doing a lookup in the annotations. Errors when the found annotations are not valid.

type AlertRuleGroup

type AlertRuleGroup struct {
	Title      string
	FolderUID  string
	Interval   int64
	Provenance Provenance
	Rules      []AlertRule
}

AlertRuleGroup is the base model for a rule group in unified alerting.

type AlertRuleGroupKey

type AlertRuleGroupKey struct {
	OrgID        int64
	NamespaceUID string
	RuleGroup    string
}

AlertRuleGroupKey is the identifier of a group of alerts

func GenerateGroupKey

func GenerateGroupKey(orgID int64) AlertRuleGroupKey

GenerateGroupKey generates a random group key

func (AlertRuleGroupKey) String

func (k AlertRuleGroupKey) String() string

type AlertRuleKey

type AlertRuleKey struct {
	OrgID int64  `xorm:"org_id"`
	UID   string `xorm:"uid"`
}

AlertRuleKey is the alert definition identifier

func GenerateRuleKey

func GenerateRuleKey(orgID int64) AlertRuleKey

GenerateRuleKey generates a random alert rule key

func (AlertRuleKey) LogContext

func (k AlertRuleKey) LogContext() []interface{}

func (AlertRuleKey) String

func (k AlertRuleKey) String() string

type AlertRuleKeyWithVersion

type AlertRuleKeyWithVersion struct {
	Version      int64
	AlertRuleKey `xorm:"extends"`
}

type AlertRuleMutator

type AlertRuleMutator func(*AlertRule)

func WithGroupIndex

func WithGroupIndex(groupIndex int) AlertRuleMutator

func WithNamespace

func WithNamespace(namespace *models2.Folder) AlertRuleMutator

func WithNotEmptyLabels

func WithNotEmptyLabels(count int, prefix string) AlertRuleMutator

func WithOrgID

func WithOrgID(orgId int64) AlertRuleMutator

func WithSequentialGroupIndex

func WithSequentialGroupIndex() AlertRuleMutator

func WithUniqueGroupIndex

func WithUniqueGroupIndex() AlertRuleMutator

func WithUniqueID

func WithUniqueID() AlertRuleMutator

type AlertRuleVersion

type AlertRuleVersion struct {
	ID               int64  `xorm:"pk autoincr 'id'"`
	RuleOrgID        int64  `xorm:"rule_org_id"`
	RuleUID          string `xorm:"rule_uid"`
	RuleNamespaceUID string `xorm:"rule_namespace_uid"`
	RuleGroup        string
	RuleGroupIndex   int `xorm:"rule_group_idx"`
	ParentVersion    int64
	RestoredFrom     int64
	Version          int64

	Created         time.Time
	Title           string
	Condition       string
	Data            []AlertQuery
	IntervalSeconds int64
	NoDataState     NoDataState
	ExecErrState    ExecutionErrorState
	// ideally this field should have been apimodels.ApiDuration
	// but this is currently not possible because of circular dependencies
	For         time.Duration
	Annotations map[string]string
	Labels      map[string]string
}

AlertRuleVersion is the model for alert rule versions in unified alerting.

type AlertmanagersChoice

type AlertmanagersChoice int
const (
	AllAlertmanagers AlertmanagersChoice = iota
	InternalAlertmanager
	ExternalAlertmanagers
)

func StringToAlertmanagersChoice

func StringToAlertmanagersChoice(str string) (AlertmanagersChoice, error)

func (AlertmanagersChoice) String

func (amc AlertmanagersChoice) String() string

String implements the Stringer interface

type Condition

type Condition struct {
	// Condition is the RefID of the query or expression from
	// the Data property to get the results for.
	Condition string `json:"condition"`

	// Data is an array of data source queries and/or server side expressions.
	Data []AlertQuery `json:"data"`
}

Condition contains backend expressions and queries and the RefID of the query or expression that will be evaluated.

func (Condition) IsValid

func (c Condition) IsValid() bool

IsValid checks the condition's validity.

type Duration

type Duration time.Duration

Duration is a type used for marshalling durations.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (Duration) MarshalYAML

func (d Duration) MarshalYAML() (interface{}, error)

func (Duration) String

func (d Duration) String() string

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error

type ExecutionErrorState

type ExecutionErrorState string

swagger:enum ExecutionErrorState

const (
	AlertingErrState ExecutionErrorState = "Alerting"
	ErrorErrState    ExecutionErrorState = "Error"
	OkErrState       ExecutionErrorState = "OK"
)

func ErrStateFromString

func ErrStateFromString(opt string) (ExecutionErrorState, error)

func (ExecutionErrorState) String

func (executionErrorState ExecutionErrorState) String() string

type GetAlertRuleByUIDQuery

type GetAlertRuleByUIDQuery struct {
	UID   string
	OrgID int64

	Result *AlertRule
}

GetAlertRuleByUIDQuery is the query for retrieving/deleting an alert rule by UID and organisation ID.

type GetAlertRulesForSchedulingQuery

type GetAlertRulesForSchedulingQuery struct {
	PopulateFolders bool

	ResultRules         []*AlertRule
	ResultFoldersTitles map[string]string
}

type GetAlertRulesGroupByRuleUIDQuery

type GetAlertRulesGroupByRuleUIDQuery struct {
	UID   string
	OrgID int64

	Result []*AlertRule
}

GetAlertRulesGroupByRuleUIDQuery is the query for retrieving a group of alerts by UID of a rule that belongs to that group

type GetLatestAlertmanagerConfigurationQuery

type GetLatestAlertmanagerConfigurationQuery struct {
	OrgID  int64
	Result *AlertConfiguration
}

GetLatestAlertmanagerConfigurationQuery is the query to get the latest alertmanager configuration.

type Image

type Image struct {
	ID        int64     `xorm:"pk autoincr 'id'"`
	Token     string    `xorm:"token"`
	Path      string    `xorm:"path"`
	URL       string    `xorm:"url"`
	CreatedAt time.Time `xorm:"created_at"`
	ExpiresAt time.Time `xorm:"expires_at"`
}

func (*Image) ExtendDuration

func (i *Image) ExtendDuration(d time.Duration)

ExtendDuration extends the expiration time of the image. It can shorten the duration of the image if d is negative.

func (*Image) HasExpired

func (i *Image) HasExpired() bool

HasExpired returns true if the image has expired.

func (*Image) HasPath

func (i *Image) HasPath() bool

HasPath returns true if the image has a path on disk.

func (*Image) HasURL

func (i *Image) HasURL() bool

HasURL returns true if the image has a URL.

func (*Image) TableName

func (i *Image) TableName() string

A XORM interface that defines the used table for this struct.

type InstanceLabels

type InstanceLabels data.Labels

InstanceLabels is an extension to data.Labels with methods for database serialization.

func (*InstanceLabels) FromDB

func (il *InstanceLabels) FromDB(b []byte) error

FromDB loads labels stored in the database as json tuples into InstanceLabels. FromDB is part of the xorm Conversion interface.

func (*InstanceLabels) StringAndHash

func (il *InstanceLabels) StringAndHash() (string, string, error)

StringAndHash returns a the json representation of the labels as tuples sorted by key. It also returns the a hash of that representation.

func (*InstanceLabels) StringKey

func (il *InstanceLabels) StringKey() (string, error)

func (*InstanceLabels) ToDB

func (il *InstanceLabels) ToDB() ([]byte, error)

ToDB is not implemented as serialization is handled with manual SQL queries). ToDB is part of the xorm Conversion interface.

type InstanceStateType

type InstanceStateType string

InstanceStateType is an enum for instance states.

const (
	// InstanceStateFiring is for a firing alert.
	InstanceStateFiring InstanceStateType = "Alerting"
	// InstanceStateNormal is for a normal alert.
	InstanceStateNormal InstanceStateType = "Normal"
	// InstanceStatePending is for an alert that is firing but has not met the duration
	InstanceStatePending InstanceStateType = "Pending"
	// InstanceStateNoData is for an alert with no data.
	InstanceStateNoData InstanceStateType = "NoData"
	// InstanceStateError is for a erroring alert.
	InstanceStateError InstanceStateType = "Error"
)

func (InstanceStateType) IsValid

func (i InstanceStateType) IsValid() bool

IsValid checks that the value of InstanceStateType is a valid string.

type LabelOption

type LabelOption func(map[string]string)

func WithoutInternalLabels

func WithoutInternalLabels() LabelOption

type ListAlertInstancesQuery

type ListAlertInstancesQuery struct {
	RuleOrgID   int64 `json:"-"`
	RuleUID     string
	State       InstanceStateType
	StateReason string

	Result []*AlertInstance
}

ListAlertInstancesQuery is the query list alert Instances.

type ListAlertRulesQuery

type ListAlertRulesQuery struct {
	OrgID         int64
	NamespaceUIDs []string
	ExcludeOrgs   []int64
	RuleGroup     string

	// DashboardUID and PanelID are optional and allow filtering rules
	// to return just those for a dashboard and panel.
	DashboardUID string
	PanelID      int64

	Result RulesGroup
}

ListAlertRulesQuery is the query for listing alert rules

type ListNamespaceAlertRulesQuery

type ListNamespaceAlertRulesQuery struct {
	OrgID int64
	// Namespace is the folder slug
	NamespaceUID string

	Result []*AlertRule
}

ListNamespaceAlertRulesQuery is the query for listing namespace alert rules

type ListOrgRuleGroupsQuery

type ListOrgRuleGroupsQuery struct {
	OrgID         int64
	NamespaceUIDs []string

	// DashboardUID and PanelID are optional and allow filtering rules
	// to return just those for a dashboard and panel.
	DashboardUID string
	PanelID      int64

	Result [][]string
}

ListOrgRuleGroupsQuery is the query for listing unique rule groups for an organization

type NoDataState

type NoDataState string

swagger:enum NoDataState

const (
	Alerting NoDataState = "Alerting"
	NoData   NoDataState = "NoData"
	OK       NoDataState = "OK"
)

func NoDataStateFromString

func NoDataStateFromString(state string) (NoDataState, error)

func (NoDataState) String

func (noDataState NoDataState) String() string

type Provenance

type Provenance string
const (
	// ProvenanceNone reflects the provenance when no provenance is stored
	// for the requested object in the database.
	ProvenanceNone Provenance = ""
	ProvenanceAPI  Provenance = "api"
	ProvenanceFile Provenance = "file"
)

type Provisionable

type Provisionable interface {
	ResourceType() string
	ResourceID() string
}

Provisionable represents a resource that can be created through a provisioning mechanism, such as Terraform or config file.

type RelativeTimeRange

type RelativeTimeRange struct {
	From Duration `json:"from" yaml:"from"`
	To   Duration `json:"to" yaml:"to"`
}

RelativeTimeRange is the per query start and end time for requests.

func (*RelativeTimeRange) ToTimeRange

func (rtr *RelativeTimeRange) ToTimeRange(now time.Time) backend.TimeRange

type RulesGroup

type RulesGroup []*AlertRule

func (RulesGroup) SortByGroupIndex

func (g RulesGroup) SortByGroupIndex()

type SaveAlertmanagerConfigurationCmd

type SaveAlertmanagerConfigurationCmd struct {
	AlertmanagerConfiguration string
	FetchedConfigurationHash  string
	ConfigurationVersion      string
	Default                   bool
	OrgID                     int64
}

SaveAlertmanagerConfigurationCmd is the command to save an alertmanager configuration.

type UpdateRule

type UpdateRule struct {
	Existing *AlertRule
	New      AlertRule
}

Jump to

Keyboard shortcuts

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