notifier.go 4.9 KB

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