base.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package notifiers
  2. import (
  3. "context"
  4. "time"
  5. "github.com/grafana/grafana/pkg/log"
  6. "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/services/alerting"
  8. )
  9. type NotifierBase struct {
  10. Name string
  11. Type string
  12. Id int64
  13. IsDeault bool
  14. UploadImage bool
  15. SendReminder bool
  16. Frequency time.Duration
  17. log log.Logger
  18. }
  19. func NewNotifierBase(model *models.AlertNotification) NotifierBase {
  20. uploadImage := true
  21. value, exist := model.Settings.CheckGet("uploadImage")
  22. if exist {
  23. uploadImage = value.MustBool()
  24. }
  25. return NotifierBase{
  26. Id: model.Id,
  27. Name: model.Name,
  28. IsDeault: model.IsDefault,
  29. Type: model.Type,
  30. UploadImage: uploadImage,
  31. SendReminder: model.SendReminder,
  32. Frequency: model.Frequency,
  33. log: log.New("alerting.notifier." + model.Name),
  34. }
  35. }
  36. func defaultShouldNotify(context *alerting.EvalContext, sendReminder bool, frequency time.Duration, notificationState *models.AlertNotificationState) bool {
  37. // Only notify on state change.
  38. if context.PrevAlertState == context.Rule.State && !sendReminder {
  39. return false
  40. }
  41. // Do not notify if interval has not elapsed
  42. lastNotify := time.Unix(notificationState.SentAt, 0)
  43. if sendReminder && !lastNotify.IsZero() && lastNotify.Add(frequency).After(time.Now()) {
  44. return false
  45. }
  46. // Do not notify if alert state if OK or pending even on repeated notify
  47. if sendReminder && (context.Rule.State == models.AlertStateOK || context.Rule.State == models.AlertStatePending) {
  48. return false
  49. }
  50. // Do not notify when we become OK for the first time.
  51. if (context.PrevAlertState == models.AlertStatePending) && (context.Rule.State == models.AlertStateOK) {
  52. return false
  53. }
  54. return true
  55. }
  56. // ShouldNotify checks this evaluation should send an alert notification
  57. func (n *NotifierBase) ShouldNotify(ctx context.Context, c *alerting.EvalContext, notiferState *models.AlertNotificationState) bool {
  58. return defaultShouldNotify(c, n.SendReminder, n.Frequency, notiferState)
  59. }
  60. func (n *NotifierBase) GetType() string {
  61. return n.Type
  62. }
  63. func (n *NotifierBase) NeedsImage() bool {
  64. return n.UploadImage
  65. }
  66. func (n *NotifierBase) GetNotifierId() int64 {
  67. return n.Id
  68. }
  69. func (n *NotifierBase) GetIsDefault() bool {
  70. return n.IsDeault
  71. }
  72. func (n *NotifierBase) GetSendReminder() bool {
  73. return n.SendReminder
  74. }
  75. func (n *NotifierBase) GetFrequency() time.Duration {
  76. return n.Frequency
  77. }