notifier.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package alerting
  2. import (
  3. "errors"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/log"
  6. m "github.com/grafana/grafana/pkg/models"
  7. )
  8. type RootNotifier struct {
  9. log log.Logger
  10. }
  11. func NewRootNotifier() *RootNotifier {
  12. return &RootNotifier{
  13. log: log.New("alerting.notifier"),
  14. }
  15. }
  16. func (n *RootNotifier) GetType() string {
  17. return "root"
  18. }
  19. func (n *RootNotifier) Notify(context *EvalContext) {
  20. n.log.Info("Sending notifications for", "ruleId", context.Rule.Id)
  21. notifiers, err := n.getNotifiers(context.Rule.OrgId, context.Rule.Notifications)
  22. if err != nil {
  23. n.log.Error("Failed to read notifications", "error", err)
  24. return
  25. }
  26. for _, notifier := range notifiers {
  27. n.log.Info("Sending notification", "firing", context.Firing, "type", notifier.GetType())
  28. go notifier.Notify(context)
  29. }
  30. }
  31. func (n *RootNotifier) getNotifiers(orgId int64, notificationIds []int64) ([]Notifier, error) {
  32. query := &m.GetAlertNotificationsQuery{OrgId: orgId, Ids: notificationIds}
  33. if err := bus.Dispatch(query); err != nil {
  34. return nil, err
  35. }
  36. var result []Notifier
  37. for _, notification := range query.Result {
  38. if not, err := n.getNotifierFor(notification); err != nil {
  39. return nil, err
  40. } else {
  41. result = append(result, not)
  42. }
  43. }
  44. return result, nil
  45. }
  46. func (n *RootNotifier) getNotifierFor(model *m.AlertNotification) (Notifier, error) {
  47. factory, found := notifierFactories[model.Type]
  48. if !found {
  49. return nil, errors.New("Unsupported notification type")
  50. }
  51. return factory(model)
  52. }
  53. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  54. var notifierFactories map[string]NotifierFactory = make(map[string]NotifierFactory)
  55. func RegisterNotifier(typeName string, factory NotifierFactory) {
  56. notifierFactories[typeName] = factory
  57. }