Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Improve CEL expression evaluation #253

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions api/v1alpha1/conditions_const.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,23 @@ const (
// EvaluatedCELCondition reports on whether the CEL expression is evaluated properly.
EvaluatedCELCondition clusterv1.ConditionType = "EvaluatedCEL"

// FailedToEvaluatePreConditionReason is used when some pre CEL expression have been failed to evaluate.
FailedToEvaluatePreConditionReason = "FailedToEvaluatePreCondition"
// EvaluateCELConditionFailedReason is used when some pre CEL expression have been failed to evaluate.
EvaluateCELConditionFailedReason = "EvaluateCELConditionFailed"

// FailedToEvaluatePostConditionReason is used when some post CEL expression have been failed to evaluate.
FailedToEvaluatePostConditionReason = "FailedToEvaluatePostCondition"
// CompileCELExpressionFailedReason is used when CEL expression is failed to compile.
CompileCELExpressionFailedReason = "CompileCELExpressionFailed"

// ObjectNotFoundReason is used when dynamic client cannot retrieve a object.
ObjectNotFoundReason = "ObjectNotFound"

// CRDNotExistingReason is used when CRD is not registered in the API server.
CRDNotExistingReason = "CRDNotExisting"

// WrongInputVarReason is used when CEL expression has wrong input var referenced.
WrongInputVarReason = "WrongInputVar"

// CELExpressionTypeMismatchReason is used when CEL expression returns a non boolean type.
CELExpressionTypeMismatchReason = "CELExpressionTypeMismatch"
)

const (
Expand Down
156 changes: 112 additions & 44 deletions internal/controller/clusteraddon_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -771,26 +771,31 @@ check:
// If WaitForPreCondition is mentioned.
if !reflect.DeepEqual(stage.WaitForPreCondition, clusteraddon.WaitForCondition{}) {
// Evaluate the condition.
logger.V(1).Info("starting to evaluate pre condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook)
if err := getDynamicResourceAndEvaluateCEL(ctx, in.dynamicClient, in.discoverClient, stage.WaitForPreCondition); err != nil {
if errors.Is(err, clusteraddon.ErrConditionNotMatch) {
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.FailedToEvaluatePreConditionReason,
clusterv1.ConditionSeverityInfo,
"failed to successfully evaluate pre condition: %q: %s", stage.Name, err.Error(),
)
logger.V(1).Info("starting to evaluate pre condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook, "preCondition", stage.WaitForPostCondition.Conditions)
eval, shouldReturn, err := getDynamicResourceAndEvaluateCEL(ctx, in, stage.WaitForPreCondition)
if err != nil {
in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseWaitingForPreCondition)
return false, fmt.Errorf("failed to evaluate CEL expression for pre-condition: %w", err)
}
if shouldReturn {
in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseWaitingForPreCondition)
return false, nil
}

in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseWaitingForPreCondition)
if !eval {
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.EvaluateCELConditionFailedReason,
clusterv1.ConditionSeverityInfo,
"CEL expression: %s is false", stage.WaitForPreCondition.Conditions,
)

return true, nil
}
return false, fmt.Errorf("failed to get dynamic resource and evaluate cel expression for pre condition: %w", err)
return true, nil
}

conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)
logger.V(1).Info("finished evaluating pre condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook)
logger.V(1).Info("finished evaluating pre condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook, "preCondition", stage.WaitForPreCondition.Conditions)
}

in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseApplyingOrDeleting)
Expand Down Expand Up @@ -896,24 +901,31 @@ check:
// If WaitForPostCondition is mentioned.
if !reflect.DeepEqual(stage.WaitForPostCondition, clusteraddon.WaitForCondition{}) {
// Evaluate the condition.
logger.V(1).Info("starting to evaluate post condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook)
if err := getDynamicResourceAndEvaluateCEL(ctx, in.dynamicClient, in.discoverClient, stage.WaitForPostCondition); err != nil {
if errors.Is(err, clusteraddon.ErrConditionNotMatch) {
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.FailedToEvaluatePostConditionReason,
clusterv1.ConditionSeverityInfo,
"failed to successfully evaluate post condition: %q: %s", stage.Name, err.Error(),
)
logger.V(1).Info("starting to evaluate post condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook, "postCondition", stage.WaitForPostCondition.Conditions)
eval, shouldReturn, err := getDynamicResourceAndEvaluateCEL(ctx, in, stage.WaitForPostCondition)
if err != nil {
in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseWaitingForPostCondition)
return false, fmt.Errorf("failed to evaluate CEL expression for post-condition: %w", err)
}
if shouldReturn {
in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseWaitingForPostCondition)
return false, nil
}

return true, nil
}
return false, fmt.Errorf("failed to get dynamic resource and evaluate cel expression for post condition: %w", err)
if !eval {
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.EvaluateCELConditionFailedReason,
clusterv1.ConditionSeverityInfo,
"CEL expression: %s is false", stage.WaitForPostCondition.Conditions,
)

return true, nil
}

conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)
logger.V(1).Info("finished evaluating post condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook)
logger.V(1).Info("finished evaluating post condition", "clusterStack", in.clusterAddon.Spec.ClusterStack, "name", stage.Name, "hook", in.clusterAddon.Spec.Hook, "postCondition", stage.WaitForPostCondition.Conditions)
}

in.clusterAddon.SetStagePhase(stage.Name, stage.Action, csov1alpha1.StagePhaseDone)
Expand Down Expand Up @@ -1100,31 +1112,46 @@ func helmTemplateNewClusterStack(in *templateAndApplyClusterAddonInput, name str
return newHelmTemplate, nil
}

func getDynamicResourceAndEvaluateCEL(ctx context.Context, dynamicClient *dynamic.DynamicClient, discoveryClient *discovery.DiscoveryClient, waitCondition clusteraddon.WaitForCondition) error {
func getDynamicResourceAndEvaluateCEL(ctx context.Context, in *templateAndApplyClusterAddonInput, waitCondition clusteraddon.WaitForCondition) (eval, shouldReturn bool, err error) {
evalMap := make(map[string]interface{})

env, err := cel.NewEnv()
if err != nil {
return fmt.Errorf("environment creation error: %w", err)
return false, false, fmt.Errorf("environment creation error: %w", err)
}

for _, object := range waitCondition.Objects {
env, err = env.Extend(
cel.Variable(object.Key, celtypes.NewMapType(cel.StringType, cel.AnyType)),
)
if err != nil {
return fmt.Errorf("failed to extend the current cel environment with %q: %w", object.Key, err)
return false, false, fmt.Errorf("failed to extend the current cel environment with %q: %w", object.Key, err)
}
}

ast, iss := env.Compile(waitCondition.Conditions)
if !errors.Is(iss.Err(), nil) {
return fmt.Errorf("failed to compile cel expression: %q: %w", waitCondition.Conditions, err)
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.CompileCELExpressionFailedReason,
clusterv1.ConditionSeverityError,
"failed to compile CEL expression: %s, %s", waitCondition.Conditions, iss.Err().Error(),
)

record.Warnf(
in.clusterAddon,
csov1alpha1.CompileCELExpressionFailedReason,
"failed to compile CEL expression: %s, %s", waitCondition.Conditions, iss.Err(),
)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janiskemper I would add a comment here, why you don't return an error.

return false, true, nil
}
conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)

prg, err := env.Program(ast)
if err != nil {
return fmt.Errorf("failed to generate an evaluable instance of the Ast within the environment: %w", err)
return false, false, fmt.Errorf("failed to generate an evaluable instance of the Ast within the environment: %w", err)
}

for _, object := range waitCondition.Objects {
Expand All @@ -1141,37 +1168,78 @@ func getDynamicResourceAndEvaluateCEL(ctx context.Context, dynamicClient *dynami
gvr.Version = splittedAPIVersion[0]
}

mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(discoveryClient))
mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(in.discoverClient))
mapping, err := mapper.RESTMapping(schema.GroupKind{Group: gvr.Group, Kind: gvr.Kind}, gvr.Version)
if err != nil {
return fmt.Errorf("error creating rest mapping: %w", err)
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.CRDNotExistingReason,
clusterv1.ConditionSeverityError,
"error creating rest mapping for CEL expression: %s", err.Error(),
)

return false, false, fmt.Errorf("error creating rest mapping for CEL expression: %w", err)
}
conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)

resource := dynamicClient.Resource(mapping.Resource)
resource := in.dynamicClient.Resource(mapping.Resource)

unstructuredObj, err := resource.Namespace(object.Namespace).Get(ctx, object.Name, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("failed to get object(name: %s, namespace: %s) from dynamic client: %w", object.Name, object.Namespace, err)
if !apierrors.IsNotFound(err) {
return false, false, fmt.Errorf("failed to get object(name: %s, namespace: %s) from dynamic client: %w", object.Name, object.Namespace, err)
}

conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.ObjectNotFoundReason,
clusterv1.ConditionSeverityError,
"object(%s/%s) from dynamic client for CEL expression is not found: %s", object.Namespace, object.Name, err.Error(),
)

return false, false, fmt.Errorf("failed to get object(%s/%s) from dynamic client for CEL expression: %w", object.Namespace, object.Name, err)
Comment on lines +1199 to +1202
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janiskemper is there a reason why both strings are different?

Suggestion:

err2 := fmt.fmt.Errorf("failed to get object(%s/%s) from dynamic client for CEL expression: %w", object.Namespace, object.Name, err)

conditions.MarkFalse(..., err2.Error())

return false, false, err2

Just a comment, not merge blocking.

}

evalMap[object.Key] = unstructuredObj.Object
}

out, _, err := prg.Eval(evalMap)
if err != nil {
return fmt.Errorf("failed to evaluate the Ast and environment against the input vars: %w", err)
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.WrongInputVarReason,
clusterv1.ConditionSeverityError,
"failed to evaluate the Ast and environment against the input vars for CEL expression: %s", err.Error(),
)

return false, false, fmt.Errorf("failed to evaluate the Ast and environment against the input vars for CEL expression: %w", err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@janiskemper the same err2-pattern could be used here.

}
conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)

boolVal, ok := (out.Value()).(bool)
if !ok {
return fmt.Errorf("failed to evaluate the cel expression, its value is no boolean: %w", clusteraddon.ErrConditionNotMatch)
}
conditions.MarkFalse(
in.clusterAddon,
csov1alpha1.EvaluatedCELCondition,
csov1alpha1.CELExpressionTypeMismatchReason,
clusterv1.ConditionSeverityError,
"failed to evaluate CEL expression: want boolean, got: %s", out.Value(),
)

if !boolVal {
return fmt.Errorf("failed to evaluate the cel expression, please check again: %w", clusteraddon.ErrConditionNotMatch)
record.Warnf(
in.clusterAddon,
csov1alpha1.CELExpressionTypeMismatchReason,
"failed to evaluate CEL expression: want boolean, got: %s", out.Value(),
)

return false, true, nil
}
conditions.Delete(in.clusterAddon, csov1alpha1.EvaluatedCELCondition)

return nil
return boolVal, false, nil
}

func buildTemplateFromClusterAddonValues(ctx context.Context, addonValuePath string, cluster *clusterv1.Cluster, c client.Client) ([]byte, error) {
Expand Down
4 changes: 0 additions & 4 deletions pkg/clusteraddon/clusteraddon.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ limitations under the License.
package clusteraddon

import (
"errors"
"fmt"
"os"
"path/filepath"
Expand All @@ -29,9 +28,6 @@ import (
// Action is the type for helm chart action (e.g. - apply, delete).
type Action string

// ErrConditionNotMatch is used when the specified CEL expression doesn't match in the stage.
var ErrConditionNotMatch = errors.New("condition don't match")

var (
// Apply applies a helm chart.
Apply = Action("apply")
Expand Down
Loading