result_handler.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package alerting
  2. import (
  3. "github.com/grafana/grafana/pkg/bus"
  4. "github.com/grafana/grafana/pkg/log"
  5. m "github.com/grafana/grafana/pkg/models"
  6. )
  7. type ResultHandler interface {
  8. Handle(result *AlertResultContext)
  9. }
  10. type ResultHandlerImpl struct {
  11. notifier Notifier
  12. log log.Logger
  13. }
  14. func NewResultHandler() *ResultHandlerImpl {
  15. return &ResultHandlerImpl{
  16. log: log.New("alerting.resultHandler"),
  17. notifier: NewRootNotifier(),
  18. }
  19. }
  20. func (handler *ResultHandlerImpl) Handle(result *AlertResultContext) {
  21. var newState m.AlertStateType
  22. if result.Error != nil {
  23. handler.log.Error("Alert Rule Result Error", "ruleId", result.Rule.Id, "error", result.Error)
  24. newState = m.AlertStatePending
  25. } else if result.Firing {
  26. newState = m.AlertStateFiring
  27. } else {
  28. newState = m.AlertStateOK
  29. }
  30. if result.Rule.State != newState {
  31. handler.log.Info("New state change", "alertId", result.Rule.Id, "newState", newState, "oldState", result.Rule.State)
  32. cmd := &m.SetAlertStateCommand{
  33. AlertId: result.Rule.Id,
  34. OrgId: result.Rule.OrgId,
  35. State: newState,
  36. }
  37. if err := bus.Dispatch(cmd); err != nil {
  38. handler.log.Error("Failed to save state", "error", err)
  39. }
  40. result.Rule.State = newState
  41. handler.notifier.Notify(result)
  42. }
  43. }