notifier.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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.MAlertingNotificationSent.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. metrics.MAlertingNotificationFailed.WithLabelValues(notifier.GetType()).Inc()
  54. return err
  55. }
  56. if evalContext.IsTestRun {
  57. return nil
  58. }
  59. cmd := &models.SetAlertNotificationStateToCompleteCommand{
  60. Id: notifierState.state.Id,
  61. Version: notifierState.state.Version,
  62. }
  63. return bus.DispatchCtx(evalContext.Ctx, cmd)
  64. }
  65. func (n *notificationService) sendNotification(evalContext *EvalContext, notifierState *notifierState) error {
  66. if !evalContext.IsTestRun {
  67. setPendingCmd := &models.SetAlertNotificationStateToPendingCommand{
  68. Id: notifierState.state.Id,
  69. Version: notifierState.state.Version,
  70. AlertRuleStateUpdatedVersion: evalContext.Rule.StateChanges,
  71. }
  72. err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd)
  73. if err == models.ErrAlertNotificationStateVersionConflict {
  74. return nil
  75. }
  76. if err != nil {
  77. return err
  78. }
  79. // We need to update state version to be able to log
  80. // unexpected version conflicts when marking notifications as ok
  81. notifierState.state.Version = setPendingCmd.ResultVersion
  82. }
  83. return n.sendAndMarkAsComplete(evalContext, notifierState)
  84. }
  85. func (n *notificationService) sendNotifications(evalContext *EvalContext, notifierStates notifierStateSlice) error {
  86. for _, notifierState := range notifierStates {
  87. err := n.sendNotification(evalContext, notifierState)
  88. if err != nil {
  89. n.log.Error("failed to send notification", "uid", notifierState.notifier.GetNotifierUID(), "error", err)
  90. return 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: setting.AlertingEvaluationTimeout,
  104. OrgId: context.Rule.OrgID,
  105. OrgRole: models.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 := &models.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 := &models.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 *models.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. // NotifierFactory is a signature for creating notifiers.
  167. type NotifierFactory func(notification *models.AlertNotification) (Notifier, error)
  168. var notifierFactories = make(map[string]*NotifierPlugin)
  169. // RegisterNotifier register an notifier
  170. func RegisterNotifier(plugin *NotifierPlugin) {
  171. notifierFactories[plugin.Type] = plugin
  172. }
  173. // GetNotifiers returns a list of metadata about available notifiers.
  174. func GetNotifiers() []*NotifierPlugin {
  175. list := make([]*NotifierPlugin, 0)
  176. for _, value := range notifierFactories {
  177. list = append(list, value)
  178. }
  179. return list
  180. }