notifier.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package alerting
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  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. notifierStates, err := n.getNeededNotifiers(context.Rule.OrgId, context.Rule.Notifications, context)
  35. if err != nil {
  36. return err
  37. }
  38. if len(notifierStates) == 0 {
  39. return nil
  40. }
  41. if notifierStates.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, notifierStates)
  47. }
  48. func (n *notificationService) sendAndMarkAsComplete(evalContext *EvalContext, notifierState *NotifierState) error {
  49. err := notifierState.notifier.Notify(evalContext)
  50. cmd := &m.SetAlertNotificationStateToCompleteCommand{
  51. Id: notifierState.state.Id,
  52. Version: notifierState.state.Version,
  53. SentAt: time.Now().Unix(),
  54. }
  55. err = bus.DispatchCtx(evalContext.Ctx, cmd)
  56. if err == m.ErrAlertNotificationStateVersionConflict {
  57. return nil
  58. }
  59. if err != nil {
  60. return err
  61. }
  62. return nil
  63. }
  64. func (n *notificationService) sendNotification(evalContext *EvalContext, notifierState *NotifierState) error {
  65. n.log.Debug("trying to send notification", "id", notifierState.notifier.GetNotifierId())
  66. setPendingCmd := &m.SetAlertNotificationStateToPendingCommand{
  67. State: notifierState.state,
  68. }
  69. err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd)
  70. if err == m.ErrAlertNotificationStateVersionConflict {
  71. return nil
  72. }
  73. if err != nil {
  74. return err
  75. }
  76. return n.sendAndMarkAsComplete(evalContext, notifierState)
  77. }
  78. func (n *notificationService) sendNotifications(evalContext *EvalContext, notifierStates NotifierStateSlice) error {
  79. for _, notifierState := range notifierStates {
  80. err := n.sendNotification(evalContext, notifierState)
  81. if err != nil {
  82. n.log.Error("failed to send notification", "id", notifierState.notifier.GetNotifierId())
  83. }
  84. }
  85. return nil
  86. }
  87. func (n *notificationService) uploadImage(context *EvalContext) (err error) {
  88. uploader, err := imguploader.NewImageUploader()
  89. if err != nil {
  90. return err
  91. }
  92. renderOpts := rendering.Opts{
  93. Width: 1000,
  94. Height: 500,
  95. Timeout: alertTimeout / 2,
  96. OrgId: context.Rule.OrgId,
  97. OrgRole: m.ROLE_ADMIN,
  98. ConcurrentLimit: setting.AlertingRenderLimit,
  99. }
  100. ref, err := context.GetDashboardUID()
  101. if err != nil {
  102. return err
  103. }
  104. renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?panelId=%d", ref.Uid, ref.Slug, context.Rule.PanelId)
  105. result, err := n.renderService.Render(context.Ctx, renderOpts)
  106. if err != nil {
  107. return err
  108. }
  109. context.ImageOnDiskPath = result.FilePath
  110. context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath)
  111. if err != nil {
  112. return err
  113. }
  114. if context.ImagePublicUrl != "" {
  115. n.log.Info("uploaded screenshot of alert to external image store", "url", context.ImagePublicUrl)
  116. }
  117. return nil
  118. }
  119. func (n *notificationService) getNeededNotifiers(orgId int64, notificationIds []int64, evalContext *EvalContext) (NotifierStateSlice, error) {
  120. query := &m.GetAlertNotificationsToSendQuery{OrgId: orgId, Ids: notificationIds}
  121. if err := bus.Dispatch(query); err != nil {
  122. return nil, err
  123. }
  124. var result NotifierStateSlice
  125. for _, notification := range query.Result {
  126. not, err := n.createNotifierFor(notification)
  127. if err != nil {
  128. n.log.Error("Could not create notifier", "notifier", notification.Id)
  129. continue
  130. }
  131. query := &m.GetNotificationStateQuery{
  132. NotifierId: notification.Id,
  133. AlertId: evalContext.Rule.Id,
  134. OrgId: evalContext.Rule.OrgId,
  135. }
  136. err = bus.DispatchCtx(evalContext.Ctx, query)
  137. if err != nil {
  138. n.log.Error("Could not get notification state.", "notifier", notification.Id)
  139. continue
  140. }
  141. if not.ShouldNotify(evalContext.Ctx, evalContext, query.Result) {
  142. result = append(result, &NotifierState{
  143. notifier: not,
  144. state: query.Result,
  145. })
  146. }
  147. }
  148. return result, nil
  149. }
  150. func (n *notificationService) createNotifierFor(model *m.AlertNotification) (Notifier, error) {
  151. notifierPlugin, found := notifierFactories[model.Type]
  152. if !found {
  153. return nil, errors.New("Unsupported notification type")
  154. }
  155. return notifierPlugin.Factory(model)
  156. }
  157. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  158. var notifierFactories = make(map[string]*NotifierPlugin)
  159. func RegisterNotifier(plugin *NotifierPlugin) {
  160. notifierFactories[plugin.Type] = plugin
  161. }
  162. func GetNotifiers() []*NotifierPlugin {
  163. list := make([]*NotifierPlugin, 0)
  164. for _, value := range notifierFactories {
  165. list = append(list, value)
  166. }
  167. return list
  168. }