base.go 2.2 KB

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