models

package
v11.1.4-modfix Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2024 License: AGPL-3.0 Imports: 36 Imported by: 0

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	RuleTypeAlerting  = "alerting"
	RuleTypeRecording = "recording"
)
View Source
const (
	// Annotations are actually a set of labels, so technically this is the label name of an annotation.
	DashboardUIDAnnotation = "__dashboardUid__"
	PanelIDAnnotation      = "__panelId__"

	// 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"

	// MigratedLabelPrefix is a label prefix for all labels created during legacy migration.
	MigratedLabelPrefix = "__legacy_"
	// MigratedUseLegacyChannelsLabel is created during legacy migration to route to separate nested policies for migrated channels.
	MigratedUseLegacyChannelsLabel = MigratedLabelPrefix + "use_channels__"
	// MigratedContactLabelPrefix is created during legacy migration to route a migrated alert rule to a specific migrated channel.
	MigratedContactLabelPrefix = MigratedLabelPrefix + "c_"
	// MigratedSilenceLabelErrorKeepState is a label that will match a silence rule intended for legacy alerts with error state = keep_state.
	MigratedSilenceLabelErrorKeepState = MigratedLabelPrefix + "silence_error_keep_state__"
	// MigratedSilenceLabelNodataKeepState is a label that will match a silence rule intended for legacy alerts with nodata state = keep_state.
	MigratedSilenceLabelNodataKeepState = MigratedLabelPrefix + "silence_nodata_keep_state__"
	// MigratedAlertIdAnnotation is created during legacy migration to store the ID of the migrated legacy alert rule.
	MigratedAlertIdAnnotation = "__alertId__"
	// MigratedMessageAnnotation is created during legacy migration to store the migrated alert message.
	MigratedMessageAnnotation = "message"

	// AutogeneratedRouteLabel a label name used to distinguish alerts that are supposed to be handled by the autogenerated policy. Only expected value is `true`.
	AutogeneratedRouteLabel = "__grafana_autogenerated__"
	// AutogeneratedRouteReceiverNameLabel a label name that contains the name of the receiver that should be used to send notifications for the alert.
	AutogeneratedRouteReceiverNameLabel = "__grafana_receiver__"
	// AutogeneratedRouteSettingsHashLabel a label name that contains the hash of the notification settings that will be used to send notifications for the alert.
	// This should uniquely identify the notification settings (group_by, group_wait, group_interval, repeat_interval, mute_time_intervals) for the alert.
	AutogeneratedRouteSettingsHashLabel = "__grafana_route_settings_hash__"
)
View Source
const (
	StateReasonMissingSeries = "MissingSeries"
	StateReasonNoData        = "NoData"
	StateReasonError         = "Error"
	StateReasonPaused        = "Paused"
	StateReasonUpdated       = "Updated"
	StateReasonRuleDeleted   = "RuleDeleted"
	StateReasonKeepLast      = "KeepLast"
)
View Source
const (
	QuotaTargetSrv quota.TargetSrv = "ngalert"
	QuotaTarget    quota.Target    = "alert_rule"
)
View Source
const (
	// FromAlertHeaderName name of header added to datasource query requests
	// to denote request is originating from Grafana Alerting.
	//
	// Data sources might check this in query method as sometimes alerting
	// needs special considerations.
	// Several existing systems also compare against the value of this header.
	// Altering this constitutes a breaking change.
	//
	// Note: The spelling of this headers is intentionally degenerate from the
	// others for compatibility reasons. When sent over a network, the key of
	// this header is canonicalized to "Fromalert".
	// However, some datasources still compare against the string "FromAlert".
	FromAlertHeaderName = "FromAlert"

	// CacheSkipHeaderName name of header added to datasource query requests
	// to denote request should not be cached.
	CacheSkipHeaderName = "X-Cache-Skip"
)
View Source
const AlertConfigurationVersion = 1
View Source
const GroupByAll = "..."

GroupByAll is a special value defined by alertmanager that can be used in a Route's GroupBy field to aggregate by all possible labels.

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("rule title under the same organisation and folder should be unique")
	ErrQuotaReached                       = errors.New("quota has been exceeded")
	// ErrNoDashboard is returned when the alert rule does not have a Dashboard UID
	// in its annotations or the dashboard does not exist.
	ErrNoDashboard = errors.New("no dashboard")

	// ErrNoPanel is returned when the alert rule does not have a PanelID in its
	// annotations.
	ErrNoPanel = errors.New("no panel")
)
View Source
var (
	// InternalLabelNameSet are labels that grafana automatically include as part of the labelset.
	InternalLabelNameSet = map[string]struct{}{
		alertingModels.RuleUIDLabel:      {},
		alertingModels.NamespaceUIDLabel: {},
	}
	InternalAnnotationNameSet = map[string]struct{}{
		DashboardUIDAnnotation:              {},
		PanelIDAnnotation:                   {},
		alertingModels.ImageTokenAnnotation: {},
	}

	// LabelsUserCannotSpecify are labels that the user cannot specify when creating an alert rule.
	LabelsUserCannotSpecify = map[string]struct{}{
		AutogeneratedRouteLabel:             {},
		AutogeneratedRouteReceiverNameLabel: {},
		AutogeneratedRouteSettingsHashLabel: {},
	}
)
View Source
var (
	ErrAlertRuleConflictBase = errutil.Conflict("alerting.alert-rule.conflict").
								MustTemplate(errAlertRuleConflictMsg, errutil.WithPublic(errAlertRuleConflictMsg))
	ErrAlertRuleGroupNotFound       = errutil.NotFound("alerting.alert-rule.notFound")
	ErrInvalidRelativeTimeRangeBase = errutil.BadRequest("alerting.alert-rule.invalidRelativeTime").MustTemplate("Invalid alert rule query {{ .Public.RefID }}: invalid relative time range [From: {{ .Public.From }}, To: {{ .Public.To }}]")
)
View Source
var (
	RuleMuts = AlertRuleMutators{}
	NSMuts   = NotificationSettingsMutators{}
	RuleGen  = &AlertRuleGenerator{
		mutators: []AlertRuleMutator{
			RuleMuts.WithUniqueUID(), RuleMuts.WithUniqueTitle(),
		},
	}
)
View Source
var DefaultNotificationSettingsGroupBy = []string{FolderTitleLabel, model.AlertNameLabel}

DefaultNotificationSettingsGroupBy are the default required GroupBy fields for notification settings.

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 (
	SilenceMuts = SilenceMutators{}
)

Functions ¶

func AlertRuleGroupKeyByNamespaceAndRuleGroup ¶

func AlertRuleGroupKeyByNamespaceAndRuleGroup(k1, k2 *AlertRuleGroupKey) bool

func AlertRulesByGroupKeyAndIndex ¶

func AlertRulesByGroupKeyAndIndex(a1, a2 *AlertRule) bool

func AlertRulesByIndex ¶

func AlertRulesByIndex(a1, a2 *AlertRule) bool

AlertRulesByIndex orders alert rules by rule group index. You should make sure that all alert rules belong to the same rule group (have the same RuleGroupKey) before using this ordering.

func ConcatReasons ¶

func ConcatReasons(reasons ...string) string

func CopyMatchers ¶

func CopyMatchers(matchers []*amv2.Matcher) []*amv2.Matcher

CopyMatchers creates a deep copy of Matchers.

func ErrAlertRuleConflict ¶

func ErrAlertRuleConflict(rule AlertRule, underlying error) error

func ErrInvalidRelativeTimeRange ¶

func ErrInvalidRelativeTimeRange(refID string, rtr RelativeTimeRange) error

func GenerateAlertLabels ¶

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

func GroupByAlertRuleGroupKey ¶

func GroupByAlertRuleGroupKey(rules []*AlertRule) map[AlertRuleGroupKey]RulesGroup

GroupByAlertRuleGroupKey groups all rules by AlertRuleGroupKey. Returns map of RulesGroup sorted by AlertRule.RuleGroupIndex

func NotificationSettingsGen ¶

func NotificationSettingsGen(mutators ...Mutator[NotificationSettings]) func() NotificationSettings

NotificationSettingsGen generates NotificationSettings using a base and mutators.

func PatchPartialAlertRule ¶

func PatchPartialAlertRule(existingRule *AlertRule, ruleToPatch *AlertRuleWithOptionals)

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 SilenceGen ¶

func SilenceGen(mutators ...Mutator[Silence]) func() Silence

SilenceGen generates Silence using a base and mutators.

func SortAlertRuleGroupWithFolderTitle ¶

func SortAlertRuleGroupWithFolderTitle(g []AlertRuleGroupWithFolderFullpath)

SortAlertRuleGroupWithFolderTitle sorts AlertRuleGroupWithFolderTitle by folder UID and group name

func SortAlertRulesByGroupIndex ¶

func SortAlertRulesByGroupIndex(rules []AlertRule)

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

func WithRuleKey ¶

func WithRuleKey(ctx context.Context, ruleKey AlertRuleKey) context.Context

Types ¶

type AdminConfiguration ¶

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

	// 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.

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
	ResultFingerprint string
}

AlertInstance represents a single alert instance.

func AlertInstanceGen ¶

func AlertInstanceGen(mutators ...AlertInstanceMutator) *AlertInstance

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

type AlertInstanceKey ¶

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

type AlertInstanceMutator ¶

type AlertInstanceMutator func(*AlertInstance)

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 '__expr__' 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 CreateHysteresisExpression ¶

func CreateHysteresisExpression(t *testing.T, refID string, inputRefID string, threshold int, recoveryThreshold int) AlertQuery

func CreateLokiQuery ¶

func CreateLokiQuery(refID string, expr string, intervalMs int64, maxDataPoints int64, queryType string, datasourceUID string) AlertQuery

func CreatePrometheusQuery ¶

func CreatePrometheusQuery(refID string, expr string, intervalMs int64, maxDataPoints int64, isInstant bool, datasourceUID string) AlertQuery

func CreateReduceExpression ¶

func CreateReduceExpression(refID string, inputRefID string, reducer string) 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) IsHysteresisExpression ¶

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

IsHysteresisExpression returns true if the model describes a hysteresis command expression. Returns error if the Model is not a valid JSON

func (*AlertQuery) PatchHysteresisExpression ¶

func (aq *AlertQuery) PatchHysteresisExpression(loadedMetrics map[data.Fingerprint]struct{}) error

PatchHysteresisExpression updates the AlertQuery to include loaded metrics into hysteresis

func (*AlertQuery) PreSave ¶

func (aq *AlertQuery) PreSave() error

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

func (*AlertQuery) String ¶

func (aq *AlertQuery) String() string

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"`
	Record          *Record `xorm:"json"`
	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
	IsPaused             bool
	NotificationSettings []NotificationSettings `xorm:"notification_settings"` // we use slice to workaround xorm mapping that does not serialize a struct to JSON unless it's a slice
}

AlertRule is the model for alert rules in unified alerting.

func CopyRule ¶

func CopyRule(r *AlertRule, mutators ...AlertRuleMutator) *AlertRule

CopyRule creates a deep copy of AlertRule

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) GetDashboardUID ¶

func (alertRule *AlertRule) GetDashboardUID() string

GetDashboardUID returns the DashboardUID or "".

func (*AlertRule) GetEvalCondition ¶

func (alertRule *AlertRule) GetEvalCondition() Condition

func (*AlertRule) GetFolderKey ¶

func (alertRule *AlertRule) GetFolderKey() FolderKey

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) GetNamespaceUID ¶

func (alertRule *AlertRule) GetNamespaceUID() string

func (*AlertRule) GetPanelID ¶

func (alertRule *AlertRule) GetPanelID() int64

GetPanelID returns the Panel ID or -1.

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) SetDashboardAndPanelFromAnnotations ¶

func (alertRule *AlertRule) SetDashboardAndPanelFromAnnotations() error

SetDashboardAndPanelFromAnnotations will set the DashboardUID and PanelID field by doing a lookup in the annotations. Errors when the found annotations are not valid.

func (*AlertRule) Type ¶

func (alertRule *AlertRule) Type() RuleType

func (*AlertRule) ValidateAlertRule ¶

func (alertRule *AlertRule) ValidateAlertRule(cfg setting.UnifiedAlertingSettings) error

ValidateAlertRule validates various alert rule fields.

type AlertRuleGenerator ¶

type AlertRuleGenerator struct {
	AlertRuleMutators
	// contains filtered or unexported fields
}

func (*AlertRuleGenerator) Generate ¶

func (g *AlertRuleGenerator) Generate() AlertRule

func (*AlertRuleGenerator) GenerateLabels ¶

func (g *AlertRuleGenerator) GenerateLabels(min, max int, prefix string) data.Labels

func (*AlertRuleGenerator) GenerateMany ¶

func (g *AlertRuleGenerator) GenerateMany(bounds ...int) []AlertRule

func (*AlertRuleGenerator) GenerateManyRef ¶

func (g *AlertRuleGenerator) GenerateManyRef(bounds ...int) []*AlertRule

func (*AlertRuleGenerator) GenerateQuery ¶

func (g *AlertRuleGenerator) GenerateQuery() AlertQuery

func (*AlertRuleGenerator) GenerateRef ¶

func (g *AlertRuleGenerator) GenerateRef() *AlertRule

func (*AlertRuleGenerator) With ¶

func (*AlertRuleGenerator) WithCondition ¶

func (g *AlertRuleGenerator) WithCondition(condition string) AlertRuleMutator

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 AlertRuleGroupKeyBy ¶

type AlertRuleGroupKeyBy func(a1, a2 *AlertRuleGroupKey) bool

AlertRuleGroupKeyBy is a function that defines the ordering of alert rule group keys.

func (AlertRuleGroupKeyBy) Sort ¶

func (by AlertRuleGroupKeyBy) Sort(keys []AlertRuleGroupKey)

type AlertRuleGroupKeySorter ¶

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

func (AlertRuleGroupKeySorter) Len ¶

func (s AlertRuleGroupKeySorter) Len() int

func (AlertRuleGroupKeySorter) Less ¶

func (s AlertRuleGroupKeySorter) Less(i, j int) bool

func (AlertRuleGroupKeySorter) Swap ¶

func (s AlertRuleGroupKeySorter) Swap(i, j int)

type AlertRuleGroupWithFolderFullpath ¶

type AlertRuleGroupWithFolderFullpath struct {
	*AlertRuleGroup
	OrgID          int64
	FolderFullpath string
}

AlertRuleGroupWithFolderFullpath extends AlertRuleGroup with orgID and folder title

func NewAlertRuleGroupWithFolderFullpath ¶

func NewAlertRuleGroupWithFolderFullpath(groupKey AlertRuleGroupKey, rules []AlertRule, folderFullpath string) AlertRuleGroupWithFolderFullpath

func NewAlertRuleGroupWithFolderFullpathFromRulesGroup ¶

func NewAlertRuleGroupWithFolderFullpathFromRulesGroup(groupKey AlertRuleGroupKey, rules RulesGroup, folderFullpath string) AlertRuleGroupWithFolderFullpath

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 RuleKeyFromContext ¶

func RuleKeyFromContext(ctx context.Context) (AlertRuleKey, bool)

func (AlertRuleKey) LogContext ¶

func (k AlertRuleKey) LogContext() []any

func (AlertRuleKey) String ¶

func (k AlertRuleKey) String() string

type AlertRuleKeyWithId ¶

type AlertRuleKeyWithId struct {
	AlertRuleKey
	ID int64
}

type AlertRuleKeyWithVersion ¶

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

type AlertRuleMutator ¶

type AlertRuleMutator func(r *AlertRule)

type AlertRuleMutators ¶

type AlertRuleMutators struct {
}

func (*AlertRuleMutators) WithAllRecordingRules ¶

func (a *AlertRuleMutators) WithAllRecordingRules() AlertRuleMutator

func (*AlertRuleMutators) WithAnnotation ¶

func (a *AlertRuleMutators) WithAnnotation(key, value string) AlertRuleMutator

func (*AlertRuleMutators) WithAnnotations ¶

func (a *AlertRuleMutators) WithAnnotations(lbls data.Labels) AlertRuleMutator

func (*AlertRuleMutators) WithDashboardAndPanel ¶

func (a *AlertRuleMutators) WithDashboardAndPanel(dashboardUID *string, panelID *int64) AlertRuleMutator

func (*AlertRuleMutators) WithErrorExecAs ¶

func (a *AlertRuleMutators) WithErrorExecAs(err ExecutionErrorState) AlertRuleMutator

func (*AlertRuleMutators) WithFor ¶

func (a *AlertRuleMutators) WithFor(duration time.Duration) AlertRuleMutator

func (*AlertRuleMutators) WithForNTimes ¶

func (a *AlertRuleMutators) WithForNTimes(timesOfInterval int64) AlertRuleMutator

func (*AlertRuleMutators) WithGroupIndex ¶

func (a *AlertRuleMutators) WithGroupIndex(groupIndex int) AlertRuleMutator

func (*AlertRuleMutators) WithGroupKey ¶

func (a *AlertRuleMutators) WithGroupKey(groupKey AlertRuleGroupKey) AlertRuleMutator

func (*AlertRuleMutators) WithGroupName ¶

func (a *AlertRuleMutators) WithGroupName(groupName string) AlertRuleMutator

func (*AlertRuleMutators) WithGroupPrefix ¶

func (a *AlertRuleMutators) WithGroupPrefix(prefix string) AlertRuleMutator

func (*AlertRuleMutators) WithInterval ¶

func (a *AlertRuleMutators) WithInterval(interval time.Duration) AlertRuleMutator

func (*AlertRuleMutators) WithIntervalBetween ¶

func (a *AlertRuleMutators) WithIntervalBetween(min, max int64) AlertRuleMutator

func (*AlertRuleMutators) WithIntervalMatching ¶

func (a *AlertRuleMutators) WithIntervalMatching(baseInterval time.Duration) AlertRuleMutator

WithIntervalMatching mutator that generates random interval and `for` duration that are times of the provided base interval.

func (*AlertRuleMutators) WithIntervalSeconds ¶

func (a *AlertRuleMutators) WithIntervalSeconds(seconds int64) AlertRuleMutator

func (*AlertRuleMutators) WithIsPaused ¶

func (a *AlertRuleMutators) WithIsPaused(paused bool) AlertRuleMutator

func (*AlertRuleMutators) WithLabel ¶

func (a *AlertRuleMutators) WithLabel(key, value string) AlertRuleMutator

func (*AlertRuleMutators) WithLabels ¶

func (a *AlertRuleMutators) WithLabels(lbls data.Labels) AlertRuleMutator

func (*AlertRuleMutators) WithMetric ¶

func (a *AlertRuleMutators) WithMetric(metric string) AlertRuleMutator

func (*AlertRuleMutators) WithNamespace ¶

func (a *AlertRuleMutators) WithNamespace(namespace *folder.Folder) AlertRuleMutator

func (*AlertRuleMutators) WithNamespaceUID ¶

func (a *AlertRuleMutators) WithNamespaceUID(namespaceUID string) AlertRuleMutator

func (*AlertRuleMutators) WithNamespaceUIDNotIn ¶

func (a *AlertRuleMutators) WithNamespaceUIDNotIn(exclude ...string) AlertRuleMutator

WithNamespaceUIDNotIn generates a random namespace UID if it is among excluded

func (*AlertRuleMutators) WithNoDataExecAs ¶

func (a *AlertRuleMutators) WithNoDataExecAs(nodata NoDataState) AlertRuleMutator

func (*AlertRuleMutators) WithNoNotificationSettings ¶

func (a *AlertRuleMutators) WithNoNotificationSettings() AlertRuleMutator

func (*AlertRuleMutators) WithNotEmptyLabels ¶

func (a *AlertRuleMutators) WithNotEmptyLabels(count int, prefix string) AlertRuleMutator

func (*AlertRuleMutators) WithNotificationSettings ¶

func (a *AlertRuleMutators) WithNotificationSettings(ns NotificationSettings) AlertRuleMutator

func (*AlertRuleMutators) WithNotificationSettingsGen ¶

func (a *AlertRuleMutators) WithNotificationSettingsGen(ns func() NotificationSettings) AlertRuleMutator

func (*AlertRuleMutators) WithOrgID ¶

func (a *AlertRuleMutators) WithOrgID(orgId int64) AlertRuleMutator

func (*AlertRuleMutators) WithQuery ¶

func (a *AlertRuleMutators) WithQuery(query ...AlertQuery) AlertRuleMutator

func (*AlertRuleMutators) WithRandomRecordingRules ¶

func (a *AlertRuleMutators) WithRandomRecordingRules() AlertRuleMutator

func (*AlertRuleMutators) WithRecordFrom ¶

func (a *AlertRuleMutators) WithRecordFrom(from string) AlertRuleMutator

func (*AlertRuleMutators) WithSameGroup ¶

func (a *AlertRuleMutators) WithSameGroup() AlertRuleMutator

WithSameGroup generates a random group name and assigns it to all rules passed to it

func (*AlertRuleMutators) WithSequentialGroupIndex ¶

func (a *AlertRuleMutators) WithSequentialGroupIndex() AlertRuleMutator

func (*AlertRuleMutators) WithTitle ¶

func (a *AlertRuleMutators) WithTitle(title string) AlertRuleMutator

func (*AlertRuleMutators) WithUniqueGroupIndex ¶

func (a *AlertRuleMutators) WithUniqueGroupIndex() AlertRuleMutator

func (*AlertRuleMutators) WithUniqueID ¶

func (a *AlertRuleMutators) WithUniqueID() AlertRuleMutator

func (*AlertRuleMutators) WithUniqueOrgID ¶

func (a *AlertRuleMutators) WithUniqueOrgID() AlertRuleMutator

func (*AlertRuleMutators) WithUniqueTitle ¶

func (a *AlertRuleMutators) WithUniqueTitle() AlertRuleMutator

WithUniqueTitle returns AlertRuleMutator that generates a random title if the rule's title is among titles known by the instance of mutator. Two instances of the mutator do not share known titles. Example #1 reuse mutator instance:

mut := WithUniqueTitle()
rule1 := RuleGen.With(mut).Generate()
rule2 := RuleGen.With(mut).Generate()

Example #2 reuse generator:

gen := RuleGen.With(WithUniqueTitle())
rule1 := gen.Generate()
rule2 := gen.Generate()

Example #3 non-unique:

rule1 := RuleGen.With(WithUniqueTitle()).Generate
rule2 := RuleGen.With(WithUniqueTitle()).Generate

func (*AlertRuleMutators) WithUniqueUID ¶

func (a *AlertRuleMutators) WithUniqueUID() AlertRuleMutator

WithUniqueUID returns AlertRuleMutator that generates a random UID if it is among UIDs known by the instance of mutator. NOTE: two instances of the mutator do not share known UID. Example #1 reuse mutator instance:

mut := WithUniqueUID()
rule1 := RuleGen.With(mut).Generate()
rule2 := RuleGen.With(mut).Generate()

Example #2 reuse generator:

gen := RuleGen.With(WithUniqueUID())
rule1 := gen.Generate()
rule2 := gen.Generate()

Example #3 non-unique:

rule1 := RuleGen.With(WithUniqueUID()).Generate
rule2 := RuleGen.With(WithUniqueUID()).Generate

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
	Record          *Record `xorm:"json"`
	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
	IsPaused             bool
	NotificationSettings []NotificationSettings `xorm:"notification_settings"` // we use slice to workaround xorm mapping that does not serialize a struct to JSON unless it's a slice
}

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

type AlertRuleWithOptionals ¶

type AlertRuleWithOptionals struct {
	AlertRule
	// This parameter is to know if an optional API field was sent and, therefore, patch it with the current field from
	// DB in case it was not sent.
	HasPause bool
}

AlertRuleWithOptionals This is to avoid having to pass in additional arguments deep in the call stack. Alert rule object is created in an early validation step without knowledge about current alert rule fields or if they need to be overridden. This is done in a later step and, in that step, we did not have knowledge about if a field was optional nor its possible value.

type AlertRulesBy ¶

type AlertRulesBy func(a1, a2 *AlertRule) bool

AlertsRulesBy is a function that defines the ordering of alert rules.

func (AlertRulesBy) Sort ¶

func (by AlertRulesBy) Sort(rules []*AlertRule)

type AlertRulesSorter ¶

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

func (AlertRulesSorter) Len ¶

func (s AlertRulesSorter) Len() int

func (AlertRulesSorter) Less ¶

func (s AlertRulesSorter) Less(i, j int) bool

func (AlertRulesSorter) Swap ¶

func (s AlertRulesSorter) Swap(i, j int)

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 CountAlertRulesQuery ¶

type CountAlertRulesQuery struct {
	OrgID        int64
	NamespaceUID string
}

CountAlertRulesQuery is the query for counting alert rules

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() (any, 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(any) error) error

type ExecutionErrorState ¶

type ExecutionErrorState string

swagger:enum ExecutionErrorState

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

func ErrStateFromString ¶

func ErrStateFromString(opt string) (ExecutionErrorState, error)

func (ExecutionErrorState) String ¶

func (executionErrorState ExecutionErrorState) String() string

type FolderKey ¶

type FolderKey struct {
	OrgID int64
	UID   string
}

func (FolderKey) String ¶

func (f FolderKey) String() string

type GetAlertRuleByUIDQuery ¶

type GetAlertRuleByUIDQuery struct {
	UID   string
	OrgID int64
}

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

type GetAlertRulesForSchedulingQuery ¶

type GetAlertRulesForSchedulingQuery struct {
	PopulateFolders bool
	RuleGroups      []string

	ResultRules []*AlertRule
	// A map of folder UID to folder Title in NamespaceKey format (see GetNamespaceKey)
	ResultFoldersTitles map[FolderKey]string
}

type GetAlertRulesGroupByRuleUIDQuery ¶

type GetAlertRulesGroupByRuleUIDQuery struct {
	UID   string
	OrgID int64
}

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

type GetReceiverQuery ¶

type GetReceiverQuery struct {
	OrgID   int64
	Name    string
	Decrypt bool
}

GetReceiverQuery represents a query for a single receiver.

type GetReceiversQuery ¶

type GetReceiversQuery struct {
	OrgID   int64
	Names   []string
	Limit   int
	Offset  int
	Decrypt bool
}

GetReceiversQuery represents a query for receiver groups.

type HistoricAlertConfiguration ¶

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

	// LastApplied a timestamp indicating the most recent time at which the configuration was applied to an Alertmanager, or 0 otherwise.
	// Only set this field if the configuration has been applied by the caller.
	LastApplied int64 `xorm:"last_applied"`
}

HistoricAlertConfiguration represents a previously used alerting configuration.

func HistoricConfigFromAlertConfig ¶

func HistoricConfigFromAlertConfig(config AlertConfiguration) HistoricAlertConfiguration

type HistoryQuery ¶

type HistoryQuery struct {
	RuleUID      string
	OrgID        int64
	DashboardUID string
	PanelID      int64
	Labels       map[string]string
	From         time.Time
	To           time.Time
	Limit        int
	SignedInUser identity.Requester
}

HistoryQuery represents a query for alert state history.

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 an 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 {
	RuleUID   string
	RuleOrgID int64 `json:"-"`
}

ListAlertInstancesQuery is the query list alert Instances.

type ListAlertRulesQuery ¶

type ListAlertRulesQuery struct {
	OrgID         int64
	RuleUIDs      []string
	NamespaceUIDs []string
	ExcludeOrgs   []int64
	RuleGroups    []string

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

	ReceiverName string
}

ListAlertRulesQuery is the query for listing alert rules

type ListNamespaceAlertRulesQuery ¶

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

ListNamespaceAlertRulesQuery is the query for listing namespace alert rules

type ListNotificationSettingsQuery ¶

type ListNotificationSettingsQuery struct {
	OrgID        int64
	ReceiverName string
}

type MarkConfigurationAsAppliedCmd ¶

type MarkConfigurationAsAppliedCmd struct {
	OrgID             int64
	ConfigurationHash string
}

MarkConfigurationAsAppliedCmd is the command for marking a previously saved configuration as successfully applied.

type Mutator ¶

type Mutator[T any] func(*T)

type NoDataState ¶

type NoDataState string

swagger:enum NoDataState

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

func NoDataStateFromString ¶

func NoDataStateFromString(state string) (NoDataState, error)

func (NoDataState) String ¶

func (noDataState NoDataState) String() string

type NotificationSettings ¶

type NotificationSettings struct {
	Receiver string `json:"receiver"`

	GroupBy           []string        `json:"group_by,omitempty"`
	GroupWait         *model.Duration `json:"group_wait,omitempty"`
	GroupInterval     *model.Duration `json:"group_interval,omitempty"`
	RepeatInterval    *model.Duration `json:"repeat_interval,omitempty"`
	MuteTimeIntervals []string        `json:"mute_time_intervals,omitempty"`
}

NotificationSettings represents the settings for sending notifications for a single AlertRule. It is used to automatically generate labels and an associated matching route containing the given settings.

func CopyNotificationSettings ¶

func CopyNotificationSettings(ns NotificationSettings, mutators ...Mutator[NotificationSettings]) NotificationSettings

CopyNotificationSettings creates a deep copy of NotificationSettings.

func NewDefaultNotificationSettings ¶

func NewDefaultNotificationSettings(receiver string) NotificationSettings

NewDefaultNotificationSettings creates a new default NotificationSettings with the specified receiver.

func (*NotificationSettings) Equals ¶

func (*NotificationSettings) Fingerprint ¶

func (s *NotificationSettings) Fingerprint() data.Fingerprint

Fingerprint calculates a hash value to uniquely identify a NotificationSettings by its attributes. The hash is calculated by concatenating the strings and durations of the NotificationSettings attributes and using an invalid UTF-8 sequence as a separator.

func (*NotificationSettings) IsAllDefault ¶

func (s *NotificationSettings) IsAllDefault() bool

IsAllDefault checks if the NotificationSettings object has all default values for optional fields (all except Receiver) .

func (*NotificationSettings) NormalizedGroupBy ¶

func (s *NotificationSettings) NormalizedGroupBy() []string

NormalizedGroupBy returns a consistent and ordered GroupBy.

  • If the GroupBy is empty, it returns nil so that the parent group can be inherited.
  • If the GroupBy contains the special label '...', it returns only '...'.
  • Otherwise, it returns the default GroupBy labels followed by any custom labels in sorted order.

To ensure consistent and valid generated routes, this should be used instead of GroupBy when generating fingerprints or fingerprint-level routes.

func (*NotificationSettings) ToLabels ¶

func (s *NotificationSettings) ToLabels() data.Labels

ToLabels converts the NotificationSettings into data.Labels. When added to an AlertRule these labels ensure it will match an autogenerated route with the correct settings. Labels returned:

  • AutogeneratedRouteLabel: "true"
  • AutogeneratedRouteReceiverNameLabel: Receiver
  • AutogeneratedRouteSettingsHashLabel: Fingerprint (if the NotificationSettings are not all default)

func (*NotificationSettings) Validate ¶

func (s *NotificationSettings) Validate() error

Validate checks if the NotificationSettings object is valid. It returns an error if any of the validation checks fail. The receiver must be specified. GroupWait, GroupInterval, RepeatInterval must be positive durations.

type NotificationSettingsMutators ¶

type NotificationSettingsMutators struct{}

func (NotificationSettingsMutators) WithGroupBy ¶

func (NotificationSettingsMutators) WithGroupInterval ¶

func (n NotificationSettingsMutators) WithGroupInterval(groupInterval *time.Duration) Mutator[NotificationSettings]

func (NotificationSettingsMutators) WithGroupWait ¶

func (NotificationSettingsMutators) WithMuteTimeIntervals ¶

func (n NotificationSettingsMutators) WithMuteTimeIntervals(muteTimeIntervals ...string) Mutator[NotificationSettings]

func (NotificationSettingsMutators) WithReceiver ¶

func (NotificationSettingsMutators) WithRepeatInterval ¶

func (n NotificationSettingsMutators) WithRepeatInterval(repeatInterval *time.Duration) Mutator[NotificationSettings]

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 Record ¶

type Record struct {
	// Metric indicates a metric name to send results to.
	Metric string
	// From contains a query RefID, indicating which expression node is the output of the recording rule.
	From string
}

Record contains mapping information for Recording Rules.

func (*Record) Fingerprint ¶

func (r *Record) Fingerprint() data.Fingerprint

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() expr.TimeRange

type RuleType ¶

type RuleType string

func (RuleType) String ¶

func (r RuleType) String() string

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
	LastApplied               int64
}

SaveAlertmanagerConfigurationCmd is the command to save an alertmanager configuration.

type Silence ¶

type Silence notify.GettableSilence

Silence is the model-layer representation of an alertmanager silence. Currently just a wrapper around the alerting notify.Silence.

func CopySilence ¶

func CopySilence(s Silence) Silence

CopySilence creates a deep copy of Silence.

func CopySilenceWith ¶

func CopySilenceWith(s Silence, mutators ...Mutator[Silence]) Silence

CopySilenceWith creates a deep copy of Silence and then applies mutators to it.

func (Silence) GetRuleUID ¶

func (s Silence) GetRuleUID() *string

GetRuleUID returns the rule UID of the silence if the silence is associated with a rule, otherwise nil. Currently, this works by looking for a matcher with the RuleUIDLabel name and returning its value.

type SilenceMetadata ¶

type SilenceMetadata struct {
	RuleMetadata *SilenceRuleMetadata
	Permissions  *SilencePermissionSet
}

SilenceMetadata contains metadata about a silence. Fields are pointers to allow for metadata to be optionally loaded.

type SilenceMutators ¶

type SilenceMutators struct{}

func (SilenceMutators) Expired ¶

func (n SilenceMutators) Expired() Mutator[Silence]

func (SilenceMutators) WithEmptyId ¶

func (n SilenceMutators) WithEmptyId() Mutator[Silence]

func (SilenceMutators) WithMatcher ¶

func (n SilenceMutators) WithMatcher(name, value string, matchType labels.MatchType) Mutator[Silence]

func (SilenceMutators) WithRuleUID ¶

func (n SilenceMutators) WithRuleUID(value string) Mutator[Silence]

type SilencePermission ¶

type SilencePermission string

SilencePermission is a type for representing a silence permission.

const (
	SilencePermissionRead   SilencePermission = "read"
	SilencePermissionCreate SilencePermission = "create"
	SilencePermissionWrite  SilencePermission = "write"
)

func SilencePermissions ¶

func SilencePermissions() [3]SilencePermission

SilencePermissions returns all possible silence permissions.

type SilencePermissionSet ¶

type SilencePermissionSet map[SilencePermission]bool

SilencePermissionSet represents a set of permissions for a silence.

func (SilencePermissionSet) AllSet ¶

func (p SilencePermissionSet) AllSet() bool

AllSet returns true if all possible permissions are set.

func (SilencePermissionSet) Clone ¶

Clone returns a deep copy of the permission set.

func (SilencePermissionSet) Has ¶

func (p SilencePermissionSet) Has(permission SilencePermission) bool

Has returns true if the given permission is allowed in the set.

type SilenceRuleMetadata ¶

type SilenceRuleMetadata struct {
	RuleUID   string
	RuleTitle string
	FolderUID string
}

SilenceRuleMetadata contains metadata about the rule associated with a silence.

type SilenceWithMetadata ¶

type SilenceWithMetadata struct {
	*Silence
	Metadata SilenceMetadata
}

SilenceWithMetadata is a helper type for managing a silence with associated metadata.

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