notifier.go 4.8 KB

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