notifier.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. //write result to db.
  64. cmd := &m.RecordNotificationJournalCommand{
  65. OrgId: evalContext.Rule.OrgId,
  66. AlertId: evalContext.Rule.Id,
  67. NotifierId: not.GetNotifierId(),
  68. SentAt: time.Now().Unix(),
  69. Success: success,
  70. }
  71. return bus.DispatchCtx(ctx, cmd)
  72. })
  73. if err != nil {
  74. n.log.Error("failed to send notification", "id", not.GetNotifierId())
  75. }
  76. }
  77. return nil
  78. }
  79. func (n *notificationService) uploadImage(context *EvalContext) (err error) {
  80. uploader, err := imguploader.NewImageUploader()
  81. if err != nil {
  82. return err
  83. }
  84. renderOpts := rendering.Opts{
  85. Width: 1000,
  86. Height: 500,
  87. Timeout: time.Second * 30,
  88. OrgId: context.Rule.OrgId,
  89. OrgRole: m.ROLE_ADMIN,
  90. }
  91. ref, err := context.GetDashboardUID()
  92. if err != nil {
  93. return err
  94. }
  95. renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId)
  96. result, err := n.renderService.Render(context.Ctx, renderOpts)
  97. if err != nil {
  98. return err
  99. }
  100. context.ImageOnDiskPath = result.FilePath
  101. context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath)
  102. if err != nil {
  103. return err
  104. }
  105. if context.ImagePublicUrl != "" {
  106. n.log.Info("uploaded screenshot of alert to external image store", "url", context.ImagePublicUrl)
  107. }
  108. return nil
  109. }
  110. func (n *notificationService) getNeededNotifiers(orgId int64, notificationIds []int64, evalContext *EvalContext) (NotifierSlice, error) {
  111. query := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}
  112. if err := bus.Dispatch(query); err != nil {
  113. return nil, err
  114. }
  115. var result []Notifier
  116. for _, notification := range query.Result {
  117. not, err := n.createNotifierFor(notification)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if not.ShouldNotify(evalContext.Ctx, evalContext) {
  122. result = append(result, not)
  123. }
  124. }
  125. return result, nil
  126. }
  127. func (n *notificationService) createNotifierFor(model *m.AlertNotification) (Notifier, error) {
  128. notifierPlugin, found := notifierFactories[model.Type]
  129. if !found {
  130. return nil, errors.New("Unsupported notification type")
  131. }
  132. return notifierPlugin.Factory(model)
  133. }
  134. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  135. var notifierFactories = make(map[string]*NotifierPlugin)
  136. func RegisterNotifier(plugin *NotifierPlugin) {
  137. notifierFactories[plugin.Type] = plugin
  138. }
  139. func GetNotifiers() []*NotifierPlugin {
  140. list := make([]*NotifierPlugin, 0)
  141. for _, value := range notifierFactories {
  142. list = append(list, value)
  143. }
  144. return list
  145. }