eval_handler.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. type DefaultEvalHandler struct {
  9. log log.Logger
  10. alertJobTimeout time.Duration
  11. }
  12. func NewEvalHandler() *DefaultEvalHandler {
  13. return &DefaultEvalHandler{
  14. log: log.New("alerting.evalHandler"),
  15. alertJobTimeout: time.Second * 5,
  16. }
  17. }
  18. func (e *DefaultEvalHandler) Eval(context *EvalContext) {
  19. go e.eval(context)
  20. select {
  21. case <-time.After(e.alertJobTimeout):
  22. context.Error = fmt.Errorf("Timeout")
  23. context.EndTime = time.Now()
  24. e.log.Debug("Job Execution timeout", "alertId", context.Rule.Id)
  25. case <-context.DoneChan:
  26. e.log.Debug("Job Execution done", "timeMs", context.GetDurationMs(), "alertId", context.Rule.Id, "firing", context.Firing)
  27. }
  28. }
  29. func (e *DefaultEvalHandler) eval(context *EvalContext) {
  30. for _, condition := range context.Rule.Conditions {
  31. condition.Eval(context)
  32. // break if condition could not be evaluated
  33. if context.Error != nil {
  34. break
  35. }
  36. // break if result has not triggered yet
  37. if context.Firing == false {
  38. break
  39. }
  40. }
  41. context.EndTime = time.Now()
  42. elapsedTime := context.EndTime.Sub(context.StartTime)
  43. metrics.M_Alerting_Exeuction_Time.Update(elapsedTime)
  44. context.DoneChan <- true
  45. }