definition

package
v0.0.0-...-a8ee250 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: AGPL-3.0 Imports: 18 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoMatchers              = errors.New("matchers must not be empty")
	ErrInvalidMatchers         = errors.New("only equality matchers are allowed")
	ErrDuplicateMatchers       = errors.New("matchers should be unique")
	ErrSubtreeMatchersConflict = errors.New("subtree matchers conflict with existing Grafana routes, merging will break existing notifications")
)

Functions

func AllReceivers

func AllReceivers(route *config.Route) (res []string)

AllReceivers will recursively walk a routing tree and return a list of all the referenced receiver names.

func GrafanaToUpstreamConfig

func GrafanaToUpstreamConfig(cfg *PostableApiAlertingConfig) config.Config

GrafanaToUpstreamConfig converts a Grafana alerting configuration into an upstream Alertmanager configuration. It ignores the configuration for Grafana receivers, adding only their names.

func MarshalJSONWithSecrets

func MarshalJSONWithSecrets(v any) ([]byte, error)

MarshalJSONWithSecrets marshals the given value to JSON with secrets in plain text.

alertmanager's and prometheus' Secret and SecretURL types mask their values when marshaled with the standard JSON or YAML marshallers. This function preserves the values of these types by using a custom JSON encoder.

func ValidateAlertmanagerConfig

func ValidateAlertmanagerConfig(cfg any) error

ValidateAlertmanagerConfig recursively scans the input config looking for data types for which we have a specific validation and, whenever encountered, it runs their validation. Returns the first error or nil if validation succeeds.

Types

type Config

type Config struct {
	Global       *config.GlobalConfig `yaml:"global,omitempty" json:"global,omitempty"`
	Route        *Route               `yaml:"route,omitempty" json:"route,omitempty"`
	InhibitRules []config.InhibitRule `yaml:"inhibit_rules,omitempty" json:"inhibit_rules,omitempty"`
	// MuteTimeIntervals is deprecated and will be removed before Alertmanager 1.0.
	MuteTimeIntervals []config.MuteTimeInterval `yaml:"mute_time_intervals,omitempty" json:"mute_time_intervals,omitempty"`
	TimeIntervals     []config.TimeInterval     `yaml:"time_intervals,omitempty" json:"time_intervals,omitempty"`
	Templates         []string                  `yaml:"templates,omitempty" json:"templates,omitempty"`
}

Config is the top-level configuration for Alertmanager's config files.

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(b []byte) error

Config is the entrypoint for the embedded Alertmanager config with the exception of receivers. Prometheus historically uses yaml files as the method of configuration and thus some post-validation is included in the UnmarshalYAML method. Here we simply run this with a noop unmarshaling function in order to benefit from said validation.

func (*Config) UnmarshalYAML

func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error

type MergeOpts

type MergeOpts struct {
	// DedupSuffix is a string suffix that will be appended to any resources (receivers or time intervals)
	// from the secondary configuration that have name conflicts with the primary configuration.
	//
	// The deduplication process works as follows:
	// 1. If a resource from the secondary config has the same name as one in the primary config,
	//    this suffix is appended to create a new name (e.g., "webhook" becomes "webhooksuffix")
	// 2. If the new name still conflicts, a sequential number is added (e.g., "webhooksuffix_01")
	// 3. All references to renamed resources are automatically updated throughout the configuration
	//
	// When left empty, only numeric suffixes will be used for deduplication (e.g., "webhook_01").
	//
	// Example usage:
	//   MergeOpts{
	//     DedupSuffix: "_secondary",  // Results in names like "webhook_secondary" or "webhook_secondary_01"
	//   }
	//
	// This field helps maintain distinct resource identities while preserving relationships
	// between components during the merge process.
	DedupSuffix string
	// SubtreeMatchers specifies a list of matchers that will be applied to the root route
	// of the routing tree being merged. These matchers are essential for properly isolating
	// and identifying alerts from the secondary configuration after merging.
	//
	// The matchers must follow these requirements:
	// - At least one matcher must be provided (cannot be empty)
	// - Each matcher must use the equality operator (labels.MatchEqual type)
	// - Each matcher name must be unique within the list
	//
	// Example usage:
	//   SubtreeMatchers: config.Matchers{
	//     {Name: "source", Value: "external", Type: labels.MatchEqual},
	//     {Name: "environment", Value: "production", Type: labels.MatchEqual},
	//   }
	//
	// These matchers will be:
	// 1. Added to the root of the secondary routing tree during merge
	// 2. Added to both source and target matchers of all inhibit rules from the secondary config
	// 3. Used to ensure alerts are properly routed after configurations are merged
	//
	// Warning: If these matchers conflict with existing routes in the primary configuration,
	// the merge operation will fail with ErrSubtreeMatchersConflict to prevent breaking
	// existing notification flows.
	SubtreeMatchers config.Matchers
}

func (MergeOpts) Validate

func (o MergeOpts) Validate() error

type MergeResult

type MergeResult struct {
	Config               PostableApiAlertingConfig
	RenamedReceivers     map[string]string
	RenamedTimeIntervals map[string]string
}

MergeResult represents the result of merging two Alertmanager configurations. It contains the unified configuration and maps of renamed receivers and time intervals.

func Merge

Merge combines two Alertmanager configurations into a single unified configuration.

The function handles three main aspects of the merge process:

  1. Resource Deduplication: When resources (receivers or time intervals) with identical names exist in both configurations, resources from configuration "b" are renamed according to these rules: - First, the MergeOpts.DedupSuffix is appended to the name - If the name is still not unique, a numbered suffix is added (e.g., "_01", "_02") - All references to renamed resources are automatically updated throughout the configuration

2. Route Merging:

  • The entire routing tree from "b" is inserted as a sub-tree under the root route of "a"
  • The sub-tree is positioned as the first route in the list of routes
  • The MergeOpts.SubtreeMatchers are added to the root of the "b" routing tree
  • Default timing settings (GroupWait, GroupInterval, RepeatInterval) are explicitly set on the "b" route to prevent inheriting potentially unwanted defaults from the parent configuration
  • If any existing routes in "a" would match the SubtreeMatchers, the merge will fail with ErrSubtreeMatchersConflict to prevent breaking existing routing behavior

3. Inhibit Rule Merging:

  • All inhibit rules from "b" are copied to the result
  • MergeOpts.SubtreeMatchers are added to both source and target matchers of each copied inhibit rule to maintain proper context separation

Returns a MergeResult containing the merged configuration and maps of renamed resources that can be used to track the renaming that occurred during the merge process.

Example usage:

result, err := Merge(primaryConfig, secondaryConfig, MergeOpts{
  DedupSuffix: "_secondary",
  SubtreeMatchers: config.Matchers{
    {Name: "source", Value: "external", Type: labels.MatchEqual},
  },
})

If the merge fails with ErrSubtreeMatchersConflict, it indicates that the SubtreeMatchers would conflict with existing routes, potentially disrupting alert notifications. In this case, you should choose different SubtreeMatchers that don't overlap with existing route matchers.

type ObjectMatcherAPIModel

type ObjectMatcherAPIModel [3]string

ObjectMatcher is a matcher that can be used to filter alerts. swagger:model ObjectMatcher

type ObjectMatchers

type ObjectMatchers labels.Matchers

swagger:ignore ObjectMatchers is Matchers with a different Unmarshal and Marshal methods that accept matchers as objects that have already been parsed.

func (ObjectMatchers) MarshalJSON

func (m ObjectMatchers) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Matchers.

func (ObjectMatchers) MarshalYAML

func (m ObjectMatchers) MarshalYAML() (interface{}, error)

MarshalYAML implements the yaml.Marshaler interface for Matchers.

func (*ObjectMatchers) UnmarshalJSON

func (m *ObjectMatchers) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Matchers.

func (*ObjectMatchers) UnmarshalYAML

func (m *ObjectMatchers) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Matchers.

type ObjectMatchersAPIModel

type ObjectMatchersAPIModel []ObjectMatcherAPIModel

ObjectMatchers is a list of matchers that can be used to filter alerts. swagger:model ObjectMatchers

type PostableApiAlertingConfig

type PostableApiAlertingConfig struct {
	Config `yaml:",inline"`

	// Override with our superset receiver type
	Receivers []*PostableApiReceiver `yaml:"receivers,omitempty" json:"receivers,omitempty"`
}

nolint:revive

func Load

func Load(rawCfg []byte) (*PostableApiAlertingConfig, error)

Load parses a slice of bytes (json/yaml) into a configuration and validates it.

func LoadCompat

func LoadCompat(rawCfg []byte) (*PostableApiAlertingConfig, error)

LoadCompat loads a PostableApiAlertingConfig from a YAML configuration and runs validations to ensure that it works with the Mimir Alertmanager.

func (*PostableApiAlertingConfig) GetMuteTimeIntervals

func (c *PostableApiAlertingConfig) GetMuteTimeIntervals() []config.MuteTimeInterval

func (*PostableApiAlertingConfig) GetReceivers

func (c *PostableApiAlertingConfig) GetReceivers() []*PostableApiReceiver

func (*PostableApiAlertingConfig) GetRoute

func (c *PostableApiAlertingConfig) GetRoute() *Route

func (*PostableApiAlertingConfig) GetTimeIntervals

func (c *PostableApiAlertingConfig) GetTimeIntervals() []config.TimeInterval

func (*PostableApiAlertingConfig) ReceiverType

func (c *PostableApiAlertingConfig) ReceiverType() ReceiverType

Type requires validate has been called and just checks the first receiver type

func (*PostableApiAlertingConfig) UnmarshalJSON

func (c *PostableApiAlertingConfig) UnmarshalJSON(b []byte) error

func (*PostableApiAlertingConfig) UnmarshalYAML

func (c *PostableApiAlertingConfig) UnmarshalYAML(unmarshal func(interface{}) error) error

func (*PostableApiAlertingConfig) Validate

func (c *PostableApiAlertingConfig) Validate() error

Validate ensures that the two routing trees use the correct receiver types.

type PostableApiReceiver

type PostableApiReceiver struct {
	config.Receiver          `yaml:",inline"`
	PostableGrafanaReceivers `yaml:",inline"`
}

nolint:revive

func (*PostableApiReceiver) GetName

func (r *PostableApiReceiver) GetName() string

func (*PostableApiReceiver) Type

func (*PostableApiReceiver) UnmarshalJSON

func (r *PostableApiReceiver) UnmarshalJSON(b []byte) error

func (*PostableApiReceiver) UnmarshalYAML

func (r *PostableApiReceiver) UnmarshalYAML(unmarshal func(interface{}) error) error

type PostableApiTemplate

type PostableApiTemplate struct {
	Name    string       `yaml:"name" json:"name"`
	Content string       `yaml:"content" json:"content"`
	Kind    TemplateKind `yaml:"kind" json:"kind"`
}

nolint:revive

func TemplatesMapToPostableAPITemplates

func TemplatesMapToPostableAPITemplates(templates map[string]string, kind TemplateKind) []PostableApiTemplate

func (*PostableApiTemplate) Validate

func (t *PostableApiTemplate) Validate() error

type PostableGrafanaReceiver

type PostableGrafanaReceiver struct {
	UID                   string            `json:"uid" yaml:"uid"`
	Name                  string            `json:"name" yaml:"name"`
	Type                  string            `json:"type" yaml:"type"`
	DisableResolveMessage bool              `json:"disableResolveMessage" yaml:"disableResolveMessage"`
	Settings              RawMessage        `json:"settings,omitempty" yaml:"settings,omitempty"`
	SecureSettings        map[string]string `json:"secureSettings,omitempty" yaml:"secureSettings,omitempty"`
}

func (*PostableGrafanaReceiver) DecryptSecureSettings

func (pgr *PostableGrafanaReceiver) DecryptSecureSettings(decryptFn func(payload []byte) ([]byte, error)) (map[string]string, error)

DecryptSecureSettings returns a map containing the decoded and decrypted secure settings.

type PostableGrafanaReceivers

type PostableGrafanaReceivers struct {
	GrafanaManagedReceivers []*PostableGrafanaReceiver `yaml:"grafana_managed_receiver_configs,omitempty" json:"grafana_managed_receiver_configs,omitempty"`
}

type Provenance

type Provenance string

type RawMessage

type RawMessage json.RawMessage // This type alias adds YAML marshaling to the json.RawMessage.

func (RawMessage) MarshalJSON

func (r RawMessage) MarshalJSON() ([]byte, error)

MarshalJSON returns m as the JSON encoding of m.

func (RawMessage) MarshalYAML

func (r RawMessage) MarshalYAML() (interface{}, error)

func (*RawMessage) UnmarshalJSON

func (r *RawMessage) UnmarshalJSON(data []byte) error

func (*RawMessage) UnmarshalYAML

func (r *RawMessage) UnmarshalYAML(unmarshal func(interface{}) error) error

type ReceiverType

type ReceiverType int
const (
	GrafanaReceiverType ReceiverType = 1 << iota
	AlertmanagerReceiverType
	EmptyReceiverType = GrafanaReceiverType | AlertmanagerReceiverType
)

func (ReceiverType) Can

func (r ReceiverType) Can(other ReceiverType) bool

Can determines whether a receiver type can implement another receiver type. This is useful as receivers with just names but no contact points are valid in all backends.

func (ReceiverType) String

func (r ReceiverType) String() string

type Route

type Route struct {
	Receiver string `yaml:"receiver,omitempty" json:"receiver,omitempty"`

	GroupByStr []string          `yaml:"group_by,omitempty" json:"group_by,omitempty"`
	GroupBy    []model.LabelName `yaml:"-" json:"-"`
	GroupByAll bool              `yaml:"-" json:"-"`
	// Deprecated. Remove before v1.0 release.
	Match map[string]string `yaml:"match,omitempty" json:"match,omitempty"`
	// Deprecated. Remove before v1.0 release.
	MatchRE             config.MatchRegexps `yaml:"match_re,omitempty" json:"match_re,omitempty"`
	Matchers            config.Matchers     `yaml:"matchers,omitempty" json:"matchers,omitempty"`
	ObjectMatchers      ObjectMatchers      `yaml:"object_matchers,omitempty" json:"object_matchers,omitempty"`
	MuteTimeIntervals   []string            `yaml:"mute_time_intervals,omitempty" json:"mute_time_intervals,omitempty"`
	ActiveTimeIntervals []string            `yaml:"active_time_intervals,omitempty" json:"active_time_intervals,omitempty"`
	Continue            bool                `yaml:"continue" json:"continue,omitempty"`
	Routes              []*Route            `yaml:"routes,omitempty" json:"routes,omitempty"`

	GroupWait      *model.Duration `yaml:"group_wait,omitempty" json:"group_wait,omitempty"`
	GroupInterval  *model.Duration `yaml:"group_interval,omitempty" json:"group_interval,omitempty"`
	RepeatInterval *model.Duration `yaml:"repeat_interval,omitempty" json:"repeat_interval,omitempty"`

	Provenance Provenance `yaml:"provenance,omitempty" json:"provenance,omitempty"`
}

A Route is a node that contains definitions of how to handle alerts. This is modified from the upstream alertmanager in that it adds the ObjectMatchers property.

func AsGrafanaRoute

func AsGrafanaRoute(r *config.Route) *Route

AsGrafanaRoute returns a Grafana route from an Alertmanager route.

func (*Route) AllMatchers

func (r *Route) AllMatchers() (config.Matchers, error)

AllMatchers returns concatenated Match, MatchRE, Matchers and ObjectMatchers in a format of config.Matchers.

func (*Route) AsAMRoute

func (r *Route) AsAMRoute() *config.Route

AsAMRoute returns an Alertmanager route from a Grafana route. The ObjectMatchers are converted to Matchers.

func (*Route) ResourceID

func (r *Route) ResourceID() string

func (*Route) ResourceType

func (r *Route) ResourceType() string

func (*Route) UnmarshalYAML

func (r *Route) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the yaml.Unmarshaler interface for Route. This is a copy of alertmanager's upstream except it removes validation on the label key.

func (*Route) Validate

func (r *Route) Validate() error

Validate normalizes a Route r, and returns errors if r is an invalid root route. Root routes must satisfy a few additional conditions.

func (*Route) ValidateChild

func (r *Route) ValidateChild() error

ValidateChild normalizes a possibly nested Route r, and returns errors if r is invalid.

func (*Route) ValidateMuteTimes

func (r *Route) ValidateMuteTimes(timeIntervals map[string]struct{}) error

ValidateMuteTimes validates that all mute time intervals referenced by the route exist. TODO: Can be removed once grafana/grafan uses ValidateTimeIntervals instead.

func (*Route) ValidateReceivers

func (r *Route) ValidateReceivers(receivers map[string]struct{}) error

func (*Route) ValidateTimeIntervals

func (r *Route) ValidateTimeIntervals(timeIntervals map[string]struct{}) error

ValidateTimeIntervals checks that all time intervals referenced by the route exist in the provided map.

type TemplateKind

type TemplateKind string
const GrafanaTemplateKind TemplateKind = "grafana"
const MimirTemplateKind TemplateKind = "mimir"

Jump to

Keyboard shortcuts

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