Documentation
¶
Overview ¶
Package state is a generated GoMock package.
Index ¶
- Constants
- Variables
- func FormatStateAndReason(state eval.State, reason string) string
- func FromAlertsStateToStoppedAlert(firingStates []StateTransition, appURL *url.URL, clock clock.Clock, ...) apimodels.PostableAlerts
- func GetRuleExtraLabels(l log.Logger, rule *models.AlertRule, folderTitle string, includeFolder bool) map[string]string
- func NewEvaluationValues(m map[string]eval.NumberValueCapture) map[string]float64
- func ParseFormattedState(stateStr string) (eval.State, string, error)
- func StateToPostableAlert(transition StateTransition, appURL *url.URL, ...) *models.PostableAlert
- func StatesToRuleStatus(states []*State) ngModels.RuleStatus
- type AlertInstanceManager
- type AlertInstancesProvider
- type AsyncStatePersister
- type CountingImageService
- type Evaluation
- type FakeHistorian
- type FakeInstanceStore
- func (f *FakeInstanceStore) DeleteAlertInstances(ctx context.Context, q ...models.AlertInstanceKey) error
- func (f *FakeInstanceStore) DeleteAlertInstancesByRule(ctx context.Context, key models.AlertRuleKeyWithGroup) error
- func (f *FakeInstanceStore) FullSync(ctx context.Context, instances []models.AlertInstance, batchSize int) error
- func (f *FakeInstanceStore) ListAlertInstances(_ context.Context, q *models.ListAlertInstancesQuery) ([]*models.AlertInstance, error)
- func (f *FakeInstanceStore) RecordedOps() []any
- func (f *FakeInstanceStore) SaveAlertInstance(_ context.Context, q models.AlertInstance) error
- func (f *FakeInstanceStore) SaveAlertInstancesForRule(ctx context.Context, key models.AlertRuleKeyWithGroup, ...) error
- type FakeInstanceStoreOp
- type FakeRuleReader
- type Historian
- type ImageCapturer
- type InstanceReader
- type InstanceStore
- type InstanceWriter
- type Manager
- func (st *Manager) DeleteStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKeyWithGroup, reason string) []StateTransition
- func (st *Manager) ForgetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKeyWithGroup) []*State
- func (st *Manager) Get(orgID int64, alertRuleUID string, stateId data.Fingerprint) *State
- func (st *Manager) GetAll(orgID int64) []*State
- func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State
- func (st *Manager) GetStatusForRuleUID(orgID int64, alertRuleUID string) ngModels.RuleStatus
- func (st *Manager) ProcessEvalResults(ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, ...) StateTransitions
- func (st *Manager) Put(states []*State)
- func (st *Manager) ResetStateByRuleUID(ctx context.Context, rule *ngModels.AlertRule, reason string) []StateTransition
- func (st *Manager) Run(ctx context.Context) error
- func (st *Manager) Warm(ctx context.Context, orgReader OrgReader, rulesReader RuleReader, ...)
- type ManagerCfg
- type MockImageCapturer
- type MockImageCapturerMockRecorder
- type MultiInstanceReader
- type NoopImageService
- type NoopPersister
- type NotAvailableImageService
- type OrgReader
- type RuleReader
- type Sender
- type State
- func (a *State) Copy() *State
- func (a *State) Equals(b *State) bool
- func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error)
- func (a *State) GetLabels(opts ...models.LabelOption) map[string]string
- func (a *State) GetLastEvaluationValuesForCondition() map[string]float64
- func (a *State) GetRuleKey() models.AlertRuleKey
- func (a *State) IsStale() bool
- func (a *State) Maintain(interval int64, evaluatedAt time.Time)
- func (a *State) NeedsSending(now time.Time, resendDelay time.Duration, resolvedRetention time.Duration) bool
- func (a *State) SetAlerting(reason string, startsAt, endsAt time.Time)
- func (a *State) SetError(err error, startsAt, endsAt time.Time)
- func (a *State) SetNextValues(result eval.Result)
- func (a *State) SetNoData(reason string, startsAt, endsAt time.Time)
- func (a *State) SetNormal(reason string, startsAt, endsAt time.Time)
- func (a *State) SetPending(reason string, startsAt, endsAt time.Time)
- func (a *State) SetRecovering(reason string, startsAt, endsAt time.Time)
- func (a *State) ShouldBeResolved(oldState eval.State) bool
- type StatePersister
- type StateTransition
- type StateTransitions
- type SyncRuleStatePersister
- type SyncStatePersister
Constants ¶
const ( NoDataAlertName = "DatasourceNoData" ErrorAlertName = "DatasourceError" Rulename = "rulename" )
Variables ¶
var NoopSender = func(_ context.Context, _ StateTransitions) {}
NoopSender is a no-op sender. Used when you want state manager to update LastSentAt without sending any alerts.
var (
ResendDelay = 30 * time.Second
)
Functions ¶
func FromAlertsStateToStoppedAlert ¶
func FromAlertsStateToStoppedAlert(firingStates []StateTransition, appURL *url.URL, clock clock.Clock, featureToggles featuremgmt.FeatureToggles) apimodels.PostableAlerts
FromAlertsStateToStoppedAlert selects only transitions from firing states (states eval.Alerting, eval.NoData, eval.Error) and converts them to models.PostableAlert with EndsAt set to time.Now
func GetRuleExtraLabels ¶
func GetRuleExtraLabels(l log.Logger, rule *models.AlertRule, folderTitle string, includeFolder bool) map[string]string
GetRuleExtraLabels returns a map of built-in labels that should be added to an alert before it is sent to the Alertmanager or its state is cached.
func NewEvaluationValues ¶
func NewEvaluationValues(m map[string]eval.NumberValueCapture) map[string]float64
NewEvaluationValues returns the labels and values for each RefID in the capture.
func ParseFormattedState ¶
ParseFormattedState parses a state string in the format "state (reason)" and returns the state and reason separately.
func StateToPostableAlert ¶
func StateToPostableAlert(transition StateTransition, appURL *url.URL, featureToggles featuremgmt.FeatureToggles) *models.PostableAlert
StateToPostableAlert converts a state to a model that is accepted by Alertmanager. Annotations and Labels are copied from the state. - if state has at least one result, a new label '__value_string__' is added to the label set - the alert's GeneratorURL is constructed to point to the alert detail view - if evaluation state is either NoData or Error, the resulting set of labels is changed:
- original alert name (label: model.AlertNameLabel) is backed up to OriginalAlertName
- label model.AlertNameLabel is overwritten to either NoDataAlertName or ErrorAlertName
func StatesToRuleStatus ¶
func StatesToRuleStatus(states []*State) ngModels.RuleStatus
Types ¶
type AlertInstanceManager ¶
type AlertInstanceManager interface {
GetAll(orgID int64) []*State
GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State
}
AlertInstanceManager defines the interface for querying the current alert instances.
type AlertInstancesProvider ¶
type AlertInstancesProvider interface {
GetAlertInstances() []models.AlertInstance
}
type AsyncStatePersister ¶
type AsyncStatePersister struct {
// contains filtered or unexported fields
}
func (*AsyncStatePersister) Async ¶
func (a *AsyncStatePersister) Async(ctx context.Context, instancesProvider AlertInstancesProvider)
func (*AsyncStatePersister) Sync ¶
func (a *AsyncStatePersister) Sync(_ context.Context, _ trace.Span, _ models.AlertRuleKeyWithGroup, _ StateTransitions)
type CountingImageService ¶
type CountingImageService struct {
Called int
Image *models.Image
Err error
// contains filtered or unexported fields
}
func NewFailingCountingImageService ¶
func NewFailingCountingImageService(err error) *CountingImageService
type Evaluation ¶
type Evaluation struct {
EvaluationTime time.Time
EvaluationState eval.State
// Values contains the RefID and value of reduce and math expressions.
// Classic conditions can have different values for the same RefID as they can include multiple conditions.
// For these, we use the index of the condition in addition RefID as the key e.g. "A0, A1, A2, etc.".
Values map[string]float64
// Condition is the refID specified as the condition in the alerting rule at the time of the evaluation.
Condition string
}
type FakeHistorian ¶
type FakeHistorian struct {
StateTransitions []StateTransition
}
func (*FakeHistorian) Record ¶
func (f *FakeHistorian) Record(ctx context.Context, rule history_model.RuleMeta, states []StateTransition) <-chan error
type FakeInstanceStore ¶
type FakeInstanceStore struct {
// contains filtered or unexported fields
}
func (*FakeInstanceStore) DeleteAlertInstances ¶
func (f *FakeInstanceStore) DeleteAlertInstances(ctx context.Context, q ...models.AlertInstanceKey) error
func (*FakeInstanceStore) DeleteAlertInstancesByRule ¶
func (f *FakeInstanceStore) DeleteAlertInstancesByRule(ctx context.Context, key models.AlertRuleKeyWithGroup) error
func (*FakeInstanceStore) FullSync ¶
func (f *FakeInstanceStore) FullSync(ctx context.Context, instances []models.AlertInstance, batchSize int) error
func (*FakeInstanceStore) ListAlertInstances ¶
func (f *FakeInstanceStore) ListAlertInstances(_ context.Context, q *models.ListAlertInstancesQuery) ([]*models.AlertInstance, error)
func (*FakeInstanceStore) RecordedOps ¶
func (f *FakeInstanceStore) RecordedOps() []any
func (*FakeInstanceStore) SaveAlertInstance ¶
func (f *FakeInstanceStore) SaveAlertInstance(_ context.Context, q models.AlertInstance) error
func (*FakeInstanceStore) SaveAlertInstancesForRule ¶
func (f *FakeInstanceStore) SaveAlertInstancesForRule(ctx context.Context, key models.AlertRuleKeyWithGroup, instances []models.AlertInstance) error
type FakeInstanceStoreOp ¶
type FakeRuleReader ¶
type FakeRuleReader struct{}
func (*FakeRuleReader) ListAlertRules ¶
func (f *FakeRuleReader) ListAlertRules(_ context.Context, q *models.ListAlertRulesQuery) (models.RulesGroup, error)
type Historian ¶
type Historian interface {
// RecordStates writes a number of state transitions for a given rule to state history. It returns a channel that
// is closed when writing the state transitions has completed. If an error has occurred, the channel will contain a
// non-nil error.
Record(ctx context.Context, rule history_model.RuleMeta, states []StateTransition) <-chan error
}
Historian maintains an audit log of alert state history.
type ImageCapturer ¶
type ImageCapturer interface {
NewImage(ctx context.Context, r *models.AlertRule) (*models.Image, error)
}
ImageCapturer captures images.
type InstanceReader ¶
type InstanceReader interface {
ListAlertInstances(ctx context.Context, cmd *models.ListAlertInstancesQuery) ([]*models.AlertInstance, error)
}
InstanceReader provides methods to fetch alert instances.
type InstanceStore ¶
type InstanceStore interface {
InstanceReader
InstanceWriter
}
InstanceStore represents the ability to fetch and write alert instances.
type InstanceWriter ¶
type InstanceWriter interface {
SaveAlertInstance(ctx context.Context, instance models.AlertInstance) error
DeleteAlertInstances(ctx context.Context, keys ...models.AlertInstanceKey) error
// SaveAlertInstancesForRule overwrites the state for the given rule.
SaveAlertInstancesForRule(ctx context.Context, key models.AlertRuleKeyWithGroup, instances []models.AlertInstance) error
DeleteAlertInstancesByRule(ctx context.Context, key models.AlertRuleKeyWithGroup) error
FullSync(ctx context.Context, instances []models.AlertInstance, batchSize int) error
}
InstanceWriter provides methods to write alert instances.
type Manager ¶
type Manager struct {
ResendDelay time.Duration
ResolvedRetention time.Duration
// contains filtered or unexported fields
}
func NewManager ¶
func NewManager(cfg ManagerCfg, statePersister StatePersister) *Manager
func (*Manager) DeleteStateByRuleUID ¶
func (st *Manager) DeleteStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKeyWithGroup, reason string) []StateTransition
DeleteStateByRuleUID removes the rule instances from cache and instanceStore. A closed channel is returned to be able to gracefully handle the clear state step in scheduler in case we do not need to use the historian to save state history.
func (*Manager) ForgetStateByRuleUID ¶
func (*Manager) GetStatesForRuleUID ¶
func (*Manager) GetStatusForRuleUID ¶
func (st *Manager) GetStatusForRuleUID(orgID int64, alertRuleUID string) ngModels.RuleStatus
func (*Manager) ProcessEvalResults ¶
func (st *Manager) ProcessEvalResults( ctx context.Context, evaluatedAt time.Time, alertRule *ngModels.AlertRule, results eval.Results, extraLabels data.Labels, send Sender, ) StateTransitions
ProcessEvalResults updates the current states that belong to a rule with the evaluation results. if extraLabels is not empty, those labels will be added to every state. The extraLabels take precedence over rule labels and result labels This will update the states in cache/store and return the state transitions that need to be sent to the alertmanager.
func (*Manager) ResetStateByRuleUID ¶
func (st *Manager) ResetStateByRuleUID(ctx context.Context, rule *ngModels.AlertRule, reason string) []StateTransition
ResetStateByRuleUID removes the rule instances from cache and instanceStore and saves state history. If the state history has to be saved, rule must not be nil.
func (*Manager) Warm ¶
func (st *Manager) Warm(ctx context.Context, orgReader OrgReader, rulesReader RuleReader, instanceReader InstanceReader)
type ManagerCfg ¶
type ManagerCfg struct {
Metrics *metrics.State
ExternalURL *url.URL
InstanceStore InstanceStore
Images ImageCapturer
Clock clock.Clock
Historian Historian
// MaxStateSaveConcurrency controls the number of goroutines (per rule) that can save alert state in parallel.
MaxStateSaveConcurrency int
// StatePeriodicSaveBatchSize controls the size of the alert instance batch that is saved periodically when the
// alertingSaveStatePeriodic feature flag is enabled.
StatePeriodicSaveBatchSize int
RulesPerRuleGroupLimit int64
DisableExecution bool
// Duration for which a resolved alert state transition will continue to be sent to the Alertmanager.
ResolvedRetention time.Duration
Tracer tracing.Tracer
Log log.Logger
}
type MockImageCapturer ¶
type MockImageCapturer struct {
// contains filtered or unexported fields
}
MockImageCapturer is a mock of ImageCapturer interface.
func NewMockImageCapturer ¶
func NewMockImageCapturer(ctrl *gomock.Controller) *MockImageCapturer
NewMockImageCapturer creates a new mock instance.
func (*MockImageCapturer) EXPECT ¶
func (m *MockImageCapturer) EXPECT() *MockImageCapturerMockRecorder
EXPECT returns an object that allows the caller to indicate expected use.
type MockImageCapturerMockRecorder ¶
type MockImageCapturerMockRecorder struct {
// contains filtered or unexported fields
}
MockImageCapturerMockRecorder is the mock recorder for MockImageCapturer.
type MultiInstanceReader ¶
type MultiInstanceReader struct {
ProtoDBReader InstanceReader
DBReader InstanceReader
// contains filtered or unexported fields
}
MultiInstanceReader merges results from two InstanceReaders.
For each rule, it picks the state that has the newer LastEvalTime.
func NewMultiInstanceReader ¶
func NewMultiInstanceReader(logger log.Logger, r1, r2 InstanceReader) *MultiInstanceReader
func (*MultiInstanceReader) ListAlertInstances ¶
func (m *MultiInstanceReader) ListAlertInstances(ctx context.Context, cmd *models.ListAlertInstancesQuery) ([]*models.AlertInstance, error)
ListAlertInstances fetches alert instances for a query from both readers, groups them by rule UID, and returns the newest instances for each rule as a single slice.
type NoopPersister ¶
type NoopPersister struct{}
func (*NoopPersister) Async ¶
func (n *NoopPersister) Async(_ context.Context, _ AlertInstancesProvider)
func (*NoopPersister) Sync ¶
func (n *NoopPersister) Sync(_ context.Context, _ trace.Span, _ models.AlertRuleKeyWithGroup, _ StateTransitions)
type NotAvailableImageService ¶
type NotAvailableImageService struct{}
NotAvailableImageService is a service that returns ErrScreenshotsUnavailable.
type RuleReader ¶
type RuleReader interface {
ListAlertRules(ctx context.Context, query *models.ListAlertRulesQuery) (models.RulesGroup, error)
}
RuleReader represents the ability to fetch alert rules.
type Sender ¶
type Sender func(context.Context, StateTransitions)
Sender is an optional callback intended for sending the states to an alertmanager.
type State ¶
type State struct {
OrgID int64
AlertRuleUID string
// CacheID is a unique, opaque identifier for the state, and is used to find the state
// in the state cache. It tends to be derived from the state's labels.
CacheID data.Fingerprint
// State represents the current state.
State eval.State
// StateReason is a textual description to explain why the state has its current state.
StateReason string
// ResultFingerprint is a hash of labels of the result before it is processed by
ResultFingerprint data.Fingerprint
// LatestResult contains the result of the most recent evaluation, if available.
LatestResult *Evaluation
// Error is set if the current evaluation returned an error. If error is non-nil results
// can still contain the results of previous evaluations.
Error error
// Image contains an optional image for the state. It tends to be included in notifications
// as a visualization to show why the alert fired.
Image *models.Image
// Annotations contains the annotations from the alert rule. If an annotation is templated
// then the template is first evaluated to derive the final annotation.
Annotations map[string]string
// Labels contain the labels from the query and any custom labels from the alert rule.
// If a label is templated then the template is first evaluated to derive the final label.
Labels data.Labels
// Values contains the values of any instant vectors, reduce and math expressions, or classic
// conditions.
Values map[string]float64
// FiredAt is the time the state first transitions to Alerting.
FiredAt *time.Time
StartsAt time.Time
// EndsAt is different from the Prometheus EndsAt as EndsAt is updated for both Normal states
// and states that have been resolved. It cannot be used to determine when a state was resolved.
EndsAt time.Time
// ResolvedAt is set when the state is first resolved. That is to say, when the state first transitions
// from Alerting, NoData, Recovering, or Error to Normal. It is reset to zero when the state transitions from Normal
// to any other state.
ResolvedAt *time.Time
LastSentAt *time.Time
LastEvaluationString string
LastEvaluationTime time.Time
EvaluationDuration time.Duration
}
func (*State) GetAlertInstanceKey ¶
func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error)
func (*State) GetLastEvaluationValuesForCondition ¶
func (*State) GetRuleKey ¶
func (a *State) GetRuleKey() models.AlertRuleKey
func (*State) IsStale ¶
IsStale returns true if the state is stale, meaning that the state is ready to be evicted from the cache.
func (*State) NeedsSending ¶
func (a *State) NeedsSending(now time.Time, resendDelay time.Duration, resolvedRetention time.Duration) bool
NeedsSending returns true if the given state needs to be sent to the Alertmanager. Reasons for sending include: - The state has been resolved since the last notification. - The state is firing and the last notification was sent at least resendDelay ago. - The state was resolved within the resolvedRetention period, and the last notification was sent at least resendDelay ago.
func (*State) SetAlerting ¶
SetAlerting sets the state to Alerting. It changes both the start and end time.
func (*State) SetNextValues ¶
func (*State) SetNoData ¶
SetNoData sets the state to NoData. It changes both the start and end time.
func (*State) SetNormal ¶
SetNormal sets the state to Normal. It changes both the start and end time.
func (*State) SetPending ¶
SetPending sets the state to Pending. It changes both the start and end time.
func (*State) SetRecovering ¶
SetRecovering sets the state to Recovering. It changes both the start and end time.
type StatePersister ¶
type StatePersister interface {
Async(ctx context.Context, instancesProvider AlertInstancesProvider)
Sync(ctx context.Context, span trace.Span, ruleKey ngModels.AlertRuleKeyWithGroup, states StateTransitions)
}
func NewAsyncStatePersister ¶
func NewAsyncStatePersister(log log.Logger, ticker *clock.Ticker, cfg ManagerCfg) StatePersister
func NewNoopPersister ¶
func NewNoopPersister() StatePersister
func NewSyncRuleStatePersisiter ¶
func NewSyncRuleStatePersisiter(log log.Logger, cfg ManagerCfg) StatePersister
func NewSyncStatePersisiter ¶
func NewSyncStatePersisiter(log log.Logger, cfg ManagerCfg) StatePersister
type StateTransition ¶
StateTransition describes the transition from one state to another.
func (StateTransition) Changed ¶
func (c StateTransition) Changed() bool
func (StateTransition) Formatted ¶
func (c StateTransition) Formatted() string
func (StateTransition) PreviousFormatted ¶
func (c StateTransition) PreviousFormatted() string
type StateTransitions ¶
type StateTransitions []StateTransition
func (StateTransitions) StaleStates ¶
func (c StateTransitions) StaleStates() StateTransitions
StaleStates returns the subset of StateTransitions that are stale.
type SyncRuleStatePersister ¶
type SyncRuleStatePersister struct {
// contains filtered or unexported fields
}
func (*SyncRuleStatePersister) Async ¶
func (a *SyncRuleStatePersister) Async(_ context.Context, _ AlertInstancesProvider)
func (*SyncRuleStatePersister) Sync ¶
func (a *SyncRuleStatePersister) Sync(ctx context.Context, span trace.Span, ruleKey models.AlertRuleKeyWithGroup, states StateTransitions)
type SyncStatePersister ¶
type SyncStatePersister struct {
// contains filtered or unexported fields
}
func (*SyncStatePersister) Async ¶
func (a *SyncStatePersister) Async(_ context.Context, _ AlertInstancesProvider)
func (*SyncStatePersister) Sync ¶
func (a *SyncStatePersister) Sync(ctx context.Context, span trace.Span, _ ngModels.AlertRuleKeyWithGroup, allStates StateTransitions)
Sync persists the state transitions to the database. It deletes stale states and saves the current states.