SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
package alertmanagertypes
import (
"context"
"crypto/md5"
"encoding/json"
"fmt"
"slices"
"time"
"dario.cat/mergo"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/prometheus/alertmanager/config"
commoncfg "github.com/prometheus/common/config"
"github.com/prometheus/common/model"
"github.com/uptrace/bun"
)
const (
DefaultReceiverName string = "default-receiver"
DefaultGroupBy string = "ruleId"
DefaultGroupByAll string = "__all__"
)
var (
ErrCodeAlertmanagerConfigInvalid = errors.MustNewCode("alertmanager_config_invalid")
ErrCodeAlertmanagerConfigNotFound = errors.MustNewCode("alertmanager_config_not_found")
ErrCodeAlertmanagerConfigConflict = errors.MustNewCode("alertmanager_config_conflict")
)
type (
// GlobalConfig is the type for the global configuration.
GlobalConfig = config.GlobalConfig
)
type RouteConfig struct {
GroupByStr []string `mapstructure:"group_by"`
GroupInterval time.Duration `mapstructure:"group_interval"`
GroupWait time.Duration `mapstructure:"group_wait"`
RepeatInterval time.Duration `mapstructure:"repeat_interval"`
}
type StoreableConfig struct {
bun.BaseModel `bun:"table:alertmanager_config"`
types.Identifiable
types.TimeAuditable
Config string `bun:"config"`
Hash string `bun:"hash"`
OrgID string `bun:"org_id"`
}
// Config is the type for the entire alertmanager configuration.
type Config struct {
// alertmanagerConfig is the actual alertmanager configuration referenced from the upstream
alertmanagerConfig *config.Config
// storeableConfig is the representation of the config in the store
storeableConfig *StoreableConfig
// customConfigs holds the custom notifier configs upstream's
// config.Receiver cannot carry, keyed by receiver name.
customConfigs map[string]customReceiverConfigs
}
// customReceiverConfigs is the per-receiver custom notifier
// configs. To add another, mirror GoogleChat: a field here, a matching field
// on Receiver, and extensions to customConfigsOf + isEmpty.
type customReceiverConfigs struct {
GoogleChat []*GoogleChatReceiverConfig
Jira []*JiraReceiverConfig
JSMOps []*JSMOpsReceiverConfig
IncidentIO []*IncidentIOReceiverConfig
Telegram []*TelegramReceiverConfig
}
func (c customReceiverConfigs) isEmpty() bool {
return len(c.GoogleChat) == 0 && len(c.Jira) == 0 && len(c.JSMOps) == 0 && len(c.IncidentIO) == 0 && len(c.Telegram) == 0
}
func customConfigsOf(receiver *Receiver) customReceiverConfigs {
return customReceiverConfigs{
GoogleChat: receiver.GoogleChatConfigs,
Jira: receiver.JiraConfigs,
JSMOps: receiver.JSMOpsConfigs,
IncidentIO: receiver.IncidentIOConfigs,
Telegram: receiver.TelegramConfigs,
}
}
// storedConfig is the persistence unit. The outer Receivers shadows the
// embed's so receivers emit as the extended *Receiver (encoding/json:
// shallower-field-wins on duplicate JSON names).
type storedConfig struct {
*config.Config
Receivers []*Receiver `json:"receivers"`
}
func NewConfig(c *config.Config, orgID string) *Config {
customConfigs := make(map[string]customReceiverConfigs)
raw := string(newRawFromConfig(c, customConfigs))
return &Config{
alertmanagerConfig: c,
customConfigs: customConfigs,
storeableConfig: &StoreableConfig{
Identifiable: types.Identifiable{
ID: valuer.GenerateUUID(),
},
TimeAuditable: types.TimeAuditable{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
},
Config: raw,
Hash: fmt.Sprintf("%x", newConfigHash(raw)),
OrgID: orgID,
},
}
}
func NewConfigFromStoreableConfig(sc *StoreableConfig) (*Config, error) {
alertmanagerConfig, customConfigs, err := newConfigFromString(sc.Config)
if err != nil {
return nil, err
}
// It must be replaced with an empty, non-nil global, upstream swaps nil for
// DefaultGlobalConfig, which would let a path that skips SetGlobalConfig pass
// validation and fail silently at delivery instead of failing fast here.
alertmanagerConfig.Global = &config.GlobalConfig{}
return &Config{
alertmanagerConfig: alertmanagerConfig,
customConfigs: customConfigs,
storeableConfig: sc,
}, nil
}
func NewDefaultConfig(globalConfig GlobalConfig, routeConfig RouteConfig, orgID string) (*Config, error) {
// Mergo treats an explicit false as zero-value and overwrites it to true, so we save it in smtpRequireTLS and restore the user-specified value.
smtpRequireTLS := globalConfig.SMTPRequireTLS
err := mergo.Merge(&globalConfig, config.DefaultGlobalConfig())
if err != nil {
return nil, err
}
globalConfig.SMTPRequireTLS = smtpRequireTLS
route, err := NewRouteFromRouteConfig(nil, routeConfig)
if err != nil {
return nil, err
}
return NewConfig(&config.Config{
Global: &globalConfig,
Route: route,
Receivers: []config.Receiver{{Name: DefaultReceiverName}},
}, orgID), nil
}
func newConfigFromString(s string) (*config.Config, map[string]customReceiverConfigs, error) {
stored := storedConfig{Config: new(config.Config)}
if err := json.Unmarshal([]byte(s), &stored); err != nil {
return nil, nil, err
}
amConfig := stored.Config
amConfig.Receivers = make([]config.Receiver, len(stored.Receivers))
customConfigs := make(map[string]customReceiverConfigs)
// Re-run NewReceiver per receiver so defaults apply (mirrors create path).
for i, rcv := range stored.Receivers {
rcvJSON, err := json.Marshal(rcv)
if err != nil {
return nil, nil, err
}
parsed, err := NewReceiver(string(rcvJSON))
if err != nil {
return nil, nil, err
}
amConfig.Receivers[i] = *parsed.Receiver
if custom := customConfigsOf(parsed); !custom.isEmpty() {
customConfigs[parsed.Name] = custom
}
}
return amConfig, customConfigs, nil
}
func extendedReceivers(c *config.Config, customConfigs map[string]customReceiverConfigs) []*Receiver {
receivers := make([]*Receiver, len(c.Receivers))
for i := range c.Receivers {
base := c.Receivers[i]
custom := customConfigs[base.Name]
receivers[i] = &Receiver{
Receiver: &base,
GoogleChatConfigs: custom.GoogleChat,
JiraConfigs: custom.Jira,
JSMOpsConfigs: custom.JSMOps,
IncidentIOConfigs: custom.IncidentIO,
TelegramConfigs: custom.Telegram,
}
}
return receivers
}
func newRawFromConfig(c *config.Config, customConfigs map[string]customReceiverConfigs) []byte {
persistable := *c
persistable.Global = nil
b, err := json.Marshal(storedConfig{Config: &persistable, Receivers: extendedReceivers(c, customConfigs)})
if err != nil {
// Taking inspiration from the upstream. This is never expected to happen.
return []byte(fmt.Sprintf("<error creating config string: %s>", err))
}
return b
}
func newConfigHash(s string) [16]byte {
return md5.Sum([]byte(s))
}
// flush refreshes the storeable representation. Call after any mutation.
func (c *Config) flush() {
raw := string(newRawFromConfig(c.alertmanagerConfig, c.customConfigs))
c.storeableConfig.Config = raw
c.storeableConfig.Hash = fmt.Sprintf("%x", newConfigHash(raw))
c.storeableConfig.UpdatedAt = time.Now()
}
func (c *Config) Resolved() (*Config, error) {
raw, err := json.Marshal(storedConfig{Config: c.alertmanagerConfig, Receivers: extendedReceivers(c.alertmanagerConfig, c.customConfigs)})
if err != nil {
return nil, err
}
alertmanagerConfig, customConfigs, err := newConfigFromString(string(raw))
if err != nil {
return nil, err
}
if err := alertmanagerConfig.UnmarshalYAML(func(i interface{}) error { return nil }); err != nil {
return nil, err
}
storeableConfig := *c.storeableConfig
resolved := &Config{
alertmanagerConfig: alertmanagerConfig,
customConfigs: customConfigs,
storeableConfig: &storeableConfig,
}
resolved.applyNativeDefaults()
return resolved, nil
}
func (c *Config) validate() error {
_, err := c.Resolved()
return err
}
func (c *Config) CopyWithReset() (*Config, error) {
newConfig, err := NewDefaultConfig(
*c.alertmanagerConfig.Global,
RouteConfig{
GroupByStr: c.alertmanagerConfig.Route.GroupByStr,
GroupInterval: time.Duration(*c.alertmanagerConfig.Route.GroupInterval),
GroupWait: time.Duration(*c.alertmanagerConfig.Route.GroupWait),
RepeatInterval: time.Duration(*c.alertmanagerConfig.Route.RepeatInterval),
},
c.storeableConfig.OrgID,
)
if err != nil {
return nil, err
}
return newConfig, nil
}
func (c *Config) SetGlobalConfig(globalConfig GlobalConfig) error {
// Mergo treats an explicit false as zero-value and overwrites it to true, so we save it in smtpRequireTLS and restore the user-specified value.
smtpRequireTLS := globalConfig.SMTPRequireTLS
err := mergo.Merge(&globalConfig, config.DefaultGlobalConfig())
if err != nil {
return err
}
globalConfig.SMTPRequireTLS = smtpRequireTLS
c.alertmanagerConfig.Global = &globalConfig
c.flush()
return nil
}
func (c *Config) SetRouteConfig(routeConfig RouteConfig) error {
route, err := NewRouteFromRouteConfig(c.alertmanagerConfig.Route, routeConfig)
if err != nil {
return err
}
c.alertmanagerConfig.Route = route
c.flush()
return nil
}
func (c *Config) AddInhibitRules(rules []config.InhibitRule) error {
if c.alertmanagerConfig == nil {
return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigInvalid, "config is nil")
}
c.alertmanagerConfig.InhibitRules = append(c.alertmanagerConfig.InhibitRules, rules...)
c.flush()
return nil
}
func (c *Config) AlertmanagerConfig() *config.Config {
return c.alertmanagerConfig
}
func (c *Config) StoreableConfig() *StoreableConfig {
return c.storeableConfig
}
func cloneReceiver(receiver *Receiver) (*Receiver, error) {
raw, err := json.Marshal(receiver)
if err != nil {
return nil, err
}
return NewReceiver(string(raw))
}
func (c *Config) CreateReceiver(receiver *Receiver) error {
// check that receiver name is not already used
if c.hasReceiver(receiver.Name) {
return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigConflict, "the receiver name has to be unique, please choose a different name")
}
return c.createReceiver(receiver)
}
// CreateReceiverV2 differs from CreateReceiver only in reporting a name already in
// use as a conflict rather than as invalid input. The v2 create path is the sole
// caller: v1 create, NewConfigFromChannels and TestReceiver stay on CreateReceiver
// so their responses keep the status code clients already see.
func (c *Config) CreateReceiverV2(receiver *Receiver) error {
if c.hasReceiver(receiver.Name) {
return errors.Newf(errors.TypeAlreadyExists, ErrCodeAlertmanagerChannelAlreadyExists, "channel with display name %q already exists", receiver.Name)
}
return c.createReceiver(receiver)
}
func (c *Config) hasReceiver(name string) bool {
return slices.ContainsFunc(c.alertmanagerConfig.Receivers, func(existing config.Receiver) bool {
return existing.Name == name
})
}
func (c *Config) createReceiver(receiver *Receiver) error {
owned, err := cloneReceiver(receiver)
if err != nil {
return err
}
route, err := NewRouteFromReceiver(owned)
if err != nil {
return err
}
c.alertmanagerConfig.Route.Routes = append(c.alertmanagerConfig.Route.Routes, route)
c.alertmanagerConfig.Receivers = append(c.alertmanagerConfig.Receivers, *owned.Receiver)
c.setCustomConfigs(owned)
if err := c.validate(); err != nil {
return err
}
c.applyNativeDefaults()
c.flush()
return nil
}
func (c *Config) GetReceiver(name string) (*Receiver, error) {
for i := range c.alertmanagerConfig.Receivers {
if c.alertmanagerConfig.Receivers[i].Name == name {
base := c.alertmanagerConfig.Receivers[i]
custom := c.customConfigs[name]
return &Receiver{
Receiver: &base,
GoogleChatConfigs: custom.GoogleChat,
JiraConfigs: custom.Jira,
JSMOpsConfigs: custom.JSMOps,
IncidentIOConfigs: custom.IncidentIO,
TelegramConfigs: custom.Telegram,
}, nil
}
}
return nil, errors.Newf(errors.TypeNotFound, ErrCodeAlertmanagerChannelNotFound, "channel with name %q not found", name)
}
func (c *Config) UpdateReceiver(receiver *Receiver) error {
owned, err := cloneReceiver(receiver)
if err != nil {
return err
}
// find and update receiver
for i, existingReceiver := range c.alertmanagerConfig.Receivers {
if existingReceiver.Name == owned.Name {
c.alertmanagerConfig.Receivers[i] = *owned.Receiver
c.setCustomConfigs(owned)
break
}
}
if err := c.validate(); err != nil {
return err
}
c.applyNativeDefaults()
c.flush()
return nil
}
func (c *Config) DeleteReceiver(name string) error {
if name == "" {
return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigInvalid, "delete receiver requires the receiver name")
}
routes := c.alertmanagerConfig.Route.Routes
for i, r := range routes {
if r.Receiver == name {
c.alertmanagerConfig.Route.Routes = append(routes[:i], routes[i+1:]...)
break
}
}
for i, existingReceiver := range c.alertmanagerConfig.Receivers {
if existingReceiver.Name == name {
c.alertmanagerConfig.Receivers = append(c.alertmanagerConfig.Receivers[:i], c.alertmanagerConfig.Receivers[i+1:]...)
break
}
}
delete(c.customConfigs, name)
c.flush()
return nil
}
func (c *Config) setCustomConfigs(receiver *Receiver) {
if custom := customConfigsOf(receiver); !custom.isEmpty() {
c.customConfigs[receiver.Name] = custom
} else {
delete(c.customConfigs, receiver.Name)
}
}
func (c *Config) applyNativeDefaults() {
if c.alertmanagerConfig.Global == nil {
return
}
httpDefault := c.alertmanagerConfig.Global.HTTPConfig
for _, custom := range c.customConfigs {
for _, gc := range custom.GoogleChat {
if gc.HTTPConfig == nil {
gc.HTTPConfig = httpDefault
}
}
for _, jc := range custom.Jira {
if jc.HTTPConfig == nil {
jc.HTTPConfig = httpDefault
}
}
for _, jc := range custom.JSMOps {
if jc.HTTPConfig == nil {
jc.HTTPConfig = httpDefault
}
}
for _, ic := range custom.IncidentIO {
if ic.HTTPConfig == nil {
ic.HTTPConfig = httpDefault
}
}
for _, tc := range custom.Telegram {
if tc.HTTPConfig == nil {
tc.HTTPConfig = httpDefault
}
}
}
}
func (c *Config) CreateRuleIDMatcher(ruleID string, receiverNames []string) error {
if c.alertmanagerConfig.Route == nil {
return errors.New(errors.TypeInvalidInput, ErrCodeAlertmanagerConfigInvalid, "route is nil")
}
for _, route := range c.alertmanagerConfig.Route.Routes {
if slices.Contains(receiverNames, route.Receiver) {
if err := addRuleIDToRoute(route, ruleID); err != nil {
return err
}
}
}
c.flush()
return nil
}
func (c *Config) DeleteRuleIDInhibitor(ruleID string) error {
if c.alertmanagerConfig.InhibitRules == nil {
return nil // already nil
}
var filteredRules []config.InhibitRule
for _, inhibitor := range c.alertmanagerConfig.InhibitRules {
sourceContainsRuleID := matcherContainsRuleID(inhibitor.SourceMatchers, ruleID)
targetContainsRuleID := matcherContainsRuleID(inhibitor.TargetMatchers, ruleID)
if !sourceContainsRuleID && !targetContainsRuleID {
filteredRules = append(filteredRules, inhibitor)
}
}
c.alertmanagerConfig.InhibitRules = filteredRules
c.flush()
return nil
}
func (c *Config) UpdateRuleIDMatcher(ruleID string, receiverNames []string) error {
err := c.DeleteRuleIDMatcher(ruleID)
if err != nil {
return err
}
return c.CreateRuleIDMatcher(ruleID, receiverNames)
}
func (c *Config) DeleteRuleIDMatcher(ruleID string) error {
for i := range c.alertmanagerConfig.Route.Routes {
if err := removeRuleIDFromRoute(c.alertmanagerConfig.Route.Routes[i], ruleID); err != nil {
return err
}
}
c.flush()
return nil
}
func (c *Config) ReceiverNamesFromRuleID(ruleID string) []string {
receiverNames := make([]string, 0)
routes := c.alertmanagerConfig.Route.Routes
for _, route := range routes {
if ok := matcherContainsRuleID(route.Matchers, ruleID); ok {
receiverNames = append(receiverNames, route.Receiver)
}
}
return receiverNames
}
type storeOptions struct {
Cb func(context.Context) error
}
type StoreOption func(*storeOptions)
func WithCb(cb func(context.Context) error) StoreOption {
return func(o *storeOptions) {
o.Cb = cb
}
}
func NewStoreOptions(opts ...StoreOption) *storeOptions {
o := &storeOptions{
Cb: nil,
}
for _, opt := range opts {
opt(o)
}
return o
}
type ConfigStore interface {
// Set creates or updates a config.
Set(context.Context, *Config, ...StoreOption) error
// Get returns the config for the given orgID
Get(context.Context, string) (*Config, error)
// CreateChannel creates a new channel.
CreateChannel(context.Context, *Channel, ...StoreOption) error
// GetChannelByID returns the channel for the given id.
GetChannelByID(context.Context, string, valuer.UUID) (*Channel, error)
// UpdateChannel updates a channel.
UpdateChannel(context.Context, string, *Channel, ...StoreOption) error
// DeleteChannelByID deletes a channel.
DeleteChannelByID(context.Context, string, valuer.UUID, ...StoreOption) error
// Nil params lists every one of them in no particular order, with the
// total equal to the number returned.
ListChannels(context.Context, string, *ListChannelsParams) ([]*Channel, int64, error)
// ListAllChannels returns the list of channels for all organizations.
ListAllChannels(context.Context) ([]*Channel, error)
// GetMatchers gets a list of matchers per organization.
// Matchers is an array of ruleId to receiver names.
GetMatchers(context.Context, string) (map[string][]string, error)
}
// MarshalSecretValue if set to true will expose Secret type
// through the marshal interfaces. We need to store the actual value of the secret
// in the database, so we need to set this to true.
func init() {
commoncfg.MarshalSecretValue = true
config.MarshalSecretValue = true
}
// NotificationConfig holds configuration for alert notifications timing.
type NotificationConfig struct {
NotificationGroup map[model.LabelName]struct{}
Renotify ReNotificationConfig
UsePolicy bool
GroupByAll bool
}
func (nc *NotificationConfig) DeepCopy() NotificationConfig {
deepCopy := *nc
deepCopy.NotificationGroup = make(map[model.LabelName]struct{})
deepCopy.Renotify.NoDataInterval = nc.Renotify.NoDataInterval
deepCopy.Renotify.RenotifyInterval = nc.Renotify.RenotifyInterval
for k, v := range nc.NotificationGroup {
deepCopy.NotificationGroup[k] = v
}
deepCopy.UsePolicy = nc.UsePolicy
return deepCopy
}
type ReNotificationConfig struct {
NoDataInterval time.Duration
RenotifyInterval time.Duration
}
func NewNotificationConfig(groups []string, renotifyInterval time.Duration, noDataRenotifyInterval time.Duration, policy bool) NotificationConfig {
notificationConfig := GetDefaultNotificationConfig()
if renotifyInterval != 0 {
notificationConfig.Renotify.RenotifyInterval = renotifyInterval
}
if noDataRenotifyInterval != 0 {
notificationConfig.Renotify.NoDataInterval = noDataRenotifyInterval
}
for _, group := range groups {
notificationConfig.NotificationGroup[model.LabelName(group)] = struct{}{}
if group == DefaultGroupByAll {
notificationConfig.GroupByAll = true
}
}
notificationConfig.UsePolicy = policy
return notificationConfig
}
func GetDefaultNotificationConfig() NotificationConfig {
defaultGroups := make(map[model.LabelName]struct{})
defaultGroups[model.LabelName(DefaultGroupBy)] = struct{}{}
return NotificationConfig{
NotificationGroup: defaultGroups,
Renotify: ReNotificationConfig{
RenotifyInterval: 4 * time.Hour,
NoDataInterval: 4 * time.Hour,
}, //substitute for no - notify
}
}