result_handler.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package alerting
  2. import (
  3. "time"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/components/simplejson"
  6. "github.com/grafana/grafana/pkg/log"
  7. m "github.com/grafana/grafana/pkg/models"
  8. )
  9. type ResultHandler interface {
  10. Handle(result *AlertResult)
  11. }
  12. type ResultHandlerImpl struct {
  13. notifier Notifier
  14. log log.Logger
  15. }
  16. func NewResultHandler() *ResultHandlerImpl {
  17. return &ResultHandlerImpl{
  18. log: log.New("alerting.responseHandler"),
  19. notifier: NewNotifier(),
  20. }
  21. }
  22. func (handler *ResultHandlerImpl) Handle(result *AlertResult) {
  23. if handler.shouldUpdateState(result) {
  24. cmd := &m.UpdateAlertStateCommand{
  25. AlertId: result.AlertJob.Rule.Id,
  26. NewState: result.State,
  27. Info: result.Description,
  28. OrgId: result.AlertJob.Rule.OrgId,
  29. TriggeredAlerts: simplejson.NewFromAny(result.TriggeredAlerts),
  30. }
  31. if err := bus.Dispatch(cmd); err != nil {
  32. handler.log.Error("Failed to save state", "error", err)
  33. }
  34. handler.log.Debug("will notify about new state", "new state", result.State)
  35. handler.notifier.Notify(result)
  36. }
  37. }
  38. func (handler *ResultHandlerImpl) shouldUpdateState(result *AlertResult) bool {
  39. query := &m.GetLastAlertStateQuery{
  40. AlertId: result.AlertJob.Rule.Id,
  41. OrgId: result.AlertJob.Rule.OrgId,
  42. }
  43. if err := bus.Dispatch(query); err != nil {
  44. log.Error2("Failed to read last alert state", "error", err)
  45. return false
  46. }
  47. if query.Result == nil {
  48. return true
  49. }
  50. lastExecution := query.Result.Created
  51. asdf := result.ExeuctionTime.Add(time.Minute * -15)
  52. olderThen15Min := lastExecution.Before(asdf)
  53. changedState := query.Result.NewState != result.State
  54. return changedState || olderThen15Min
  55. }