notifier.go 4.8 KB

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