The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/pkg/services/ngalert/models/alert_rule.go

187 lines
5.0 KiB

package models
import (
"errors"
"fmt"
"time"
)
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")
)
type NoDataState string
func (noDataState NoDataState) String() string {
return string(noDataState)
}
const (
Alerting NoDataState = "Alerting"
NoData NoDataState = "NoData"
KeepLastState NoDataState = "KeepLastState"
OK NoDataState = "OK"
)
type ExecutionErrorState string
func (executionErrorState ExecutionErrorState) String() string {
return string(executionErrorState)
}
const (
AlertingErrState ExecutionErrorState = "Alerting"
KeepLastStateErrState ExecutionErrorState = "KeepLastState"
)
// AlertRule is the model for alert rules in unified alerting.
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
UID string `xorm:"uid"`
NamespaceUID string `xorm:"namespace_uid"`
RuleGroup string
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
}
Alerting: set query in rules response (#33010) * set query in rules response * Theme: tweaking dark theme colors (#33007) * Library Panels: Add library panel tab to share modal (#32953) * Explore: Scroll split panes in Explore independently (#32978) * Change default prometheus to latest and prometheus v1 to prometheus1 * Update README * Remove prometheus1 block as not used * Explore: Separatae scrolling in split view * Update snapshot * Allow skip migrations in tests via environment variable (#32958) * Dashboard: Fix issue where Slack notifications won't link to users (#32861) * DashboardPage: refactored styles from sass to emotion (#32955) * DashboardPage: refactored styles from sass to emotion * refactored dashboardPage component to be alot easier to read and understand * more refactoring... * more cleaning... * fixes frontend test * fixes frontend test- I hope * fixes frontend test- I hope * moves dashboard scss styles back to it's standalone file * GraphNG: use theme font family and size for axis labels (#33009) * GraphNG: use theme font family and size for axis labels * fix test * AlertingNG: Slack notification channel (#32675) * AlertingNG: Slack notification channel Signed-off-by: Ganesh Vernekar <ganeshvern@gmail.com> * Add tests Signed-off-by: Ganesh Vernekar <ganeshvern@gmail.com> * Fix review comments Signed-off-by: Ganesh Vernekar <ganeshvern@gmail.com> * Fix review comments and small refactoring Signed-off-by: Ganesh Vernekar <ganeshvern@gmail.com> * GraphNG: stacking (#30749) * First iteration * Dev dash * Re-use StackingMode type * Fix ts and api issues * Stacking work resurected * Fix overrides * Correct values in tooltip and updated test dashboard * Update dev dashboard * Apply correct bands for stacking * Merge fix * Update snapshot * Revert go.sum * Handle null values correctyl and make filleBelowTo and stacking mutual exclusive * Snapshots update * Graph->Time series stacking migration * Review comments * Indicate overrides in StandardEditorContext * Change stacking UI editor, migrate stacking to object option * Small refactor, fix for hiding series and dev dashboard * VizLegend: sets a min and max value of the seriesCount control in Storybook (#33022) * Alerting: Filter rules list (#32818) * Chore: Reduces strict errors (#33012) * Chore: reduces strict error in OptionPicker tests * Chore: reduces strict errors in FormDropdownCtrl * Chore: reduces has no initializer and is not definitely assigned in the constructor errors * Chore: reduces has no initializer and is not definitely assigned in the constructor errors * Chore: lowers strict count limit * Tests: updates snapshots * Tests: updates snapshots * Chore: updates after PR comments * Refactor: removes throw and changes signature for DashboardSrv.getCurrent * [Alerting]: Several modifications in alert rules (#32983) * [Alerting]: Use common properties for all rules * Add Labels in rules * Fix update ruleGroup API Return 400 Bad Request response when the request contains a UID that does not exist * Check permissions and return namespace id * Apply suggestions from code review Co-authored-by: gotjosh <josue@grafana.com> * WIP (#33025) * Chore: Bump strict error count limit (#33035) * set query in rules response Co-authored-by: Torkel Ödegaard <torkel@grafana.org> Co-authored-by: kay delaney <45561153+kaydelaney@users.noreply.github.com> Co-authored-by: Ivana Huckova <30407135+ivanahuckova@users.noreply.github.com> Co-authored-by: Dafydd <72009875+dafydd-t@users.noreply.github.com> Co-authored-by: n-wbrown <n-wbrown@users.noreply.github.com> Co-authored-by: Uchechukwu Obasi <obasiuche62@gmail.com> Co-authored-by: Leon Sorokin <leeoniya@gmail.com> Co-authored-by: Ganesh Vernekar <15064823+codesome@users.noreply.github.com> Co-authored-by: Dominik Prokop <dominik.prokop@grafana.com> Co-authored-by: Nathan Rodman <nathanrodman@gmail.com> Co-authored-by: Hugo Häggmark <hugo.haggmark@grafana.com> Co-authored-by: Sofia Papagiannaki <papagian@users.noreply.github.com> Co-authored-by: gotjosh <josue@grafana.com> Co-authored-by: Marcus Efraimsson <marcus.efraimsson@gmail.com>
4 years ago
func (alertRule *AlertRule) DataToString() string {
response := "["
for i, part := range alertRule.Data {
response += string(part.Model)
if i < len(alertRule.Data)-1 {
response += ","
}
}
response += "]"
return response
}
// AlertRuleKey is the alert definition identifier
type AlertRuleKey struct {
OrgID int64
UID string
}
func (k AlertRuleKey) String() string {
return fmt.Sprintf("{orgID: %d, UID: %s}", k.OrgID, k.UID)
}
// GetKey returns the alert definitions identifier
func (alertRule *AlertRule) GetKey() AlertRuleKey {
return AlertRuleKey{OrgID: alertRule.OrgID, UID: alertRule.UID}
}
// PreSave sets default values and loads the updated model for each alert query.
func (alertRule *AlertRule) PreSave(timeNow func() time.Time) error {
for i, q := range alertRule.Data {
err := q.PreSave()
if err != nil {
return fmt.Errorf("invalid alert query %s: %w", q.RefID, err)
}
alertRule.Data[i] = q
}
alertRule.Updated = timeNow()
return nil
}
// AlertRuleVersion is the model for alert rule versions in unified alerting.
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
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
}
// GetAlertRuleByUIDQuery is the query for retrieving/deleting an alert rule by UID and organisation ID.
type GetAlertRuleByUIDQuery struct {
UID string
OrgID int64
Result *AlertRule
}
// ListAlertRulesQuery is the query for listing alert rules
type ListAlertRulesQuery struct {
OrgID int64
Result []*AlertRule
}
// ListNamespaceAlertRulesQuery is the query for listing namespace alert rules
type ListNamespaceAlertRulesQuery struct {
OrgID int64
// Namespace is the folder slug
NamespaceUID string
Result []*AlertRule
}
// ListRuleGroupAlertRulesQuery is the query for listing rule group alert rules
type ListRuleGroupAlertRulesQuery struct {
OrgID int64
// Namespace is the folder slug
NamespaceUID string
RuleGroup string
Result []*AlertRule
}
// ListOrgRuleGroupsQuery is the query for listing unique rule groups
type ListOrgRuleGroupsQuery struct {
OrgID int64
Result [][]string
}
// Condition contains backend expressions and queries and the RefID
// of the query or expression that will be evaluated.
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"`
OrgID int64 `json:"-"`
// Data is an array of data source queries and/or server side expressions.
Data []AlertQuery `json:"data"`
}
// IsValid checks the condition's validity.
func (c Condition) IsValid() bool {
// TODO search for refIDs in QueriesAndExpressions
return len(c.Data) != 0
}