...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/workflow/task/evaluator.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/workflow/task

     1  // Copyright 2021 Chaos Mesh Authors.
     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  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package task
    15  
    16  import (
    17  	"github.com/go-logr/logr"
    18  	corev1 "k8s.io/api/core/v1"
    19  	"sigs.k8s.io/controller-runtime/pkg/client"
    20  
    21  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    22  	"github.com/chaos-mesh/chaos-mesh/pkg/expr"
    23  )
    24  
    25  type Evaluator struct {
    26  	logger     logr.Logger
    27  	kubeclient client.Client
    28  }
    29  
    30  func NewEvaluator(logger logr.Logger, kubeclient client.Client) *Evaluator {
    31  	return &Evaluator{logger: logger, kubeclient: kubeclient}
    32  }
    33  
    34  func (it *Evaluator) EvaluateConditionBranches(tasks []v1alpha1.ConditionalBranch, resultEnv map[string]interface{}) (branches []v1alpha1.ConditionalBranchStatus, err error) {
    35  
    36  	var result []v1alpha1.ConditionalBranchStatus
    37  	for _, task := range tasks {
    38  		it.logger.V(4).Info("evaluate for expression", "expression", task.Expression, "env", resultEnv)
    39  		var evalResult corev1.ConditionStatus
    40  		eval, err := expr.EvalBool(task.Expression, resultEnv)
    41  
    42  		if err != nil {
    43  			it.logger.Error(err, "failed to evaluate expression", "expression", task.Expression, "env", resultEnv)
    44  			evalResult = corev1.ConditionUnknown
    45  		} else {
    46  			if eval {
    47  				evalResult = corev1.ConditionTrue
    48  			} else {
    49  				evalResult = corev1.ConditionFalse
    50  			}
    51  		}
    52  
    53  		result = append(result, v1alpha1.ConditionalBranchStatus{
    54  			Target:           task.Target,
    55  			EvaluationResult: evalResult,
    56  		})
    57  	}
    58  	return result, nil
    59  }
    60