alerting

package
v0.0.0-kmdagger1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: AGPL-3.0 Imports: 47 Imported by: 588

Documentation

Index

Constants

View Source
const (
	// InputTypeText will render a text field in the frontend
	InputTypeText = "text"
	// InputTypePassword will render a password field in the frontend
	InputTypePassword = "password"
)
View Source
const (
	// ElementTypeInput will render an input
	ElementTypeInput = "input"
	// ElementTypeSelect will render a select
	ElementTypeSelect = "select"
	// ElementTypeCheckbox will render a checkbox
	ElementTypeCheckbox = "checkbox"
	// ElementTypeTextArea will render a textarea
	ElementTypeTextArea = "textarea"
)

Variables

View Source
var (
	// ErrFrequencyCannotBeZeroOrLess frequency cannot be below zero
	ErrFrequencyCannotBeZeroOrLess = errors.New(`"evaluate every" cannot be zero or below`)

	// ErrFrequencyCouldNotBeParsed frequency cannot be parsed
	ErrFrequencyCouldNotBeParsed = errors.New(`"evaluate every" field could not be parsed`)

	// ErrWrongUnitFormat wrong unit format
	ErrWrongUnitFormat = fmt.Errorf(`time unit not supported. supported units: %s`, reflect.ValueOf(unitMultiplier).MapKeys())
)

Functions

func GetAlertsByDashboardId2

func GetAlertsByDashboardId2(dashboardId int64, sess *db.Session) ([]*alertmodels.Alert, error)

func RegisterCondition

func RegisterCondition(typeName string, factory ConditionFactory)

RegisterCondition adds support for alerting conditions.

func RegisterNotifier

func RegisterNotifier(plugin *NotifierPlugin)

RegisterNotifier registers a notifier.

func UAEnabled

func UAEnabled(ctx context.Context) bool

func WithUAEnabled

func WithUAEnabled(ctx context.Context, enabled bool) context.Context

Types

type AlertEngine

type AlertEngine struct {
	RenderService    rendering.Service
	RequestValidator validations.PluginRequestValidator
	DataService      legacydata.RequestHandler
	Cfg              *setting.Cfg

	AlertStore AlertStore
	// contains filtered or unexported fields
}

AlertEngine is the background process that schedules alert evaluations and makes sure notifications are sent.

func ProvideAlertEngine

func ProvideAlertEngine(renderer rendering.Service, requestValidator validations.PluginRequestValidator,
	dataService legacydata.RequestHandler, usageStatsService usagestats.Service, validator validator.Service, encryptionService encryption.Internal,
	notificationService *notifications.NotificationService, tracer tracing.Tracer, store AlertStore, cfg *setting.Cfg,
	dashAlertExtractor DashAlertExtractor, dashboardService dashboards.DashboardService, cacheService *localcache.CacheService, dsService datasources.DataSourceService, annotationsRepo annotations.Repository) *AlertEngine

ProvideAlertEngine returns a new AlertEngine.

func (*AlertEngine) AlertTest

func (e *AlertEngine) AlertTest(orgID int64, dashboard *simplejson.Json, panelID int64, user *user.SignedInUser) (*EvalContext, error)

AlertTest makes a test alert.

func (*AlertEngine) IsDisabled

func (e *AlertEngine) IsDisabled() bool

IsDisabled returns true if the alerting service is disabled for this instance.

func (*AlertEngine) QueryUsageStats

func (e *AlertEngine) QueryUsageStats(ctx context.Context) (*UsageStats, error)

QueryUsageStats returns usage stats about alert rules configured in Grafana.

func (*AlertEngine) Run

func (e *AlertEngine) Run(ctx context.Context) error

Run starts the alerting service background process.

type AlertNotificationService

type AlertNotificationService struct {
	SQLStore            AlertNotificationStore
	EncryptionService   encryption.Internal
	NotificationService *notifications.NotificationService
}

func ProvideService

func ProvideService(store db.DB, encryptionService encryption.Internal,
	notificationService *notifications.NotificationService) *AlertNotificationService

func (*AlertNotificationService) CreateAlertNotificationCommand

func (s *AlertNotificationService) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (res *models.AlertNotification, err error)

func (*AlertNotificationService) DeleteAlertNotification

func (*AlertNotificationService) DeleteAlertNotificationWithUid

func (s *AlertNotificationService) DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error

func (*AlertNotificationService) GetAlertNotifications

func (s *AlertNotificationService) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (res *models.AlertNotification, err error)

func (*AlertNotificationService) GetAlertNotificationsWithUid

func (s *AlertNotificationService) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (res *models.AlertNotification, err error)

func (*AlertNotificationService) GetAlertNotificationsWithUidToSend

func (s *AlertNotificationService) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) (res []*models.AlertNotification, err error)

func (*AlertNotificationService) GetAllAlertNotifications

func (s *AlertNotificationService) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) (res []*models.AlertNotification, err error)

func (*AlertNotificationService) GetOrCreateAlertNotificationState

func (s *AlertNotificationService) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (res *models.AlertNotificationState, err error)

func (*AlertNotificationService) HandleNotificationTestCommand

func (s *AlertNotificationService) HandleNotificationTestCommand(ctx context.Context, cmd *NotificationTestCommand) error

func (*AlertNotificationService) SetAlertNotificationStateToCompleteCommand

func (s *AlertNotificationService) SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error

func (*AlertNotificationService) SetAlertNotificationStateToPendingCommand

func (s *AlertNotificationService) SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error

func (*AlertNotificationService) UpdateAlertNotification

func (*AlertNotificationService) UpdateAlertNotificationWithUid

func (s *AlertNotificationService) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (res *models.AlertNotification, err error)

type AlertNotificationStore

type AlertNotificationStore interface {
	DeleteAlertNotification(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error
	DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error
	GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (*models.AlertNotification, error)
	GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) (string, error)
	GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (*models.AlertNotification, error)
	GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) ([]*models.AlertNotification, error)
	GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) ([]*models.AlertNotification, error)
	CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (*models.AlertNotification, error)
	UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (*models.AlertNotification, error)
	UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (*models.AlertNotification, error)
	SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error
	SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error
	GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (*models.AlertNotificationState, error)
}

type AlertStore

AlertStore is a subset of SQLStore API to satisfy the needs of the alerting service. A subset is needed to make it easier to mock during the tests.

func ProvideAlertStore

func ProvideAlertStore(
	db db.DB,
	cacheService *localcache.CacheService, cfg *setting.Cfg, tagService tag.Service, features featuremgmt.FeatureToggles) AlertStore

type Condition

type Condition interface {
	Eval(result *EvalContext, requestHandler legacydata.RequestHandler) (*ConditionResult, error)
}

Condition is responsible for evaluating an alert condition.

type ConditionFactory

type ConditionFactory func(model *simplejson.Json, index int) (Condition, error)

ConditionFactory is the function signature for creating `Conditions`.

type ConditionResult

type ConditionResult struct {
	Firing      bool
	NoDataFound bool
	Operator    string
	EvalMatches []*EvalMatch
	AllMatches  []*EvalMatch
}

ConditionResult is the result of a condition evaluation.

type DashAlertExtractor

type DashAlertExtractor interface {
	GetAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) ([]*models.Alert, error)
	ValidateAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) error
}

type DashAlertExtractorService

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

DashAlertExtractorService extracts alerts from the dashboard json.

func ProvideDashAlertExtractorService

func ProvideDashAlertExtractorService(datasourcePermissionsService permissions.DatasourcePermissionsService, datasourceService datasources.DataSourceService, store AlertStore) *DashAlertExtractorService

func (*DashAlertExtractorService) GetAlerts

func (e *DashAlertExtractorService) GetAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) ([]*models.Alert, error)

GetAlerts extracts alerts from the dashboard json and does full validation on the alert json data.

func (*DashAlertExtractorService) ValidateAlerts

func (e *DashAlertExtractorService) ValidateAlerts(ctx context.Context, dashAlertInfo DashAlertInfo) error

ValidateAlerts validates alerts in the dashboard json but does not require a valid dashboard id in the first validation pass.

type DashAlertInfo

type DashAlertInfo struct {
	User  *user.SignedInUser
	Dash  *dashboards.Dashboard
	OrgID int64
}

type DatasourceAlertUsage

type DatasourceAlertUsage map[string]int

DatasourceAlertUsage is a hash where the key represents the Datasource type and the value represents how many alerts that use the datasources.

type DefaultEvalHandler

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

DefaultEvalHandler is responsible for evaluating the alert rule.

func NewEvalHandler

func NewEvalHandler(requestHandler legacydata.RequestHandler) *DefaultEvalHandler

NewEvalHandler is the `DefaultEvalHandler` constructor.

func (*DefaultEvalHandler) Eval

func (e *DefaultEvalHandler) Eval(context *EvalContext)

Eval evaluated the alert rule.

type ElementType

type ElementType string

ElementType is the type of element that can be rendered in the frontend.

type EvalContext

type EvalContext struct {
	Firing         bool
	IsTestRun      bool
	IsDebug        bool
	EvalMatches    []*EvalMatch
	AllMatches     []*EvalMatch
	Logs           []*ResultLogEntry
	Error          error
	ConditionEvals string
	StartTime      time.Time
	EndTime        time.Time
	Rule           *Rule
	Log            log.Logger

	ImagePublicURL  string
	ImageOnDiskPath string
	NoDataFound     bool
	PrevAlertState  alertmodels.AlertStateType

	RequestValidator validations.PluginRequestValidator

	Ctx context.Context

	Store AlertStore

	DatasourceService datasources.DataSourceService
	// contains filtered or unexported fields
}

EvalContext is the context object for an alert evaluation.

func NewEvalContext

func NewEvalContext(alertCtx context.Context, rule *Rule, requestValidator validations.PluginRequestValidator,
	alertStore AlertStore, dashboardService dashboards.DashboardService, dsService datasources.DataSourceService, annotationRepo annotations.Repository) *EvalContext

NewEvalContext is the EvalContext constructor.

func (*EvalContext) GetDashboardUID

func (c *EvalContext) GetDashboardUID() (*dashboards.DashboardRef, error)

GetDashboardUID returns the dashboard uid for the alert rule.

func (*EvalContext) GetDataSource

func (*EvalContext) GetDurationMs

func (c *EvalContext) GetDurationMs() float64

GetDurationMs returns the duration of the alert evaluation.

func (*EvalContext) GetNewState

func (c *EvalContext) GetNewState() alertmodels.AlertStateType

GetNewState returns the new state from the alert rule evaluation.

func (*EvalContext) GetNotificationTitle

func (c *EvalContext) GetNotificationTitle() string

GetNotificationTitle returns the title of the alert rule including alert state.

func (*EvalContext) GetRuleURL

func (c *EvalContext) GetRuleURL() (string, error)

GetRuleURL returns the url to the dashboard containing the alert.

func (*EvalContext) GetStateModel

func (c *EvalContext) GetStateModel() *StateDescription

GetStateModel returns the `StateDescription` based on current state.

type EvalMatch

type EvalMatch struct {
	Value  null.Float        `json:"value"`
	Metric string            `json:"metric"`
	Tags   map[string]string `json:"tags"`
}

EvalMatch represents the series violating the threshold.

type GetDecryptedValueFn

type GetDecryptedValueFn func(ctx context.Context, sjd map[string][]byte, key string, fallback string, secret string) string

GetDecryptedValueFn is a function that returns the decrypted value of the given key. If the key is not present, then it returns the fallback value.

type InputType

type InputType string

InputType is the type of input that can be rendered in the frontend.

type Job

type Job struct {
	Offset     int64
	OffsetWait bool
	Delay      bool

	Rule *Rule
	// contains filtered or unexported fields
}

Job holds state about when the alert rule should be evaluated.

func (*Job) GetRunning

func (j *Job) GetRunning() bool

GetRunning returns true if the job is running. A lock is taken and released on the Job to ensure atomicity.

func (*Job) SetRunning

func (j *Job) SetRunning(b bool)

SetRunning sets the running property on the Job. A lock is taken and released on the Job to ensure atomicity.

type NotificationTestCommand

type NotificationTestCommand struct {
	OrgID          int64
	ID             int64
	State          models.AlertStateType
	Name           string
	Type           string
	Settings       *simplejson.Json
	SecureSettings map[string]string
}

NotificationTestCommand initiates an test execution of an alert notification.

type Notifier

type Notifier interface {
	Notify(evalContext *EvalContext) error
	GetType() string
	NeedsImage() bool

	// ShouldNotify checks this evaluation should send an alert notification
	ShouldNotify(ctx context.Context, evalContext *EvalContext, notificationState *models.AlertNotificationState) bool

	GetNotifierUID() string
	GetIsDefault() bool
	GetSendReminder() bool
	GetDisableResolveMessage() bool
	GetFrequency() time.Duration
}

Notifier is responsible for sending alert notifications.

func InitNotifier

func InitNotifier(model *alertmodels.AlertNotification, fn GetDecryptedValueFn, notificationService *notifications.NotificationService) (Notifier, error)

InitNotifier instantiate a new notifier based on the model.

type NotifierFactory

NotifierFactory is a signature for creating notifiers.

type NotifierOption

type NotifierOption struct {
	Element        ElementType    `json:"element"`
	InputType      InputType      `json:"inputType"`
	Label          string         `json:"label"`
	Description    string         `json:"description"`
	Placeholder    string         `json:"placeholder"`
	PropertyName   string         `json:"propertyName"`
	SelectOptions  []SelectOption `json:"selectOptions"`
	ShowWhen       ShowWhen       `json:"showWhen"`
	Required       bool           `json:"required"`
	ValidationRule string         `json:"validationRule"`
	Secure         bool           `json:"secure"`
	DependsOn      string         `json:"dependsOn"`
}

NotifierOption holds information about options specific for the NotifierPlugin.

type NotifierPlugin

type NotifierPlugin struct {
	Type        string           `json:"type"`
	Name        string           `json:"name"`
	Heading     string           `json:"heading"`
	Description string           `json:"description"`
	Info        string           `json:"info"`
	Factory     NotifierFactory  `json:"-"`
	Options     []NotifierOption `json:"options"`
}

NotifierPlugin holds meta information about a notifier.

func GetNotifiers

func GetNotifiers() []*NotifierPlugin

GetNotifiers returns a list of metadata about available notifiers.

type ResultLogEntry

type ResultLogEntry struct {
	Message string
	Data    interface{}
}

ResultLogEntry represents log data for the alert evaluation.

type Rule

type Rule struct {
	ID                  int64
	OrgID               int64
	DashboardID         int64
	PanelID             int64
	Frequency           int64
	Name                string
	Message             string
	LastStateChange     time.Time
	For                 time.Duration
	NoDataState         models.NoDataOption
	ExecutionErrorState models.ExecutionErrorOption
	State               models.AlertStateType
	Conditions          []Condition
	Notifications       []string
	AlertRuleTags       []*tag.Tag

	StateChanges int64
}

Rule is the in-memory version of an alert rule.

func NewRuleFromDBAlert

func NewRuleFromDBAlert(ctx context.Context, store AlertStore, ruleDef *models.Alert, logTranslationFailures bool) (*Rule, error)

NewRuleFromDBAlert maps a db version of alert to an in-memory version.

type SelectOption

type SelectOption struct {
	Value string `json:"value"`
	Label string `json:"label"`
}

SelectOption is a simple type for Options that have dropdown options. Should be used when Element is ElementTypeSelect.

type ShowWhen

type ShowWhen struct {
	Field string `json:"field"`
	Is    string `json:"is"`
}

ShowWhen holds information about when options are dependant on other options.

type StateDescription

type StateDescription struct {
	Color string
	Text  string
	Data  string
}

StateDescription contains visual information about the alert state.

type UsageStats

type UsageStats struct {
	DatasourceUsage DatasourceAlertUsage
}

UsageStats contains stats about alert rules configured in Grafana.

type UsageStatsQuerier

type UsageStatsQuerier interface {
	QueryUsageStats(context.Context) (*UsageStats, error)
}

UsageStatsQuerier returns usage stats about alert rules configured in Grafana.

type ValidationError

type ValidationError struct {
	Reason      string
	Err         error
	AlertID     int64
	DashboardID int64
	PanelID     int64
}

ValidationError is a typed error with meta data about the validation error.

func (ValidationError) Error

func (e ValidationError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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