notifier.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. package alerting
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "golang.org/x/sync/errgroup"
  7. "github.com/grafana/grafana/pkg/bus"
  8. "github.com/grafana/grafana/pkg/components/imguploader"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/metrics"
  11. "github.com/grafana/grafana/pkg/services/rendering"
  12. m "github.com/grafana/grafana/pkg/models"
  13. )
  14. type NotifierPlugin struct {
  15. Type string `json:"type"`
  16. Name string `json:"name"`
  17. Description string `json:"description"`
  18. OptionsTemplate string `json:"optionsTemplate"`
  19. Factory NotifierFactory `json:"-"`
  20. }
  21. type NotificationService interface {
  22. SendIfNeeded(context *EvalContext) error
  23. }
  24. func NewNotificationService(renderService rendering.Service) NotificationService {
  25. return &notificationService{
  26. log: log.New("alerting.notifier"),
  27. renderService: renderService,
  28. }
  29. }
  30. type notificationService struct {
  31. log log.Logger
  32. renderService rendering.Service
  33. }
  34. func (n *notificationService) SendIfNeeded(context *EvalContext) error {
  35. notifiers, err := n.getNeededNotifiers(context.Rule.OrgId, context.Rule.Notifications, context)
  36. if err != nil {
  37. return err
  38. }
  39. if len(notifiers) == 0 {
  40. return nil
  41. }
  42. if notifiers.ShouldUploadImage() {
  43. if err = n.uploadImage(context); err != nil {
  44. n.log.Error("Failed to upload alert panel image.", "error", err)
  45. }
  46. }
  47. return n.sendNotifications(context, notifiers)
  48. }
  49. func (n *notificationService) sendNotifications(context *EvalContext, notifiers []Notifier) error {
  50. g, _ := errgroup.WithContext(context.Ctx)
  51. for _, notifier := range notifiers {
  52. not := notifier //avoid updating scope variable in go routine
  53. n.log.Debug("Sending notification", "type", not.GetType(), "id", not.GetNotifierId(), "isDefault", not.GetIsDefault())
  54. metrics.M_Alerting_Notification_Sent.WithLabelValues(not.GetType()).Inc()
  55. g.Go(func() error {
  56. success := not.Notify(context) == nil
  57. cmd := &m.RecordNotificationJournalCommand{
  58. OrgId: context.Rule.OrgId,
  59. AlertId: context.Rule.Id,
  60. NotifierId: not.GetNotifierId(),
  61. SentAt: time.Now(),
  62. Success: success,
  63. }
  64. return bus.Dispatch(cmd)
  65. })
  66. }
  67. return g.Wait()
  68. }
  69. func (n *notificationService) uploadImage(context *EvalContext) (err error) {
  70. uploader, err := imguploader.NewImageUploader()
  71. if err != nil {
  72. return err
  73. }
  74. renderOpts := rendering.Opts{
  75. Width: 1000,
  76. Height: 500,
  77. Timeout: time.Second * 30,
  78. OrgId: context.Rule.OrgId,
  79. OrgRole: m.ROLE_ADMIN,
  80. }
  81. ref, err := context.GetDashboardUID()
  82. if err != nil {
  83. return err
  84. }
  85. renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId)
  86. result, err := n.renderService.Render(context.Ctx, renderOpts)
  87. if err != nil {
  88. return err
  89. }
  90. context.ImageOnDiskPath = result.FilePath
  91. context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath)
  92. if err != nil {
  93. return err
  94. }
  95. n.log.Info("uploaded", "url", context.ImagePublicUrl)
  96. return nil
  97. }
  98. func (n *notificationService) getNeededNotifiers(orgId int64, notificationIds []int64, context *EvalContext) (NotifierSlice, error) {
  99. query := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}
  100. if err := bus.Dispatch(query); err != nil {
  101. return nil, err
  102. }
  103. var result []Notifier
  104. for _, notification := range query.Result {
  105. not, err := n.createNotifierFor(notification)
  106. if err != nil {
  107. return nil, err
  108. }
  109. if not.ShouldNotify(context) {
  110. result = append(result, not)
  111. }
  112. }
  113. return result, nil
  114. }
  115. func (n *notificationService) createNotifierFor(model *m.AlertNotification) (Notifier, error) {
  116. notifierPlugin, found := notifierFactories[model.Type]
  117. if !found {
  118. return nil, errors.New("Unsupported notification type")
  119. }
  120. return notifierPlugin.Factory(model)
  121. }
  122. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  123. var notifierFactories = make(map[string]*NotifierPlugin)
  124. func RegisterNotifier(plugin *NotifierPlugin) {
  125. notifierFactories[plugin.Type] = plugin
  126. }
  127. func GetNotifiers() []*NotifierPlugin {
  128. list := make([]*NotifierPlugin, 0)
  129. for _, value := range notifierFactories {
  130. list = append(list, value)
  131. }
  132. return list
  133. }