state

package
v0.0.0-...-56fe054 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: AGPL-3.0 Imports: 38 Imported by: 0

Documentation

Overview

Package state is a generated GoMock package.

Index

Constants

View Source
const (
	NoDataAlertName = "DatasourceNoData"
	ErrorAlertName  = "DatasourceError"

	Rulename = "rulename"
)

Variables

View Source
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.

View Source
var (
	ResendDelay = 30 * time.Second
)

Functions

func FormatStateAndReason

func FormatStateAndReason(state eval.State, reason string) string

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

func ParseFormattedState(stateStr string) (eval.State, string, error)

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

type CountingImageService

type CountingImageService struct {
	Called int
	Image  *models.Image
	Err    error
	// contains filtered or unexported fields
}

func NewFailingCountingImageService

func NewFailingCountingImageService(err error) *CountingImageService

func (*CountingImageService) NewImage

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 (*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 FakeInstanceStoreOp struct {
	Name string
	Args []any
}

type FakeRuleReader

type FakeRuleReader struct{}

func (*FakeRuleReader) ListAlertRules

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 (st *Manager) ForgetStateByRuleUID(ctx context.Context, ruleKey ngModels.AlertRuleKeyWithGroup) []*State

func (*Manager) Get

func (st *Manager) Get(orgID int64, alertRuleUID string, stateId data.Fingerprint) *State

func (*Manager) GetAll

func (st *Manager) GetAll(orgID int64) []*State

func (*Manager) GetStatesForRuleUID

func (st *Manager) GetStatesForRuleUID(orgID int64, alertRuleUID string) []*State

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) Put

func (st *Manager) Put(states []*State)

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) Run

func (st *Manager) Run(ctx context.Context) error

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

EXPECT returns an object that allows the caller to indicate expected use.

func (*MockImageCapturer) NewImage

func (m *MockImageCapturer) NewImage(arg0 context.Context, arg1 *models.AlertRule) (*models.Image, error)

NewImage mocks base method.

type MockImageCapturerMockRecorder

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

MockImageCapturerMockRecorder is the mock recorder for MockImageCapturer.

func (*MockImageCapturerMockRecorder) NewImage

func (mr *MockImageCapturerMockRecorder) NewImage(arg0, arg1 any) *gomock.Call

NewImage indicates an expected call of NewImage.

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

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 NoopImageService

type NoopImageService struct{}

NoopImageService is a no-op image service.

func (*NoopImageService) NewImage

type NoopPersister

type NoopPersister struct{}

func (*NoopPersister) Async

func (*NoopPersister) Sync

type NotAvailableImageService

type NotAvailableImageService struct{}

NotAvailableImageService is a service that returns ErrScreenshotsUnavailable.

func (*NotAvailableImageService) NewImage

type OrgReader

type OrgReader interface {
	FetchOrgIds(ctx context.Context) ([]int64, error)
}

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) Copy

func (a *State) Copy() *State

Copy creates a shallow copy of the State except for labels and annotations.

func (*State) Equals

func (a *State) Equals(b *State) bool

func (*State) GetAlertInstanceKey

func (a *State) GetAlertInstanceKey() (models.AlertInstanceKey, error)

func (*State) GetLabels

func (a *State) GetLabels(opts ...models.LabelOption) map[string]string

func (*State) GetLastEvaluationValuesForCondition

func (a *State) GetLastEvaluationValuesForCondition() map[string]float64

func (*State) GetRuleKey

func (a *State) GetRuleKey() models.AlertRuleKey

func (*State) IsStale

func (a *State) IsStale() bool

IsStale returns true if the state is stale, meaning that the state is ready to be evicted from the cache.

func (*State) Maintain

func (a *State) Maintain(interval int64, evaluatedAt time.Time)

Maintain updates the end time using the most recent evaluation.

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

func (a *State) SetAlerting(reason string, startsAt, endsAt time.Time)

SetAlerting sets the state to Alerting. It changes both the start and end time.

func (*State) SetError

func (a *State) SetError(err error, startsAt, endsAt time.Time)

SetError sets the state to Error. It changes both the start and end time.

func (*State) SetNextValues

func (a *State) SetNextValues(result eval.Result)

func (*State) SetNoData

func (a *State) SetNoData(reason string, startsAt, endsAt time.Time)

SetNoData sets the state to NoData. It changes both the start and end time.

func (*State) SetNormal

func (a *State) SetNormal(reason string, startsAt, endsAt time.Time)

SetNormal sets the state to Normal. It changes both the start and end time.

func (*State) SetPending

func (a *State) SetPending(reason string, startsAt, endsAt time.Time)

SetPending sets the state to Pending. It changes both the start and end time.

func (*State) SetRecovering

func (a *State) SetRecovering(reason string, startsAt, endsAt time.Time)

SetRecovering sets the state to Recovering. It changes both the start and end time.

func (*State) ShouldBeResolved

func (a *State) ShouldBeResolved(oldState eval.State) bool

If the state is Normal, and the previous state was Alerting, Error, NoData, or Recovering, we can consider the state to be resolved. This is used to determine if we should send a resolved notification.

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

type StateTransition struct {
	*State
	PreviousState       eval.State
	PreviousStateReason string
}

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 (*SyncRuleStatePersister) Sync

type SyncStatePersister

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

func (*SyncStatePersister) Async

func (*SyncStatePersister) Sync

Sync persists the state transitions to the database. It deletes stale states and saves the current states.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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