eval_handler.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package alerting
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/grafana/grafana/pkg/log"
  6. "github.com/grafana/grafana/pkg/metrics"
  7. )
  8. var (
  9. MaxRetries int = 1
  10. )
  11. type DefaultEvalHandler struct {
  12. log log.Logger
  13. alertJobTimeout time.Duration
  14. }
  15. func NewEvalHandler() *DefaultEvalHandler {
  16. return &DefaultEvalHandler{
  17. log: log.New("alerting.evalHandler"),
  18. alertJobTimeout: time.Second * 5,
  19. }
  20. }
  21. func (e *DefaultEvalHandler) Eval(context *EvalContext) {
  22. go e.eval(context)
  23. select {
  24. case <-time.After(e.alertJobTimeout):
  25. context.Error = fmt.Errorf("Timeout")
  26. context.EndTime = time.Now()
  27. e.log.Debug("Job Execution timeout", "alertId", context.Rule.Id)
  28. e.retry(context)
  29. case <-context.DoneChan:
  30. e.log.Debug("Job Execution done", "timeMs", context.GetDurationMs(), "alertId", context.Rule.Id, "firing", context.Firing)
  31. if context.Error != nil {
  32. e.retry(context)
  33. }
  34. }
  35. }
  36. func (e *DefaultEvalHandler) retry(context *EvalContext) {
  37. e.log.Debug("Retrying eval exeuction", "alertId", context.Rule.Id)
  38. context.RetryCount++
  39. if context.RetryCount > MaxRetries {
  40. context.DoneChan = make(chan bool, 1)
  41. context.CancelChan = make(chan bool, 1)
  42. e.Eval(context)
  43. }
  44. }
  45. func (e *DefaultEvalHandler) eval(context *EvalContext) {
  46. for _, condition := range context.Rule.Conditions {
  47. condition.Eval(context)
  48. // break if condition could not be evaluated
  49. if context.Error != nil {
  50. break
  51. }
  52. // break if result has not triggered yet
  53. if context.Firing == false {
  54. break
  55. }
  56. }
  57. context.EndTime = time.Now()
  58. elapsedTime := context.EndTime.Sub(context.StartTime)
  59. metrics.M_Alerting_Exeuction_Time.Update(elapsedTime)
  60. context.DoneChan <- true
  61. }