From f066e8cdcd178b783d0c62959bea593d3c0c30b0 Mon Sep 17 00:00:00 2001 From: Yuri Tseretyan Date: Fri, 3 Feb 2023 11:36:49 -0500 Subject: [PATCH] Alerting: Update to alerting 20230203015918-0e4e2675d7aa (after refactoring) (#62823) * add alerting prefix to some packages from alerting that have similar names in prometheus alertmanager --- go.mod | 2 +- go.sum | 2 + pkg/services/ngalert/api/api_alertmanager.go | 22 +++---- .../ngalert/api/api_alertmanager_test.go | 6 +- .../ngalert/api/api_prometheus_test.go | 5 +- .../definitions/provisioning_contactpoints.go | 14 +++-- pkg/services/ngalert/models/alert_rule.go | 2 +- pkg/services/ngalert/notifier/alertmanager.go | 49 ++++++++------- pkg/services/ngalert/notifier/alerts.go | 6 +- .../channels_config/available_channels.go | 63 ++++++++++--------- .../notifier/channels_config/factory.go | 35 ----------- pkg/services/ngalert/notifier/config.go | 29 +++++---- pkg/services/ngalert/notifier/email_test.go | 28 +++++---- pkg/services/ngalert/notifier/file_store.go | 4 +- pkg/services/ngalert/notifier/images.go | 12 ++-- pkg/services/ngalert/notifier/log.go | 6 +- .../ngalert/notifier/multiorg_alertmanager.go | 11 ++-- pkg/services/ngalert/notifier/receivers.go | 19 +++--- .../ngalert/notifier/receivers_test.go | 26 ++++---- pkg/services/ngalert/notifier/sender.go | 8 +-- pkg/services/ngalert/notifier/silences.go | 8 +-- pkg/services/ngalert/schedule/compat.go | 2 +- pkg/services/ngalert/schedule/compat_test.go | 2 +- pkg/services/ngalert/schedule/schedule.go | 2 +- .../ngalert/schedule/schedule_unit_test.go | 2 +- .../sqlstore/migrations/ualert/ualert.go | 13 ++-- .../alerting/api_notification_channel_test.go | 54 +++++++++------- 27 files changed, 209 insertions(+), 223 deletions(-) delete mode 100644 pkg/services/ngalert/notifier/channels_config/factory.go diff --git a/go.mod b/go.mod index bd2f476ff93..dcd7bcb12b6 100644 --- a/go.mod +++ b/go.mod @@ -64,7 +64,7 @@ require ( github.com/google/uuid v1.3.0 github.com/google/wire v0.5.0 github.com/gorilla/websocket v1.5.0 - github.com/grafana/alerting v0.0.0-20230125210216-facc6b27b9e0 + github.com/grafana/alerting v0.0.0-20230203015918-0e4e2675d7aa github.com/grafana/cuetsy v0.1.5 github.com/grafana/grafana-aws-sdk v0.12.0 github.com/grafana/grafana-azure-sdk-go v1.6.0 diff --git a/go.sum b/go.sum index 6680e292558..58de62f8334 100644 --- a/go.sum +++ b/go.sum @@ -1250,6 +1250,8 @@ github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWm github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grafana/alerting v0.0.0-20230125210216-facc6b27b9e0 h1:BzkQNnj+eevX30EMqJiUS1w3CPoGc8kp7pDf/ari/4Y= github.com/grafana/alerting v0.0.0-20230125210216-facc6b27b9e0/go.mod h1:NoSLbfmUwE+omWFReFrLtbtOItmvTbuQERJ6XFYp9ME= +github.com/grafana/alerting v0.0.0-20230203015918-0e4e2675d7aa h1:ue2fctL9LHJWYw9V+R1O/uWLNTfAr/KU1EUFRsqWlK4= +github.com/grafana/alerting v0.0.0-20230203015918-0e4e2675d7aa/go.mod h1:NoSLbfmUwE+omWFReFrLtbtOItmvTbuQERJ6XFYp9ME= github.com/grafana/codejen v0.0.3 h1:tAWxoTUuhgmEqxJPOLtJoxlPBbMULFwKFOcRsPRPXDw= github.com/grafana/codejen v0.0.3/go.mod h1:zmwwM/DRyQB7pfuBjTWII3CWtxcXh8LTwAYGfDfpR6s= github.com/grafana/cuetsy v0.1.5 h1:mnFwAXdbqCsyL8r7kkdUMJ4kOAR26cxIPmrZj7JzTeY= diff --git a/pkg/services/ngalert/api/api_alertmanager.go b/pkg/services/ngalert/api/api_alertmanager.go index 0bcf6efa641..f1361df27c8 100644 --- a/pkg/services/ngalert/api/api_alertmanager.go +++ b/pkg/services/ngalert/api/api_alertmanager.go @@ -10,7 +10,7 @@ import ( "time" "github.com/go-openapi/strfmt" - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" "github.com/grafana/grafana/pkg/api/response" "github.com/grafana/grafana/pkg/infra/log" @@ -77,11 +77,11 @@ func (srv AlertmanagerSrv) RouteCreateSilence(c *contextmodel.ReqContext, postab silenceID, err := am.CreateSilence(&postableSilence) if err != nil { - if errors.Is(err, alerting.ErrSilenceNotFound) { + if errors.Is(err, alertingNotify.ErrSilenceNotFound) { return ErrResp(http.StatusNotFound, err, "") } - if errors.Is(err, alerting.ErrCreateSilenceBadPayload) { + if errors.Is(err, alertingNotify.ErrCreateSilenceBadPayload) { return ErrResp(http.StatusBadRequest, err, "") } @@ -113,7 +113,7 @@ func (srv AlertmanagerSrv) RouteDeleteSilence(c *contextmodel.ReqContext, silenc } if err := am.DeleteSilence(silenceID); err != nil { - if errors.Is(err, alerting.ErrSilenceNotFound) { + if errors.Is(err, alertingNotify.ErrSilenceNotFound) { return ErrResp(http.StatusNotFound, err, "") } return ErrResp(http.StatusInternalServerError, err, "") @@ -146,7 +146,7 @@ func (srv AlertmanagerSrv) RouteGetAMAlertGroups(c *contextmodel.ReqContext) res c.Query("receiver"), ) if err != nil { - if errors.Is(err, alerting.ErrGetAlertGroupsBadPayload) { + if errors.Is(err, alertingNotify.ErrGetAlertGroupsBadPayload) { return ErrResp(http.StatusBadRequest, err, "") } // any other error here should be an unexpected failure and thus an internal error @@ -170,10 +170,10 @@ func (srv AlertmanagerSrv) RouteGetAMAlerts(c *contextmodel.ReqContext) response c.Query("receiver"), ) if err != nil { - if errors.Is(err, alerting.ErrGetAlertsBadPayload) { + if errors.Is(err, alertingNotify.ErrGetAlertsBadPayload) { return ErrResp(http.StatusBadRequest, err, "") } - if errors.Is(err, alerting.ErrGetAlertsUnavailable) { + if errors.Is(err, alertingNotify.ErrGetAlertsUnavailable) { return ErrResp(http.StatusServiceUnavailable, err, "") } // any other error here should be an unexpected failure and thus an internal error @@ -191,7 +191,7 @@ func (srv AlertmanagerSrv) RouteGetSilence(c *contextmodel.ReqContext, silenceID gettableSilence, err := am.GetSilence(silenceID) if err != nil { - if errors.Is(err, alerting.ErrSilenceNotFound) { + if errors.Is(err, alertingNotify.ErrSilenceNotFound) { return ErrResp(http.StatusNotFound, err, "") } // any other error here should be an unexpected failure and thus an internal error @@ -208,7 +208,7 @@ func (srv AlertmanagerSrv) RouteGetSilences(c *contextmodel.ReqContext) response gettableSilences, err := am.ListSilences(c.QueryStrings("filter")) if err != nil { - if errors.Is(err, alerting.ErrListSilencesBadPayload) { + if errors.Is(err, alertingNotify.ErrListSilencesBadPayload) { return ErrResp(http.StatusBadRequest, err, "") } // any other error here should be an unexpected failure and thus an internal error @@ -288,7 +288,7 @@ func (srv AlertmanagerSrv) RoutePostTestReceivers(c *contextmodel.ReqContext, bo result, err := am.TestReceivers(ctx, body) if err != nil { - if errors.Is(err, alerting.ErrNoReceivers) { + if errors.Is(err, alertingNotify.ErrNoReceivers) { return response.Error(http.StatusBadRequest, "", err) } return response.Error(http.StatusInternalServerError, "", err) @@ -362,7 +362,7 @@ func statusForTestReceivers(v []notifier.TestReceiverResult) int { if next.Error != nil { var ( invalidReceiverErr notifier.InvalidReceiverError - receiverTimeoutErr alerting.ReceiverTimeoutError + receiverTimeoutErr alertingNotify.ReceiverTimeoutError ) if errors.As(next.Error, &invalidReceiverErr) { numBadRequests += 1 diff --git a/pkg/services/ngalert/api/api_alertmanager_test.go b/pkg/services/ngalert/api/api_alertmanager_test.go index 1362fe3c871..0cfc6bbaab8 100644 --- a/pkg/services/ngalert/api/api_alertmanager_test.go +++ b/pkg/services/ngalert/api/api_alertmanager_test.go @@ -9,7 +9,7 @@ import ( "time" "github.com/go-openapi/strfmt" - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" amv2 "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" @@ -128,7 +128,7 @@ func TestStatusForTestReceivers(t *testing.T) { Name: "test1", UID: "uid1", Status: "failed", - Error: alerting.ReceiverTimeoutError{}, + Error: alertingNotify.ReceiverTimeoutError{}, }}, }, { Name: "test2", @@ -136,7 +136,7 @@ func TestStatusForTestReceivers(t *testing.T) { Name: "test2", UID: "uid2", Status: "failed", - Error: alerting.ReceiverTimeoutError{}, + Error: alertingNotify.ReceiverTimeoutError{}, }}, }})) }) diff --git a/pkg/services/ngalert/api/api_prometheus_test.go b/pkg/services/ngalert/api/api_prometheus_test.go index 03e4d05bf03..6f085d8ab29 100644 --- a/pkg/services/ngalert/api/api_prometheus_test.go +++ b/pkg/services/ngalert/api/api_prometheus_test.go @@ -9,12 +9,13 @@ import ( "testing" "time" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/grafana/grafana-plugin-sdk-go/data" - "github.com/grafana/grafana/pkg/expr" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/expr" + "github.com/grafana/grafana/pkg/infra/log" acmock "github.com/grafana/grafana/pkg/services/accesscontrol/mock" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" diff --git a/pkg/services/ngalert/api/tooling/definitions/provisioning_contactpoints.go b/pkg/services/ngalert/api/tooling/definitions/provisioning_contactpoints.go index 84fcfb7c4ec..4b432b7ce39 100644 --- a/pkg/services/ngalert/api/tooling/definitions/provisioning_contactpoints.go +++ b/pkg/services/ngalert/api/tooling/definitions/provisioning_contactpoints.go @@ -3,7 +3,9 @@ package definitions import ( "fmt" - "github.com/grafana/alerting/alerting/notifier/channels" + "github.com/grafana/alerting/logging" + alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/services/ngalert/notifier/channels_config" @@ -99,14 +101,14 @@ type EmbeddedContactPoint struct { const RedactedValue = "[REDACTED]" -func (e *EmbeddedContactPoint) Valid(decryptFunc channels.GetDecryptedValueFn) error { +func (e *EmbeddedContactPoint) Valid(decryptFunc receivers.GetDecryptedValueFn) error { if e.Type == "" { return fmt.Errorf("type should not be an empty string") } if e.Settings == nil { return fmt.Errorf("settings should not be empty") } - factory, exists := channels_config.Factory(e.Type) + factory, exists := alertingNotify.Factory(e.Type) if !exists { return fmt.Errorf("unknown type '%s'", e.Type) } @@ -114,11 +116,11 @@ func (e *EmbeddedContactPoint) Valid(decryptFunc channels.GetDecryptedValueFn) e if err != nil { return err } - cfg, _ := channels.NewFactoryConfig(&channels.NotificationChannelConfig{ + cfg, _ := receivers.NewFactoryConfig(&receivers.NotificationChannelConfig{ Settings: jsonBytes, Type: e.Type, - }, nil, decryptFunc, nil, nil, func(ctx ...interface{}) channels.Logger { - return &channels.FakeLogger{} + }, nil, decryptFunc, nil, nil, func(ctx ...interface{}) logging.Logger { + return &logging.FakeLogger{} }, setting.BuildVersion) if _, err := factory(cfg); err != nil { return err diff --git a/pkg/services/ngalert/models/alert_rule.go b/pkg/services/ngalert/models/alert_rule.go index 85fb5748064..83452cfb1da 100644 --- a/pkg/services/ngalert/models/alert_rule.go +++ b/pkg/services/ngalert/models/alert_rule.go @@ -11,7 +11,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/grafana/grafana/pkg/services/quota" "github.com/grafana/grafana/pkg/util/cmputil" diff --git a/pkg/services/ngalert/notifier/alertmanager.go b/pkg/services/ngalert/notifier/alertmanager.go index bfcb588d727..875010fa942 100644 --- a/pkg/services/ngalert/notifier/alertmanager.go +++ b/pkg/services/ngalert/notifier/alertmanager.go @@ -11,8 +11,10 @@ import ( "strconv" "time" - "github.com/grafana/alerting/alerting" - "github.com/grafana/alerting/alerting/notifier/channels" + alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers" + alertingTemplates "github.com/grafana/alerting/templates" + amv2 "github.com/prometheus/alertmanager/api/v2/models" "github.com/grafana/grafana/pkg/infra/kvstore" @@ -20,7 +22,6 @@ import ( apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" "github.com/grafana/grafana/pkg/services/ngalert/metrics" ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models" - "github.com/grafana/grafana/pkg/services/ngalert/notifier/channels_config" "github.com/grafana/grafana/pkg/services/ngalert/store" "github.com/grafana/grafana/pkg/services/notifications" "github.com/grafana/grafana/pkg/setting" @@ -45,7 +46,7 @@ type AlertingStore interface { } type Alertmanager struct { - Base *alerting.GrafanaAlertmanager + Base *alertingNotify.GrafanaAlertmanager logger log.Logger Settings *setting.Cfg @@ -53,7 +54,7 @@ type Alertmanager struct { fileStore *FileStore NotificationService notifications.Service - decryptFn channels.GetDecryptedValueFn + decryptFn receivers.GetDecryptedValueFn orgID int64 } @@ -63,7 +64,7 @@ type maintenanceOptions struct { filepath string retention time.Duration maintenanceFrequency time.Duration - maintenanceFunc func(alerting.State) (int64, error) + maintenanceFunc func(alertingNotify.State) (int64, error) } func (m maintenanceOptions) Filepath() string { @@ -78,12 +79,12 @@ func (m maintenanceOptions) MaintenanceFrequency() time.Duration { return m.maintenanceFrequency } -func (m maintenanceOptions) MaintenanceFunc(state alerting.State) (int64, error) { +func (m maintenanceOptions) MaintenanceFunc(state alertingNotify.State) (int64, error) { return m.maintenanceFunc(state) } func newAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store AlertingStore, kvStore kvstore.KVStore, - peer alerting.ClusterPeer, decryptFn channels.GetDecryptedValueFn, ns notifications.Service, + peer alertingNotify.ClusterPeer, decryptFn receivers.GetDecryptedValueFn, ns notifications.Service, m *metrics.Alertmanager) (*Alertmanager, error) { workingPath := filepath.Join(cfg.DataPath, workingDir, strconv.Itoa(int(orgID))) fileStore := NewFileStore(orgID, kvStore, workingPath) @@ -101,7 +102,7 @@ func newAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A filepath: silencesFilePath, retention: retentionNotificationsAndSilences, maintenanceFrequency: silenceMaintenanceInterval, - maintenanceFunc: func(state alerting.State) (int64, error) { + maintenanceFunc: func(state alertingNotify.State) (int64, error) { return fileStore.Persist(ctx, silencesFilename, state) }, } @@ -110,12 +111,12 @@ func newAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A filepath: nflogFilepath, retention: retentionNotificationsAndSilences, maintenanceFrequency: notificationLogMaintenanceInterval, - maintenanceFunc: func(state alerting.State) (int64, error) { + maintenanceFunc: func(state alertingNotify.State) (int64, error) { return fileStore.Persist(ctx, notificationLogFilename, state) }, } - amcfg := &alerting.GrafanaAlertmanagerConfig{ + amcfg := &alertingNotify.GrafanaAlertmanagerConfig{ WorkingDirectory: workingDir, AlertStoreCallback: nil, PeerTimeout: cfg.UnifiedAlerting.HAPeerTimeout, @@ -124,7 +125,7 @@ func newAlertmanager(ctx context.Context, orgID int64, cfg *setting.Cfg, store A } l := log.New("alertmanager", "org", orgID) - gam, err := alerting.NewGrafanaAlertmanager("orgID", orgID, amcfg, peer, l, alerting.NewGrafanaAlertmanagerMetrics(m.Registerer)) + gam, err := alertingNotify.NewGrafanaAlertmanager("orgID", orgID, amcfg, peer, l, alertingNotify.NewGrafanaAlertmanagerMetrics(m.Registerer)) if err != nil { return nil, err } @@ -257,7 +258,7 @@ func (am *Alertmanager) applyConfig(cfg *apimodels.PostableUserConfig, rawConfig if cfg.TemplateFiles == nil { cfg.TemplateFiles = map[string]string{} } - cfg.TemplateFiles["__default__.tmpl"] = channels.DefaultTemplateString + cfg.TemplateFiles["__default__.tmpl"] = alertingTemplates.DefaultTemplateString // next, we need to make sure we persist the templates to disk. paths, templatesChanged, err := PersistTemplates(cfg, am.WorkingDirPath()) @@ -314,8 +315,8 @@ func (am *Alertmanager) WorkingDirPath() string { } // buildIntegrationsMap builds a map of name to the list of Grafana integration notifiers off of a list of receiver config. -func (am *Alertmanager) buildIntegrationsMap(receivers []*apimodels.PostableApiReceiver, templates *alerting.Template) (map[string][]*alerting.Integration, error) { - integrationsMap := make(map[string][]*alerting.Integration, len(receivers)) +func (am *Alertmanager) buildIntegrationsMap(receivers []*apimodels.PostableApiReceiver, templates *alertingNotify.Template) (map[string][]*alertingNotify.Integration, error) { + integrationsMap := make(map[string][]*alertingNotify.Integration, len(receivers)) for _, receiver := range receivers { integrations, err := am.buildReceiverIntegrations(receiver, templates) if err != nil { @@ -328,19 +329,19 @@ func (am *Alertmanager) buildIntegrationsMap(receivers []*apimodels.PostableApiR } // buildReceiverIntegrations builds a list of integration notifiers off of a receiver config. -func (am *Alertmanager) buildReceiverIntegrations(receiver *apimodels.PostableApiReceiver, tmpl *alerting.Template) ([]*alerting.Integration, error) { - integrations := make([]*alerting.Integration, 0, len(receiver.GrafanaManagedReceivers)) +func (am *Alertmanager) buildReceiverIntegrations(receiver *apimodels.PostableApiReceiver, tmpl *alertingNotify.Template) ([]*alertingNotify.Integration, error) { + integrations := make([]*alertingNotify.Integration, 0, len(receiver.GrafanaManagedReceivers)) for i, r := range receiver.GrafanaManagedReceivers { n, err := am.buildReceiverIntegration(r, tmpl) if err != nil { return nil, err } - integrations = append(integrations, alerting.NewIntegration(n, n, r.Type, i)) + integrations = append(integrations, alertingNotify.NewIntegration(n, n, r.Type, i)) } return integrations, nil } -func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaReceiver, tmpl *alerting.Template) (channels.NotificationChannel, error) { +func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaReceiver, tmpl *alertingNotify.Template) (alertingNotify.NotificationChannel, error) { // secure settings are already encrypted at this point secureSettings := make(map[string][]byte, len(r.SecureSettings)) @@ -356,7 +357,7 @@ func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaRec } var ( - cfg = &channels.NotificationChannelConfig{ + cfg = &receivers.NotificationChannelConfig{ UID: r.UID, OrgID: am.orgID, Name: r.Name, @@ -366,14 +367,14 @@ func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaRec SecureSettings: secureSettings, } ) - factoryConfig, err := channels.NewFactoryConfig(cfg, NewNotificationSender(am.NotificationService), am.decryptFn, tmpl, newImageStore(am.Store), LoggerFactory, setting.BuildVersion) + factoryConfig, err := receivers.NewFactoryConfig(cfg, NewNotificationSender(am.NotificationService), am.decryptFn, tmpl, newImageStore(am.Store), LoggerFactory, setting.BuildVersion) if err != nil { return nil, InvalidReceiverError{ Receiver: r, Err: err, } } - receiverFactory, exists := channels_config.Factory(r.Type) + receiverFactory, exists := alertingNotify.Factory(r.Type) if !exists { return nil, InvalidReceiverError{ Receiver: r, @@ -392,9 +393,9 @@ func (am *Alertmanager) buildReceiverIntegration(r *apimodels.PostableGrafanaRec // PutAlerts receives the alerts and then sends them through the corresponding route based on whenever the alert has a receiver embedded or not func (am *Alertmanager) PutAlerts(postableAlerts apimodels.PostableAlerts) error { - alerts := make(alerting.PostableAlerts, 0, len(postableAlerts.PostableAlerts)) + alerts := make(alertingNotify.PostableAlerts, 0, len(postableAlerts.PostableAlerts)) for _, pa := range postableAlerts.PostableAlerts { - alerts = append(alerts, &alerting.PostableAlert{ + alerts = append(alerts, &alertingNotify.PostableAlert{ Annotations: pa.Annotations, EndsAt: pa.EndsAt, StartsAt: pa.StartsAt, diff --git a/pkg/services/ngalert/notifier/alerts.go b/pkg/services/ngalert/notifier/alerts.go index a4a853ad0e7..c74eb8d31c7 100644 --- a/pkg/services/ngalert/notifier/alerts.go +++ b/pkg/services/ngalert/notifier/alerts.go @@ -1,13 +1,13 @@ package notifier import ( - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" ) -func (am *Alertmanager) GetAlerts(active, silenced, inhibited bool, filter []string, receivers string) (alerting.GettableAlerts, error) { +func (am *Alertmanager) GetAlerts(active, silenced, inhibited bool, filter []string, receivers string) (alertingNotify.GettableAlerts, error) { return am.Base.GetAlerts(active, silenced, inhibited, filter, receivers) } -func (am *Alertmanager) GetAlertGroups(active, silenced, inhibited bool, filter []string, receivers string) (alerting.AlertGroups, error) { +func (am *Alertmanager) GetAlertGroups(active, silenced, inhibited bool, filter []string, receivers string) (alertingNotify.AlertGroups, error) { return am.Base.GetAlertGroups(active, silenced, inhibited, filter, receivers) } diff --git a/pkg/services/ngalert/notifier/channels_config/available_channels.go b/pkg/services/ngalert/notifier/channels_config/available_channels.go index 9d4787bb162..2f81aa7af18 100644 --- a/pkg/services/ngalert/notifier/channels_config/available_channels.go +++ b/pkg/services/ngalert/notifier/channels_config/available_channels.go @@ -3,7 +3,8 @@ package channels_config import ( "os" - "github.com/grafana/alerting/alerting/notifier/channels" + alertingOpsgenie "github.com/grafana/alerting/receivers/opsgenie" + alertingTemplates "github.com/grafana/alerting/templates" ) // GetAvailableNotifiers returns the metadata of all the notification channels that can be configured. @@ -141,14 +142,14 @@ func GetAvailableNotifiers() []*NotifierPlugin { Element: ElementTypeInput, InputType: InputTypeText, Description: "Templated title of the message", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "title", }, { // New in 8.0. Label: "Message", Element: ElementTypeTextArea, Description: "Custom DingDing message. You can use template variables.", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, }, @@ -229,14 +230,14 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated description of the Kafka message", PropertyName: "description", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { Label: "Details", Element: ElementTypeTextArea, Description: "Custom details to include with the message. You can use template variables.", PropertyName: "details", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, }, }, }, @@ -271,7 +272,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated subject of the email", PropertyName: "subject", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, }, }, @@ -325,7 +326,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { Description: "You can use templates for summary", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "summary", }, { // New in 9.4. @@ -388,7 +389,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated title to display", PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { // New in 9.3. Label: "Description", @@ -396,7 +397,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated description of the message", PropertyName: "description", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, }, }, }, @@ -475,13 +476,13 @@ func GetAvailableNotifiers() []*NotifierPlugin { Label: "Title", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "title", }, { // New in 8.0. Label: "Message", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, }, @@ -659,7 +660,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { { // New in 8.0. Label: "Message", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, }, @@ -684,7 +685,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated title of the Teams message.", PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { Label: "Section Title", @@ -696,7 +697,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { { // New in 8.0. Label: "Message", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, }, @@ -727,7 +728,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { { // New in 8.0. Label: "Message", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, { @@ -832,14 +833,14 @@ func GetAvailableNotifiers() []*NotifierPlugin { Element: ElementTypeInput, InputType: InputTypeText, PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { // New in 9.3. Label: "Message", Description: "Custom message. You can use template variables.", Element: ElementTypeTextArea, PropertyName: "message", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, }, }, }, @@ -911,7 +912,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { Label: "Message", Description: "Custom WeCom message. You can use template variables.", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, { // New in 9.1. @@ -920,7 +921,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated title of the message", PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { Label: "To User", @@ -971,7 +972,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { Description: "Templated title of the message", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "title", }, { @@ -979,7 +980,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { Description: "Mention a group using @ or a user using <@ID> when notifying in a channel", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, { @@ -1023,13 +1024,13 @@ func GetAvailableNotifiers() []*NotifierPlugin { Description: "Templated title of the message", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "title", }, { Label: "Message", Element: ElementTypeTextArea, - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, PropertyName: "message", }, }, @@ -1055,7 +1056,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated title of the message", PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { // New in 9.3 Label: "Description", @@ -1063,7 +1064,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated description of the message", PropertyName: "description", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, }, }, }, @@ -1110,7 +1111,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated title of the message.", PropertyName: "title", - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, }, { // New in 9.3 Label: "Description", @@ -1118,7 +1119,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { InputType: InputTypeText, Description: "Templated description of the message.", PropertyName: "description", - Placeholder: channels.DefaultMessageEmbed, + Placeholder: alertingTemplates.DefaultMessageEmbed, }, }, }, @@ -1150,7 +1151,7 @@ func GetAvailableNotifiers() []*NotifierPlugin { Description: "Alert text limited to 130 characters.", Element: ElementTypeInput, InputType: InputTypeText, - Placeholder: channels.DefaultMessageTitleEmbed, + Placeholder: alertingTemplates.DefaultMessageTitleEmbed, PropertyName: "message", }, { @@ -1175,15 +1176,15 @@ func GetAvailableNotifiers() []*NotifierPlugin { Element: ElementTypeSelect, SelectOptions: []SelectOption{ { - Value: channels.OpsgenieSendTags, + Value: alertingOpsgenie.SendTags, Label: "Tags", }, { - Value: channels.OpsgenieSendDetails, + Value: alertingOpsgenie.SendDetails, Label: "Extra Properties", }, { - Value: channels.OpsgenieSendBoth, + Value: alertingOpsgenie.SendBoth, Label: "Tags & Extra Properties", }, }, diff --git a/pkg/services/ngalert/notifier/channels_config/factory.go b/pkg/services/ngalert/notifier/channels_config/factory.go deleted file mode 100644 index 888ecdb8305..00000000000 --- a/pkg/services/ngalert/notifier/channels_config/factory.go +++ /dev/null @@ -1,35 +0,0 @@ -package channels_config - -import ( - "strings" - - "github.com/grafana/alerting/alerting/notifier/channels" -) - -var receiverFactories = map[string]func(channels.FactoryConfig) (channels.NotificationChannel, error){ - "prometheus-alertmanager": channels.AlertmanagerFactory, - "dingding": channels.DingDingFactory, - "discord": channels.DiscordFactory, - "email": channels.EmailFactory, - "googlechat": channels.GoogleChatFactory, - "kafka": channels.KafkaFactory, - "line": channels.LineFactory, - "opsgenie": channels.OpsgenieFactory, - "pagerduty": channels.PagerdutyFactory, - "pushover": channels.PushoverFactory, - "sensugo": channels.SensuGoFactory, - "slack": channels.SlackFactory, - "teams": channels.TeamsFactory, - "telegram": channels.TelegramFactory, - "threema": channels.ThreemaFactory, - "victorops": channels.VictorOpsFactory, - "webhook": channels.WebHookFactory, - "wecom": channels.WeComFactory, - "webex": channels.WebexFactory, -} - -func Factory(receiverType string) (func(channels.FactoryConfig) (channels.NotificationChannel, error), bool) { - receiverType = strings.ToLower(receiverType) - factory, exists := receiverFactories[receiverType] - return factory, exists -} diff --git a/pkg/services/ngalert/notifier/config.go b/pkg/services/ngalert/notifier/config.go index c8fcc99f2e9..d59338ce663 100644 --- a/pkg/services/ngalert/notifier/config.go +++ b/pkg/services/ngalert/notifier/config.go @@ -7,8 +7,7 @@ import ( "os" "path/filepath" - "github.com/grafana/alerting/alerting" - "github.com/grafana/alerting/alerting/notifier/channels" + alertingNotify "github.com/grafana/alerting/notify" "github.com/grafana/grafana/pkg/infra/log" api "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" @@ -90,20 +89,20 @@ func Load(rawConfig []byte) (*api.PostableUserConfig, error) { } // AlertingConfiguration provides configuration for an Alertmanager. -// It implements the alerting.Configuration interface. +// It implements the notify.Configuration interface. type AlertingConfiguration struct { AlertmanagerConfig api.PostableApiAlertingConfig RawAlertmanagerConfig []byte - AlertmanagerTemplates *alerting.Template + AlertmanagerTemplates *alertingNotify.Template - IntegrationsFunc func(receivers []*api.PostableApiReceiver, templates *alerting.Template) (map[string][]*alerting.Integration, error) - ReceiverIntegrationsFunc func(r *api.PostableGrafanaReceiver, tmpl *alerting.Template) (channels.NotificationChannel, error) + IntegrationsFunc func(receivers []*api.PostableApiReceiver, templates *alertingNotify.Template) (map[string][]*alertingNotify.Integration, error) + ReceiverIntegrationsFunc func(r *api.PostableGrafanaReceiver, tmpl *alertingNotify.Template) (alertingNotify.NotificationChannel, error) } -func (a AlertingConfiguration) BuildReceiverIntegrationsFunc() func(next *alerting.GrafanaReceiver, tmpl *alerting.Template) (alerting.Notifier, error) { - return func(next *alerting.GrafanaReceiver, tmpl *alerting.Template) (alerting.Notifier, error) { - //TODO: We shouldn't need to do all of this marshalling - there should be no difference between types. +func (a AlertingConfiguration) BuildReceiverIntegrationsFunc() func(next *alertingNotify.GrafanaReceiver, tmpl *alertingNotify.Template) (alertingNotify.Notifier, error) { + return func(next *alertingNotify.GrafanaReceiver, tmpl *alertingNotify.Template) (alertingNotify.Notifier, error) { + // TODO: We shouldn't need to do all of this marshalling - there should be no difference between types. var out api.RawMessage settingsJSON, err := json.Marshal(next.Settings) if err != nil { @@ -126,27 +125,27 @@ func (a AlertingConfiguration) BuildReceiverIntegrationsFunc() func(next *alerti } } -func (a AlertingConfiguration) DispatcherLimits() alerting.DispatcherLimits { +func (a AlertingConfiguration) DispatcherLimits() alertingNotify.DispatcherLimits { return &nilLimits{} } -func (a AlertingConfiguration) InhibitRules() []alerting.InhibitRule { +func (a AlertingConfiguration) InhibitRules() []alertingNotify.InhibitRule { return a.AlertmanagerConfig.InhibitRules } -func (a AlertingConfiguration) MuteTimeIntervals() []alerting.MuteTimeInterval { +func (a AlertingConfiguration) MuteTimeIntervals() []alertingNotify.MuteTimeInterval { return a.AlertmanagerConfig.MuteTimeIntervals } -func (a AlertingConfiguration) ReceiverIntegrations() (map[string][]*alerting.Integration, error) { +func (a AlertingConfiguration) ReceiverIntegrations() (map[string][]*alertingNotify.Integration, error) { return a.IntegrationsFunc(a.AlertmanagerConfig.Receivers, a.AlertmanagerTemplates) } -func (a AlertingConfiguration) RoutingTree() *alerting.Route { +func (a AlertingConfiguration) RoutingTree() *alertingNotify.Route { return a.AlertmanagerConfig.Route.AsAMRoute() } -func (a AlertingConfiguration) Templates() *alerting.Template { +func (a AlertingConfiguration) Templates() *alertingNotify.Template { return a.AlertmanagerTemplates } diff --git a/pkg/services/ngalert/notifier/email_test.go b/pkg/services/ngalert/notifier/email_test.go index 19c659c3fb5..7bcd66a10a2 100644 --- a/pkg/services/ngalert/notifier/email_test.go +++ b/pkg/services/ngalert/notifier/email_test.go @@ -7,7 +7,11 @@ import ( "os" "testing" - "github.com/grafana/alerting/alerting/notifier/channels" + "github.com/grafana/alerting/images" + alertingLogging "github.com/grafana/alerting/logging" + "github.com/grafana/alerting/receivers" + alertingEmail "github.com/grafana/alerting/receivers/email" + alertingTemplates "github.com/grafana/alerting/templates" "github.com/prometheus/alertmanager/template" "github.com/prometheus/alertmanager/types" "github.com/prometheus/common/model" @@ -19,7 +23,7 @@ import ( "github.com/grafana/grafana/pkg/setting" ) -// TestEmailNotifierIntegration tests channels.EmailNotifier in conjunction with Grafana notifications.EmailSender and two staged expansion of the email body +// TestEmailNotifierIntegration tests channels.EmailNotifier in conjunction with Grafana notifications.EmailSender and two staged expansion of the alertingEmail body func TestEmailNotifierIntegration(t *testing.T) { ns := createEmailSender(t) @@ -184,7 +188,7 @@ func TestEmailNotifierIntegration(t *testing.T) { } } -func createSut(t *testing.T, messageTmpl string, subjectTmpl string, emailTmpl *template.Template, ns channels.NotificationSender) channels.NotificationChannel { +func createSut(t *testing.T, messageTmpl string, subjectTmpl string, emailTmpl *template.Template, ns receivers.NotificationSender) *alertingEmail.Notifier { t.Helper() jsonData := map[string]interface{}{ @@ -201,21 +205,21 @@ func createSut(t *testing.T, messageTmpl string, subjectTmpl string, emailTmpl * bytes, err := json.Marshal(jsonData) require.NoError(t, err) - fc := channels.FactoryConfig{ - Config: &channels.NotificationChannelConfig{ + fc := receivers.FactoryConfig{ + Config: &receivers.NotificationChannelConfig{ Name: "ops", - Type: "email", + Type: "alertingEmail", Settings: json.RawMessage(bytes), }, NotificationService: ns, DecryptFunc: func(ctx context.Context, sjd map[string][]byte, key string, fallback string) string { return fallback }, - ImageStore: &channels.UnavailableImageStore{}, + ImageStore: &images.UnavailableImageStore{}, Template: emailTmpl, - Logger: &channels.FakeLogger{}, + Logger: &alertingLogging.FakeLogger{}, } - emailNotifier, err := channels.EmailFactory(fc) + emailNotifier, err := alertingEmail.New(fc) require.NoError(t, err) return emailNotifier } @@ -234,11 +238,11 @@ type emailSender struct { ns *notifications.NotificationService } -func (e emailSender) SendWebhook(ctx context.Context, cmd *channels.SendWebhookSettings) error { +func (e emailSender) SendWebhook(ctx context.Context, cmd *receivers.SendWebhookSettings) error { panic("not implemented") } -func (e emailSender) SendEmail(ctx context.Context, cmd *channels.SendEmailSettings) error { +func (e emailSender) SendEmail(ctx context.Context, cmd *receivers.SendEmailSettings) error { attached := make([]*notifications.SendEmailAttachFile, 0, len(cmd.AttachedFiles)) for _, file := range cmd.AttachedFiles { attached = append(attached, ¬ifications.SendEmailAttachFile{ @@ -295,7 +299,7 @@ func templateForTests(t *testing.T) *template.Template { require.NoError(t, os.RemoveAll(f.Name())) }) - _, err = f.WriteString(channels.TemplateForTestsString) + _, err = f.WriteString(alertingTemplates.TemplateForTestsString) require.NoError(t, err) tmpl, err := template.FromGlobs([]string{f.Name()}) diff --git a/pkg/services/ngalert/notifier/file_store.go b/pkg/services/ngalert/notifier/file_store.go index c9acb0f0ad4..3f4c36820aa 100644 --- a/pkg/services/ngalert/notifier/file_store.go +++ b/pkg/services/ngalert/notifier/file_store.go @@ -7,7 +7,7 @@ import ( "os" "path/filepath" - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" @@ -63,7 +63,7 @@ func (fileStore *FileStore) FilepathFor(ctx context.Context, filename string) (s } // Persist takes care of persisting the binary representation of internal state to the database as a base64 encoded string. -func (fileStore *FileStore) Persist(ctx context.Context, filename string, st alerting.State) (int64, error) { +func (fileStore *FileStore) Persist(ctx context.Context, filename string, st alertingNotify.State) (int64, error) { var size int64 bytes, err := st.MarshalBinary() diff --git a/pkg/services/ngalert/notifier/images.go b/pkg/services/ngalert/notifier/images.go index 222dc552837..bbeec8b36bb 100644 --- a/pkg/services/ngalert/notifier/images.go +++ b/pkg/services/ngalert/notifier/images.go @@ -4,7 +4,7 @@ import ( "context" "errors" - "github.com/grafana/alerting/alerting/notifier/channels" + "github.com/grafana/alerting/images" "github.com/grafana/grafana/pkg/services/ngalert/models" "github.com/grafana/grafana/pkg/services/ngalert/store" @@ -14,22 +14,22 @@ type imageStore struct { store store.ImageStore } -func newImageStore(store store.ImageStore) channels.ImageStore { +func newImageStore(store store.ImageStore) images.ImageStore { return &imageStore{ store: store, } } -func (i imageStore) GetImage(ctx context.Context, token string) (*channels.Image, error) { +func (i imageStore) GetImage(ctx context.Context, token string) (*images.Image, error) { image, err := i.store.GetImage(ctx, token) if err != nil { if errors.Is(err, models.ErrImageNotFound) { - err = channels.ErrImageNotFound + err = images.ErrImageNotFound } } - var result *channels.Image + var result *images.Image if image != nil { - result = &channels.Image{ + result = &images.Image{ Token: image.Token, Path: image.Path, URL: image.URL, diff --git a/pkg/services/ngalert/notifier/log.go b/pkg/services/ngalert/notifier/log.go index fe59a0fec92..a48477d8abe 100644 --- a/pkg/services/ngalert/notifier/log.go +++ b/pkg/services/ngalert/notifier/log.go @@ -1,12 +1,12 @@ package notifier import ( - "github.com/grafana/alerting/alerting/notifier/channels" + alertingLogging "github.com/grafana/alerting/logging" "github.com/grafana/grafana/pkg/infra/log" ) -var LoggerFactory channels.LoggerFactory = func(ctx ...interface{}) channels.Logger { +var LoggerFactory alertingLogging.LoggerFactory = func(ctx ...interface{}) alertingLogging.Logger { return &logWrapper{log.New(ctx...)} } @@ -14,6 +14,6 @@ type logWrapper struct { *log.ConcreteLogger } -func (l logWrapper) New(ctx ...interface{}) channels.Logger { +func (l logWrapper) New(ctx ...interface{}) alertingLogging.Logger { return logWrapper{l.ConcreteLogger.New(ctx...)} } diff --git a/pkg/services/ngalert/notifier/multiorg_alertmanager.go b/pkg/services/ngalert/notifier/multiorg_alertmanager.go index dc484647c2c..1ee6e350dbb 100644 --- a/pkg/services/ngalert/notifier/multiorg_alertmanager.go +++ b/pkg/services/ngalert/notifier/multiorg_alertmanager.go @@ -9,11 +9,12 @@ import ( "sync" "time" - "github.com/grafana/alerting/alerting" - "github.com/grafana/alerting/alerting/notifier/channels" "github.com/prometheus/alertmanager/cluster" "github.com/prometheus/client_golang/prometheus" + alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers" + "github.com/grafana/grafana/pkg/infra/kvstore" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/ngalert/metrics" @@ -41,21 +42,21 @@ type MultiOrgAlertmanager struct { logger log.Logger // clusterPeer represents the clustering peers of Alertmanagers between Grafana instances. - peer alerting.ClusterPeer + peer alertingNotify.ClusterPeer settleCancel context.CancelFunc configStore AlertingStore orgStore store.OrgStore kvStore kvstore.KVStore - decryptFn channels.GetDecryptedValueFn + decryptFn receivers.GetDecryptedValueFn metrics *metrics.MultiOrgAlertmanager ns notifications.Service } func NewMultiOrgAlertmanager(cfg *setting.Cfg, configStore AlertingStore, orgStore store.OrgStore, - kvStore kvstore.KVStore, provStore provisioning.ProvisioningStore, decryptFn channels.GetDecryptedValueFn, + kvStore kvstore.KVStore, provStore provisioning.ProvisioningStore, decryptFn receivers.GetDecryptedValueFn, m *metrics.MultiOrgAlertmanager, ns notifications.Service, l log.Logger, s secrets.Service, ) (*MultiOrgAlertmanager, error) { moa := &MultiOrgAlertmanager{ diff --git a/pkg/services/ngalert/notifier/receivers.go b/pkg/services/ngalert/notifier/receivers.go index 7e56baaa64b..9410ce69512 100644 --- a/pkg/services/ngalert/notifier/receivers.go +++ b/pkg/services/ngalert/notifier/receivers.go @@ -7,8 +7,9 @@ import ( "fmt" "time" + alertingNotify "github.com/grafana/alerting/notify" + "github.com/go-openapi/strfmt" - "github.com/grafana/alerting/alerting" "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/alertmanager/types" @@ -56,9 +57,9 @@ func (e ReceiverTimeoutError) Error() string { } func (am *Alertmanager) TestReceivers(ctx context.Context, c apimodels.TestReceiversConfigBodyParams) (*TestReceiversResult, error) { - receivers := make([]*alerting.APIReceiver, 0, len(c.Receivers)) + receivers := make([]*alertingNotify.APIReceiver, 0, len(c.Receivers)) for _, r := range c.Receivers { - greceivers := make([]*alerting.GrafanaReceiver, 0, len(r.GrafanaManagedReceivers)) + greceivers := make([]*alertingNotify.GrafanaReceiver, 0, len(r.GrafanaManagedReceivers)) for _, gr := range r.PostableGrafanaReceivers.GrafanaManagedReceivers { var settings map[string]interface{} //TODO: We shouldn't need to do this marshalling. @@ -72,7 +73,7 @@ func (am *Alertmanager) TestReceivers(ctx context.Context, c apimodels.TestRecei return nil, fmt.Errorf("unable to marshal settings into map: %v", err) } - greceivers = append(greceivers, &alerting.GrafanaReceiver{ + greceivers = append(greceivers, &alertingNotify.GrafanaReceiver{ UID: gr.UID, Name: gr.Name, Type: gr.Type, @@ -81,19 +82,19 @@ func (am *Alertmanager) TestReceivers(ctx context.Context, c apimodels.TestRecei SecureSettings: gr.SecureSettings, }) } - receivers = append(receivers, &alerting.APIReceiver{ + receivers = append(receivers, &alertingNotify.APIReceiver{ ConfigReceiver: r.Receiver, - GrafanaReceivers: alerting.GrafanaReceivers{ + GrafanaReceivers: alertingNotify.GrafanaReceivers{ Receivers: greceivers, }, }) } - var alert *alerting.TestReceiversConfigAlertParams + var alert *alertingNotify.TestReceiversConfigAlertParams if c.Alert != nil { - alert = &alerting.TestReceiversConfigAlertParams{Annotations: c.Alert.Annotations, Labels: c.Alert.Labels} + alert = &alertingNotify.TestReceiversConfigAlertParams{Annotations: c.Alert.Annotations, Labels: c.Alert.Labels} } - result, err := am.Base.TestReceivers(ctx, alerting.TestReceiversConfigBodyParams{ + result, err := am.Base.TestReceivers(ctx, alertingNotify.TestReceiversConfigBodyParams{ Alert: alert, Receivers: receivers, }) diff --git a/pkg/services/ngalert/notifier/receivers_test.go b/pkg/services/ngalert/notifier/receivers_test.go index d9b923c5de9..2c3b3102946 100644 --- a/pkg/services/ngalert/notifier/receivers_test.go +++ b/pkg/services/ngalert/notifier/receivers_test.go @@ -6,13 +6,13 @@ import ( "net/url" "testing" - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" "github.com/stretchr/testify/require" ) func TestInvalidReceiverError_Error(t *testing.T) { - e := alerting.InvalidReceiverError{ - Receiver: &alerting.GrafanaReceiver{ + e := alertingNotify.InvalidReceiverError{ + Receiver: &alertingNotify.GrafanaReceiver{ Name: "test", UID: "uid", }, @@ -22,8 +22,8 @@ func TestInvalidReceiverError_Error(t *testing.T) { } func TestReceiverTimeoutError_Error(t *testing.T) { - e := alerting.ReceiverTimeoutError{ - Receiver: &alerting.GrafanaReceiver{ + e := alertingNotify.ReceiverTimeoutError{ + Receiver: &alertingNotify.GrafanaReceiver{ Name: "test", UID: "uid", }, @@ -44,18 +44,18 @@ func (e timeoutError) Timeout() bool { func TestProcessNotifierError(t *testing.T) { t.Run("assert ReceiverTimeoutError is returned for context deadline exceeded", func(t *testing.T) { - r := &alerting.GrafanaReceiver{ + r := &alertingNotify.GrafanaReceiver{ Name: "test", UID: "uid", } - require.Equal(t, alerting.ReceiverTimeoutError{ + require.Equal(t, alertingNotify.ReceiverTimeoutError{ Receiver: r, Err: context.DeadlineExceeded, - }, alerting.ProcessNotifierError(r, context.DeadlineExceeded)) + }, alertingNotify.ProcessNotifierError(r, context.DeadlineExceeded)) }) t.Run("assert ReceiverTimeoutError is returned for *url.Error timeout", func(t *testing.T) { - r := &alerting.GrafanaReceiver{ + r := &alertingNotify.GrafanaReceiver{ Name: "test", UID: "uid", } @@ -64,18 +64,18 @@ func TestProcessNotifierError(t *testing.T) { URL: "https://grafana.net", Err: timeoutError{}, } - require.Equal(t, alerting.ReceiverTimeoutError{ + require.Equal(t, alertingNotify.ReceiverTimeoutError{ Receiver: r, Err: urlError, - }, alerting.ProcessNotifierError(r, urlError)) + }, alertingNotify.ProcessNotifierError(r, urlError)) }) t.Run("assert unknown error is returned unmodified", func(t *testing.T) { - r := &alerting.GrafanaReceiver{ + r := &alertingNotify.GrafanaReceiver{ Name: "test", UID: "uid", } err := errors.New("this is an error") - require.Equal(t, err, alerting.ProcessNotifierError(r, err)) + require.Equal(t, err, alertingNotify.ProcessNotifierError(r, err)) }) } diff --git a/pkg/services/ngalert/notifier/sender.go b/pkg/services/ngalert/notifier/sender.go index fd016cabec9..13fcebba592 100644 --- a/pkg/services/ngalert/notifier/sender.go +++ b/pkg/services/ngalert/notifier/sender.go @@ -3,7 +3,7 @@ package notifier import ( "context" - "github.com/grafana/alerting/alerting/notifier/channels" + "github.com/grafana/alerting/receivers" "github.com/grafana/grafana/pkg/services/notifications" ) @@ -12,7 +12,7 @@ type sender struct { ns notifications.Service } -func (s sender) SendWebhook(ctx context.Context, cmd *channels.SendWebhookSettings) error { +func (s sender) SendWebhook(ctx context.Context, cmd *receivers.SendWebhookSettings) error { return s.ns.SendWebhookSync(ctx, ¬ifications.SendWebhookSync{ Url: cmd.URL, User: cmd.User, @@ -25,7 +25,7 @@ func (s sender) SendWebhook(ctx context.Context, cmd *channels.SendWebhookSettin }) } -func (s sender) SendEmail(ctx context.Context, cmd *channels.SendEmailSettings) error { +func (s sender) SendEmail(ctx context.Context, cmd *receivers.SendEmailSettings) error { var attached []*notifications.SendEmailAttachFile if cmd.AttachedFiles != nil { attached = make([]*notifications.SendEmailAttachFile, 0, len(cmd.AttachedFiles)) @@ -51,6 +51,6 @@ func (s sender) SendEmail(ctx context.Context, cmd *channels.SendEmailSettings) }) } -func NewNotificationSender(ns notifications.Service) channels.NotificationSender { +func NewNotificationSender(ns notifications.Service) receivers.NotificationSender { return &sender{ns: ns} } diff --git a/pkg/services/ngalert/notifier/silences.go b/pkg/services/ngalert/notifier/silences.go index d69efcde06c..bbc57bba855 100644 --- a/pkg/services/ngalert/notifier/silences.go +++ b/pkg/services/ngalert/notifier/silences.go @@ -1,18 +1,18 @@ package notifier import ( - "github.com/grafana/alerting/alerting" + alertingNotify "github.com/grafana/alerting/notify" ) -func (am *Alertmanager) ListSilences(filter []string) (alerting.GettableSilences, error) { +func (am *Alertmanager) ListSilences(filter []string) (alertingNotify.GettableSilences, error) { return am.Base.ListSilences(filter) } -func (am *Alertmanager) GetSilence(silenceID string) (alerting.GettableSilence, error) { +func (am *Alertmanager) GetSilence(silenceID string) (alertingNotify.GettableSilence, error) { return am.Base.GetSilence(silenceID) } -func (am *Alertmanager) CreateSilence(ps *alerting.PostableSilence) (string, error) { +func (am *Alertmanager) CreateSilence(ps *alertingNotify.PostableSilence) (string, error) { return am.Base.CreateSilence(ps) } diff --git a/pkg/services/ngalert/schedule/compat.go b/pkg/services/ngalert/schedule/compat.go index 282403bd4f7..94f8a14b2a3 100644 --- a/pkg/services/ngalert/schedule/compat.go +++ b/pkg/services/ngalert/schedule/compat.go @@ -10,7 +10,7 @@ import ( "github.com/benbjohnson/clock" "github.com/go-openapi/strfmt" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/common/model" diff --git a/pkg/services/ngalert/schedule/compat_test.go b/pkg/services/ngalert/schedule/compat_test.go index fa97ad58305..419f79795ea 100644 --- a/pkg/services/ngalert/schedule/compat_test.go +++ b/pkg/services/ngalert/schedule/compat_test.go @@ -9,7 +9,7 @@ import ( "github.com/benbjohnson/clock" "github.com/go-openapi/strfmt" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/prometheus/alertmanager/api/v2/models" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" diff --git a/pkg/services/ngalert/schedule/schedule.go b/pkg/services/ngalert/schedule/schedule.go index 62a6a391842..a6f5e9c5fed 100644 --- a/pkg/services/ngalert/schedule/schedule.go +++ b/pkg/services/ngalert/schedule/schedule.go @@ -8,7 +8,7 @@ import ( "time" "github.com/benbjohnson/clock" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/hashicorp/go-multierror" prometheusModel "github.com/prometheus/common/model" "go.opentelemetry.io/otel/attribute" diff --git a/pkg/services/ngalert/schedule/schedule_unit_test.go b/pkg/services/ngalert/schedule/schedule_unit_test.go index 02fc1aee2ec..f667af9532c 100644 --- a/pkg/services/ngalert/schedule/schedule_unit_test.go +++ b/pkg/services/ngalert/schedule/schedule_unit_test.go @@ -11,7 +11,7 @@ import ( "time" "github.com/benbjohnson/clock" - alertingModels "github.com/grafana/alerting/alerting/models" + alertingModels "github.com/grafana/alerting/models" "github.com/grafana/grafana-plugin-sdk-go/data" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" diff --git a/pkg/services/sqlstore/migrations/ualert/ualert.go b/pkg/services/sqlstore/migrations/ualert/ualert.go index eb319f03787..8544e5471a9 100644 --- a/pkg/services/sqlstore/migrations/ualert/ualert.go +++ b/pkg/services/sqlstore/migrations/ualert/ualert.go @@ -12,12 +12,13 @@ import ( "strings" "time" - "github.com/grafana/alerting/alerting/notifier/channels" + alertingLogging "github.com/grafana/alerting/logging" + alertingNotify "github.com/grafana/alerting/notify" + "github.com/grafana/alerting/receivers" pb "github.com/prometheus/alertmanager/silence/silencepb" "xorm.io/xorm" ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models" - "github.com/grafana/grafana/pkg/services/ngalert/notifier/channels_config" "github.com/grafana/grafana/pkg/services/sqlstore/migrator" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" @@ -478,7 +479,7 @@ func (m *migration) validateAlertmanagerConfig(orgID int64, config *PostableUser return err } var ( - cfg = &channels.NotificationChannelConfig{ + cfg = &receivers.NotificationChannelConfig{ UID: gr.UID, OrgID: orgID, Name: gr.Name, @@ -502,12 +503,12 @@ func (m *migration) validateAlertmanagerConfig(orgID int64, config *PostableUser } return fallback } - receiverFactory, exists := channels_config.Factory(gr.Type) + receiverFactory, exists := alertingNotify.Factory(gr.Type) if !exists { return fmt.Errorf("notifier %s is not supported", gr.Type) } - factoryConfig, err := channels.NewFactoryConfig(cfg, nil, decryptFunc, nil, nil, func(ctx ...interface{}) channels.Logger { - return &channels.FakeLogger{} + factoryConfig, err := receivers.NewFactoryConfig(cfg, nil, decryptFunc, nil, nil, func(ctx ...interface{}) alertingLogging.Logger { + return &alertingLogging.FakeLogger{} }, setting.BuildVersion) if err != nil { return err diff --git a/pkg/tests/api/alerting/api_notification_channel_test.go b/pkg/tests/api/alerting/api_notification_channel_test.go index 5f6e38f6aab..363385f60d8 100644 --- a/pkg/tests/api/alerting/api_notification_channel_test.go +++ b/pkg/tests/api/alerting/api_notification_channel_test.go @@ -16,12 +16,20 @@ import ( "testing" "time" - "github.com/grafana/alerting/alerting/notifier/channels" - "github.com/grafana/grafana/pkg/expr" + "github.com/grafana/alerting/receivers" + alertingLine "github.com/grafana/alerting/receivers/line" + alertingPagerduty "github.com/grafana/alerting/receivers/pagerduty" + alertingPushover "github.com/grafana/alerting/receivers/pushover" + alertingSlack "github.com/grafana/alerting/receivers/slack" + alertingTelegram "github.com/grafana/alerting/receivers/telegram" + alertingThreema "github.com/grafana/alerting/receivers/threema" + alertingTemplates "github.com/grafana/alerting/templates" "github.com/prometheus/alertmanager/template" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" + "github.com/grafana/grafana/pkg/expr" + "github.com/grafana/grafana/pkg/infra/db" apimodels "github.com/grafana/grafana/pkg/services/ngalert/api/tooling/definitions" ngmodels "github.com/grafana/grafana/pkg/services/ngalert/models" @@ -720,24 +728,24 @@ func TestIntegrationNotificationChannels(t *testing.T) { mockChannel.responses["slack_recvX"] = `{"ok": true}` // Overriding some URLs to send to the mock channel. - os, opa, ot, opu, ogb, ol, oth := channels.SlackAPIEndpoint, channels.PagerdutyEventAPIURL, - channels.TelegramAPIURL, channels.PushoverEndpoint, channels.GetBoundary, - channels.LineNotifyURL, channels.ThreemaGwBaseURL - originalTemplate := channels.DefaultTemplateString + os, opa, ot, opu, ogb, ol, oth := alertingSlack.APIURL, alertingPagerduty.APIURL, + alertingTelegram.APIURL, alertingPushover.APIURL, receivers.GetBoundary, + alertingLine.APIURL, alertingThreema.APIURL + originalTemplate := alertingTemplates.DefaultTemplateString t.Cleanup(func() { - channels.SlackAPIEndpoint, channels.PagerdutyEventAPIURL, - channels.TelegramAPIURL, channels.PushoverEndpoint, channels.GetBoundary, - channels.LineNotifyURL, channels.ThreemaGwBaseURL = os, opa, ot, opu, ogb, ol, oth - channels.DefaultTemplateString = originalTemplate + alertingSlack.APIURL, alertingPagerduty.APIURL, + alertingTelegram.APIURL, alertingPushover.APIURL, receivers.GetBoundary, + alertingLine.APIURL, alertingThreema.APIURL = os, opa, ot, opu, ogb, ol, oth + alertingTemplates.DefaultTemplateString = originalTemplate }) - channels.DefaultTemplateString = channels.TemplateForTestsString - channels.SlackAPIEndpoint = fmt.Sprintf("http://%s/slack_recvX/slack_testX", mockChannel.server.Addr) - channels.PagerdutyEventAPIURL = fmt.Sprintf("http://%s/pagerduty_recvX/pagerduty_testX", mockChannel.server.Addr) - channels.TelegramAPIURL = fmt.Sprintf("http://%s/telegram_recv/bot%%s/%%s", mockChannel.server.Addr) - channels.PushoverEndpoint = fmt.Sprintf("http://%s/pushover_recv/pushover_test", mockChannel.server.Addr) - channels.LineNotifyURL = fmt.Sprintf("http://%s/line_recv/line_test", mockChannel.server.Addr) - channels.ThreemaGwBaseURL = fmt.Sprintf("http://%s/threema_recv/threema_test", mockChannel.server.Addr) - channels.GetBoundary = func() string { return "abcd" } + alertingTemplates.DefaultTemplateString = alertingTemplates.TemplateForTestsString + alertingSlack.APIURL = fmt.Sprintf("http://%s/slack_recvX/slack_testX", mockChannel.server.Addr) + alertingPagerduty.APIURL = fmt.Sprintf("http://%s/pagerduty_recvX/pagerduty_testX", mockChannel.server.Addr) + alertingTelegram.APIURL = fmt.Sprintf("http://%s/telegram_recv/bot%%s/%%s", mockChannel.server.Addr) + alertingPushover.APIURL = fmt.Sprintf("http://%s/pushover_recv/pushover_test", mockChannel.server.Addr) + alertingLine.APIURL = fmt.Sprintf("http://%s/line_recv/line_test", mockChannel.server.Addr) + alertingThreema.APIURL = fmt.Sprintf("http://%s/threema_recv/threema_test", mockChannel.server.Addr) + receivers.GetBoundary = func() string { return "abcd" } env.NotificationService.EmailHandlerSync = mockEmail.sendEmailCommandHandlerSync // As we are using a NotificationService mock here, but the test expects real NotificationService - @@ -1153,8 +1161,8 @@ func multipartEqual(t *testing.T, exp, act string) { } } - expReader := multipart.NewReader(strings.NewReader(exp), channels.GetBoundary()) - actReader := multipart.NewReader(strings.NewReader(act), channels.GetBoundary()) + expReader := multipart.NewReader(strings.NewReader(exp), receivers.GetBoundary()) + actReader := multipart.NewReader(strings.NewReader(act), receivers.GetBoundary()) expMap, actMap := make(map[string]string), make(map[string]string) fillMap(expReader, expMap) fillMap(actReader, actMap) @@ -1172,7 +1180,7 @@ type mockEmailHandler struct { func (e *mockEmailHandler) sendEmailCommandHandlerSync(_ context.Context, cmd *notifications.SendEmailCommandSync) error { // We 0 out the start time since that is a variable that we cannot predict. - alerts := cmd.Data["Alerts"].(channels.ExtendedAlerts) + alerts := cmd.Data["Alerts"].(alertingTemplates.ExtendedAlerts) for i := range alerts { alerts[i].StartsAt = time.Time{} } @@ -2293,8 +2301,8 @@ var expEmailNotifications = []*notifications.SendEmailCommandSync{ "Title": "[FIRING:1] EmailAlert (default)", "Message": "", "Status": "firing", - "Alerts": channels.ExtendedAlerts{ - channels.ExtendedAlert{ + "Alerts": alertingTemplates.ExtendedAlerts{ + alertingTemplates.ExtendedAlert{ Status: "firing", Labels: template.KV{"alertname": "EmailAlert", "grafana_folder": "default"}, Annotations: template.KV{},