notifier.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. package alerting
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "time"
  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(evalContext *EvalContext, notifiers []Notifier) error {
  50. for _, notifier := range notifiers {
  51. not := notifier
  52. err := bus.InTransaction(evalContext.Ctx, func(ctx context.Context) error {
  53. n.log.Debug("trying to send notification", "id", not.GetNotifierId())
  54. // Verify that we can send the notification again
  55. // but this time within the same transaction.
  56. if !evalContext.IsTestRun && !not.ShouldNotify(context.Background(), evalContext) {
  57. return nil
  58. }
  59. n.log.Debug("Sending notification", "type", not.GetType(), "id", not.GetNotifierId(), "isDefault", not.GetIsDefault())
  60. metrics.M_Alerting_Notification_Sent.WithLabelValues(not.GetType()).Inc()
  61. //send notification
  62. success := not.Notify(evalContext) == nil
  63. if evalContext.IsTestRun {
  64. return nil
  65. }
  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. if err != nil {
  77. n.log.Error("failed to send notification", "id", not.GetNotifierId())
  78. }
  79. }
  80. return nil
  81. }
  82. func (n *notificationService) uploadImage(context *EvalContext) (err error) {
  83. uploader, err := imguploader.NewImageUploader()
  84. if err != nil {
  85. return err
  86. }
  87. renderOpts := rendering.Opts{
  88. Width: 1000,
  89. Height: 500,
  90. Timeout: alertTimeout / 2,
  91. OrgId: context.Rule.OrgId,
  92. OrgRole: m.ROLE_ADMIN,
  93. }
  94. ref, err := context.GetDashboardUID()
  95. if err != nil {
  96. return err
  97. }
  98. renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId)
  99. result, err := n.renderService.Render(context.Ctx, renderOpts)
  100. if err != nil {
  101. return err
  102. }
  103. context.ImageOnDiskPath = result.FilePath
  104. context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath)
  105. if err != nil {
  106. return err
  107. }
  108. if context.ImagePublicUrl != "" {
  109. n.log.Info("uploaded screenshot of alert to external image store", "url", context.ImagePublicUrl)
  110. }
  111. return nil
  112. }
  113. func (n *notificationService) getNeededNotifiers(orgId int64, notificationIds []int64, evalContext *EvalContext) (NotifierSlice, error) {
  114. query := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}
  115. if err := bus.Dispatch(query); err != nil {
  116. return nil, err
  117. }
  118. var result []Notifier
  119. for _, notification := range query.Result {
  120. not, err := n.createNotifierFor(notification)
  121. if err != nil {
  122. return nil, err
  123. }
  124. if not.ShouldNotify(evalContext.Ctx, evalContext) {
  125. result = append(result, not)
  126. }
  127. }
  128. return result, nil
  129. }
  130. func (n *notificationService) createNotifierFor(model *m.AlertNotification) (Notifier, error) {
  131. notifierPlugin, found := notifierFactories[model.Type]
  132. if !found {
  133. return nil, errors.New("Unsupported notification type")
  134. }
  135. return notifierPlugin.Factory(model)
  136. }
  137. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  138. var notifierFactories = make(map[string]*NotifierPlugin)
  139. func RegisterNotifier(plugin *NotifierPlugin) {
  140. notifierFactories[plugin.Type] = plugin
  141. }
  142. func GetNotifiers() []*NotifierPlugin {
  143. list := make([]*NotifierPlugin, 0)
  144. for _, value := range notifierFactories {
  145. list = append(list, value)
  146. }
  147. return list
  148. }