notifier.go 6.3 KB

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