alerting

package
v0.0.85-test Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: AGPL-3.0 Imports: 34 Imported by: 593

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 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 models.PluginRequestValidator
	DataService      legacydata.RequestHandler
	Cfg              *setting.Cfg
	// 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 models.PluginRequestValidator,
	dataService legacydata.RequestHandler, usageStatsService usagestats.Service, encryptionService encryption.Internal,
	notificationService *notifications.NotificationService, tracer tracing.Tracer, sqlStore AlertStore, cfg *setting.Cfg,
	dashAlertExtractor DashAlertExtractor) *AlertEngine

ProvideAlertEngine returns a new AlertEngine.

func (*AlertEngine) AlertTest

func (e *AlertEngine) AlertTest(orgID int64, dashboard *simplejson.Json, panelID int64, user *models.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            *sqlstore.SQLStore
	EncryptionService   encryption.Internal
	NotificationService *notifications.NotificationService
}

func ProvideService

func ProvideService(store *sqlstore.SQLStore, encryptionService encryption.Internal,
	notificationService *notifications.NotificationService) *AlertNotificationService

func (*AlertNotificationService) CreateAlertNotificationCommand

func (s *AlertNotificationService) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) 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) error

func (*AlertNotificationService) GetAlertNotificationsWithUid

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

func (*AlertNotificationService) GetAlertNotificationsWithUidToSend

func (s *AlertNotificationService) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error

func (*AlertNotificationService) GetAllAlertNotifications

func (s *AlertNotificationService) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error

func (*AlertNotificationService) GetOrCreateAlertNotificationState

func (s *AlertNotificationService) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) 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) error

type AlertStore

type AlertStore interface {
	GetAllAlertQueryHandler(context.Context, *models.GetAllAlertsQuery) error
	GetDataSource(context.Context, *models.GetDataSourceQuery) error
	GetDashboardUIDById(context.Context, *models.GetDashboardRefByIdQuery) error
	SetAlertNotificationStateToCompleteCommand(context.Context, *models.SetAlertNotificationStateToCompleteCommand) error
	SetAlertNotificationStateToPendingCommand(context.Context, *models.SetAlertNotificationStateToPendingCommand) error
	GetAlertNotificationUidWithId(context.Context, *models.GetAlertNotificationUidQuery) error
	GetAlertNotificationsWithUidToSend(context.Context, *models.GetAlertNotificationsWithUidToSendQuery) error
	GetOrCreateAlertNotificationState(context.Context, *models.GetOrCreateNotificationStateQuery) error
	SetAlertState(context.Context, *models.SetAlertStateCommand) error
}

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.

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
}

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, alertStore 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  *models.SignedInUser
	Dash  *models.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
	Logs           []*ResultLogEntry
	Error          error
	ConditionEvals string
	StartTime      time.Time
	EndTime        time.Time
	Rule           *Rule
	Log            log.Logger

	ImagePublicURL  string
	ImageOnDiskPath string
	NoDataFound     bool
	PrevAlertState  models.AlertStateType

	RequestValidator models.PluginRequestValidator

	Ctx context.Context

	Store AlertStore
	// contains filtered or unexported fields
}

EvalContext is the context object for an alert evaluation.

func NewEvalContext

func NewEvalContext(alertCtx context.Context, rule *Rule, requestValidator models.PluginRequestValidator, sqlStore AlertStore) *EvalContext

NewEvalContext is the EvalContext constructor.

func (*EvalContext) GetDashboardUID

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

GetDashboardUID returns the dashboard uid for the alert rule.

func (*EvalContext) GetDurationMs

func (c *EvalContext) GetDurationMs() float64

GetDurationMs returns the duration of the alert evaluation.

func (*EvalContext) GetNewState

func (c *EvalContext) GetNewState() models.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 *models.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       []*models.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 Ticker

type Ticker struct {
	C chan time.Time
	// contains filtered or unexported fields
}

Ticker is a ticker to power the alerting scheduler. it's like a time.Ticker, except:

  • it doesn't drop ticks for slow receivers, rather, it queues up. so that callers are in control to instrument what's going on.
  • it automatically ticks every second, which is the right thing in our current design
  • it ticks on intervalSec marks or very shortly after. this provides a predictable load pattern (this shouldn't cause too much load contention issues because the next steps in the pipeline just process at their own pace)
  • the timestamps are used to mark "last datapoint to query for" and as such, are a configurable amount of seconds in the past
  • because we want to allow:
  • a clean "resume where we left off" and "don't yield ticks we already did"
  • adjusting offset over time to compensate for storage backing up or getting fast and providing lower latency you specify a lastProcessed timestamp as well as an offset at creation, or runtime

func NewTicker

func NewTicker(last time.Time, initialOffset time.Duration, c clock.Clock, intervalSec int64) *Ticker

NewTicker returns a ticker that ticks on intervalSec marks or very shortly after, and never drops ticks

func (*Ticker) Pause

func (t *Ticker) Pause()

Pause unpauses the ticker and no ticks will be sent.

func (*Ticker) ResetOffset

func (t *Ticker) ResetOffset(duration time.Duration)

ResetOffset resets the offset.

func (*Ticker) Unpause

func (t *Ticker) Unpause()

Unpause unpauses the ticker and ticks will be sent.

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