eval_handler.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package alerting
  2. import (
  3. "strconv"
  4. "strings"
  5. "time"
  6. "github.com/grafana/grafana/pkg/infra/log"
  7. "github.com/grafana/grafana/pkg/infra/metrics"
  8. )
  9. type DefaultEvalHandler struct {
  10. log log.Logger
  11. alertJobTimeout time.Duration
  12. }
  13. func NewEvalHandler() *DefaultEvalHandler {
  14. return &DefaultEvalHandler{
  15. log: log.New("alerting.evalHandler"),
  16. alertJobTimeout: time.Second * 5,
  17. }
  18. }
  19. func (e *DefaultEvalHandler) Eval(context *EvalContext) {
  20. firing := true
  21. noDataFound := true
  22. conditionEvals := ""
  23. for i := 0; i < len(context.Rule.Conditions); i++ {
  24. condition := context.Rule.Conditions[i]
  25. cr, err := condition.Eval(context)
  26. if err != nil {
  27. context.Error = err
  28. }
  29. // break if condition could not be evaluated
  30. if context.Error != nil {
  31. break
  32. }
  33. if i == 0 {
  34. firing = cr.Firing
  35. noDataFound = cr.NoDataFound
  36. }
  37. // calculating Firing based on operator
  38. if cr.Operator == "or" {
  39. firing = firing || cr.Firing
  40. noDataFound = noDataFound || cr.NoDataFound
  41. } else {
  42. firing = firing && cr.Firing
  43. noDataFound = noDataFound && cr.NoDataFound
  44. }
  45. if i > 0 {
  46. conditionEvals = "[" + conditionEvals + " " + strings.ToUpper(cr.Operator) + " " + strconv.FormatBool(cr.Firing) + "]"
  47. } else {
  48. conditionEvals = strconv.FormatBool(firing)
  49. }
  50. context.EvalMatches = append(context.EvalMatches, cr.EvalMatches...)
  51. }
  52. context.ConditionEvals = conditionEvals + " = " + strconv.FormatBool(firing)
  53. context.Firing = firing
  54. context.NoDataFound = noDataFound
  55. context.EndTime = time.Now()
  56. elapsedTime := context.EndTime.Sub(context.StartTime).Nanoseconds() / int64(time.Millisecond)
  57. metrics.M_Alerting_Execution_Time.Observe(float64(elapsedTime))
  58. }