result_handler.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package alerting
  2. import (
  3. "time"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/log"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/services/annotations"
  8. )
  9. type ResultHandler interface {
  10. Handle(ctx *EvalContext)
  11. }
  12. type DefaultResultHandler struct {
  13. notifier Notifier
  14. log log.Logger
  15. }
  16. func NewResultHandler() *DefaultResultHandler {
  17. return &DefaultResultHandler{
  18. log: log.New("alerting.resultHandler"),
  19. notifier: NewRootNotifier(),
  20. }
  21. }
  22. func (handler *DefaultResultHandler) Handle(ctx *EvalContext) {
  23. oldState := ctx.Rule.State
  24. if ctx.Error != nil {
  25. handler.log.Error("Alert Rule Result Error", "ruleId", ctx.Rule.Id, "error", ctx.Error)
  26. ctx.Rule.State = m.AlertStatePending
  27. } else if ctx.Firing {
  28. ctx.Rule.State = m.AlertStateFiring
  29. } else {
  30. ctx.Rule.State = m.AlertStateOK
  31. }
  32. if ctx.Rule.State != oldState {
  33. handler.log.Info("New state change", "alertId", ctx.Rule.Id, "newState", ctx.Rule.State, "oldState", oldState)
  34. cmd := &m.SetAlertStateCommand{
  35. AlertId: ctx.Rule.Id,
  36. OrgId: ctx.Rule.OrgId,
  37. State: ctx.Rule.State,
  38. }
  39. if err := bus.Dispatch(cmd); err != nil {
  40. handler.log.Error("Failed to save state", "error", err)
  41. }
  42. // save annotation
  43. item := annotations.Item{
  44. OrgId: ctx.Rule.OrgId,
  45. Type: annotations.AlertType,
  46. AlertId: ctx.Rule.Id,
  47. Title: ctx.Rule.Name,
  48. Text: ctx.GetStateText(),
  49. NewState: string(ctx.Rule.State),
  50. PrevState: string(oldState),
  51. Timestamp: time.Now(),
  52. }
  53. annotationRepo := annotations.GetRepository()
  54. if err := annotationRepo.Save(&item); err != nil {
  55. handler.log.Error("Failed to save annotation for new alert state", "error", err)
  56. }
  57. handler.notifier.Notify(ctx)
  58. }
  59. }