base.go 2.1 KB

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