notifier.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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/infra/metrics"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/services/rendering"
  11. "github.com/grafana/grafana/pkg/setting"
  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. notifierStates, err := n.getNeededNotifiers(context.Rule.OrgId, context.Rule.Notifications, context)
  36. if err != nil {
  37. return err
  38. }
  39. if len(notifierStates) == 0 {
  40. return nil
  41. }
  42. if notifierStates.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, notifierStates)
  48. }
  49. func (n *notificationService) sendAndMarkAsComplete(evalContext *EvalContext, notifierState *notifierState) error {
  50. notifier := notifierState.notifier
  51. n.log.Debug("Sending notification", "type", notifier.GetType(), "uid", notifier.GetNotifierUid(), "isDefault", notifier.GetIsDefault())
  52. metrics.M_Alerting_Notification_Sent.WithLabelValues(notifier.GetType()).Inc()
  53. err := notifier.Notify(evalContext)
  54. if err != nil {
  55. n.log.Error("failed to send notification", "uid", notifier.GetNotifierUid(), "error", err)
  56. }
  57. if evalContext.IsTestRun {
  58. return nil
  59. }
  60. cmd := &m.SetAlertNotificationStateToCompleteCommand{
  61. Id: notifierState.state.Id,
  62. Version: notifierState.state.Version,
  63. }
  64. return bus.DispatchCtx(evalContext.Ctx, cmd)
  65. }
  66. func (n *notificationService) sendNotification(evalContext *EvalContext, notifierState *notifierState) error {
  67. if !evalContext.IsTestRun {
  68. setPendingCmd := &m.SetAlertNotificationStateToPendingCommand{
  69. Id: notifierState.state.Id,
  70. Version: notifierState.state.Version,
  71. AlertRuleStateUpdatedVersion: evalContext.Rule.StateChanges,
  72. }
  73. err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd)
  74. if err == m.ErrAlertNotificationStateVersionConflict {
  75. return nil
  76. }
  77. if err != nil {
  78. return err
  79. }
  80. // We need to update state version to be able to log
  81. // unexpected version conflicts when marking notifications as ok
  82. notifierState.state.Version = setPendingCmd.ResultVersion
  83. }
  84. return n.sendAndMarkAsComplete(evalContext, notifierState)
  85. }
  86. func (n *notificationService) sendNotifications(evalContext *EvalContext, notifierStates notifierStateSlice) error {
  87. for _, notifierState := range notifierStates {
  88. err := n.sendNotification(evalContext, notifierState)
  89. if err != nil {
  90. n.log.Error("failed to send notification", "uid", notifierState.notifier.GetNotifierUid(), "error", err)
  91. }
  92. }
  93. return nil
  94. }
  95. func (n *notificationService) uploadImage(context *EvalContext) (err error) {
  96. uploader, err := imguploader.NewImageUploader()
  97. if err != nil {
  98. return err
  99. }
  100. renderOpts := rendering.Opts{
  101. Width: 1000,
  102. Height: 500,
  103. Timeout: time.Duration(float64(alertTimeout) * 0.9),
  104. OrgId: context.Rule.OrgId,
  105. OrgRole: m.ROLE_ADMIN,
  106. ConcurrentLimit: setting.AlertingRenderLimit,
  107. }
  108. ref, err := context.GetDashboardUID()
  109. if err != nil {
  110. return err
  111. }
  112. renderOpts.Path = fmt.Sprintf("d-solo/%s/%s?orgId=%d&panelId=%d", ref.Uid, ref.Slug, context.Rule.OrgId, context.Rule.PanelId)
  113. result, err := n.renderService.Render(context.Ctx, renderOpts)
  114. if err != nil {
  115. return err
  116. }
  117. context.ImageOnDiskPath = result.FilePath
  118. context.ImagePublicUrl, err = uploader.Upload(context.Ctx, context.ImageOnDiskPath)
  119. if err != nil {
  120. return err
  121. }
  122. if context.ImagePublicUrl != "" {
  123. n.log.Info("uploaded screenshot of alert to external image store", "url", context.ImagePublicUrl)
  124. }
  125. return nil
  126. }
  127. func (n *notificationService) getNeededNotifiers(orgId int64, notificationUids []string, evalContext *EvalContext) (notifierStateSlice, error) {
  128. query := &m.GetAlertNotificationsWithUidToSendQuery{OrgId: orgId, Uids: notificationUids}
  129. if err := bus.Dispatch(query); err != nil {
  130. return nil, err
  131. }
  132. var result notifierStateSlice
  133. for _, notification := range query.Result {
  134. not, err := InitNotifier(notification)
  135. if err != nil {
  136. n.log.Error("Could not create notifier", "notifier", notification.Uid, "error", err)
  137. continue
  138. }
  139. query := &m.GetOrCreateNotificationStateQuery{
  140. NotifierId: notification.Id,
  141. AlertId: evalContext.Rule.Id,
  142. OrgId: evalContext.Rule.OrgId,
  143. }
  144. err = bus.DispatchCtx(evalContext.Ctx, query)
  145. if err != nil {
  146. n.log.Error("Could not get notification state.", "notifier", notification.Id, "error", err)
  147. continue
  148. }
  149. if not.ShouldNotify(evalContext.Ctx, evalContext, query.Result) {
  150. result = append(result, &notifierState{
  151. notifier: not,
  152. state: query.Result,
  153. })
  154. }
  155. }
  156. return result, nil
  157. }
  158. // InitNotifier instantiate a new notifier based on the model
  159. func InitNotifier(model *m.AlertNotification) (Notifier, error) {
  160. notifierPlugin, found := notifierFactories[model.Type]
  161. if !found {
  162. return nil, errors.New("Unsupported notification type")
  163. }
  164. return notifierPlugin.Factory(model)
  165. }
  166. type NotifierFactory func(notification *m.AlertNotification) (Notifier, error)
  167. var notifierFactories = make(map[string]*NotifierPlugin)
  168. // RegisterNotifier register an notifier
  169. func RegisterNotifier(plugin *NotifierPlugin) {
  170. notifierFactories[plugin.Type] = plugin
  171. }
  172. func GetNotifiers() []*NotifierPlugin {
  173. list := make([]*NotifierPlugin, 0)
  174. for _, value := range notifierFactories {
  175. list = append(list, value)
  176. }
  177. return list
  178. }