...

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