eval_handler.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package alerting
  15. import (
  16. "strconv"
  17. "strings"
  18. "time"
  19. )
  20. // DefaultEvalHandler is responsible for evaluating the alert rule.
  21. type DefaultEvalHandler struct {
  22. alertJobTimeout time.Duration
  23. }
  24. // NewEvalHandler is the `DefaultEvalHandler` constructor.
  25. func NewEvalHandler() *DefaultEvalHandler {
  26. return &DefaultEvalHandler{
  27. alertJobTimeout: time.Second * 5,
  28. }
  29. }
  30. // Eval evaluated the alert rule.
  31. func (e *DefaultEvalHandler) Eval(context *EvalContext) {
  32. firing := true
  33. noDataFound := true
  34. conditionEvals := ""
  35. for i := 0; i < len(context.Rule.Conditions); i++ {
  36. condition := context.Rule.Conditions[i]
  37. cr, err := condition.Eval(context)
  38. if err != nil {
  39. context.Error = err
  40. }
  41. // break if condition could not be evaluated
  42. if context.Error != nil {
  43. break
  44. }
  45. if i == 0 {
  46. firing = cr.Firing
  47. noDataFound = cr.NoDataFound
  48. }
  49. // calculating Firing based on operator
  50. if cr.Operator == "or" {
  51. firing = firing || cr.Firing
  52. noDataFound = noDataFound || cr.NoDataFound
  53. } else {
  54. firing = firing && cr.Firing
  55. noDataFound = noDataFound && cr.NoDataFound
  56. }
  57. if i > 0 {
  58. conditionEvals = "[" + conditionEvals + " " + strings.ToUpper(cr.Operator) + " " + strconv.FormatBool(cr.Firing) + "]"
  59. } else {
  60. conditionEvals = strconv.FormatBool(firing)
  61. }
  62. context.EvalMatches = append(context.EvalMatches, cr.EvalMatches...)
  63. context.AlertOkEvalMatches = append(context.AlertOkEvalMatches, cr.AlertOkEvalMatches...)
  64. }
  65. context.ConditionEvals = conditionEvals + " = " + strconv.FormatBool(firing)
  66. context.Firing = firing
  67. context.NoDataFound = noDataFound
  68. context.EndTime = time.Now()
  69. // elapsedTime := ctx.EndTime.Sub(ctx.StartTime).Nanoseconds() / int64(time.Millisecond)
  70. // metrics.MAlertingExecutionTime.Observe(float64(elapsedTime))
  71. }