eval_handler.go 1.8 KB

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