notifier.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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) NeedsImage() bool {
  20. return false
  21. }
  22. func (n *RootNotifier) Notify(context *EvalContext) {
  23. n.log.Info("Sending notifications for", "ruleId", context.Rule.Id)
  24. notifiers, err := n.getNotifiers(context.Rule.OrgId, context.Rule.Notifications)
  25. if err != nil {
  26. n.log.Error("Failed to read notifications", "error", err)
  27. return
  28. }
  29. for _, notifier := range notifiers {
  30. n.log.Info("Sending notification", "firing", context.Firing, "type", notifier.GetType())
  31. go notifier.Notify(context)
  32. }
  33. }
  34. func (n *RootNotifier) getNotifiers(orgId int64, notificationIds []int64) ([]Notifier, error) {
  35. query := &m.GetAlertNotificationsQuery{OrgId: orgId, Ids: notificationIds}
  36. if err := bus.Dispatch(query); err != nil {
  37. return nil, err
  38. }
  39. var result []Notifier
  40. for _, notification := range query.Result {
  41. if not, err := n.getNotifierFor(notification); err != nil {
  42. return nil, err
  43. } else {
  44. result = append(result, not)
  45. }
  46. }
  47. return result, nil
  48. }
  49. func (n *RootNotifier) getNotifierFor(model *m.AlertNotification) (Notifier, error) {
  50. factory, found := notifierFactories[model.Type]
  51. if !found {
  52. return nil, errors.New("Unsupported notification type")
  53. }
  54. return factory(model)
  55. }
  56. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  57. var notifierFactories map[string]NotifierFactory = make(map[string]NotifierFactory)
  58. func RegisterNotifier(typeName string, factory NotifierFactory) {
  59. notifierFactories[typeName] = factory
  60. }