| 1 |
/* |
| 2 |
Copyright 2023 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package cel |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"math" |
| 22 |
|
| 23 |
"github.com/google/cel-go/cel" |
| 24 |
"github.com/google/cel-go/common/types" |
| 25 |
"github.com/google/cel-go/common/types/ref" |
| 26 |
"github.com/google/cel-go/common/types/traits" |
| 27 |
|
| 28 |
v1 "k8s.io/api/admission/v1" |
| 29 |
corev1 "k8s.io/api/core/v1" |
| 30 |
"k8s.io/apimachinery/pkg/util/version" |
| 31 |
"k8s.io/apiserver/pkg/admission" |
| 32 |
apiservercel "k8s.io/apiserver/pkg/cel" |
| 33 |
"k8s.io/apiserver/pkg/cel/environment" |
| 34 |
"k8s.io/apiserver/pkg/cel/lazy" |
| 35 |
) |
| 36 |
|
| 37 |
const VariablesTypeName = "kubernetes.variables" |
| 38 |
|
| 39 |
// CompositedCompiler compiles expressions with variable composition. |
| 40 |
type CompositedCompiler struct { |
| 41 |
Compiler |
| 42 |
ConditionCompiler |
| 43 |
MutatingCompiler |
| 44 |
|
| 45 |
CompositionEnv *CompositionEnv |
| 46 |
} |
| 47 |
|
| 48 |
// CompositedConditionEvaluator provides evaluation of a condition expression with variable composition. |
| 49 |
// The expressions must return a boolean. |
| 50 |
type CompositedConditionEvaluator struct { |
| 51 |
ConditionEvaluator |
| 52 |
|
| 53 |
compositionEnv *CompositionEnv |
| 54 |
} |
| 55 |
|
| 56 |
// CompositedEvaluator provides evaluation of a single expression with variable composition. |
| 57 |
// The types that may returned by the expression is determined at compilation time. |
| 58 |
type CompositedEvaluator struct { |
| 59 |
MutatingEvaluator |
| 60 |
|
| 61 |
compositionEnv *CompositionEnv |
| 62 |
} |
| 63 |
|
| 64 |
func NewCompositedCompiler(envSet *environment.EnvSet) (*CompositedCompiler, error) { |
| 65 |
compositionContext, err := NewCompositionEnv(VariablesTypeName, envSet) |
| 66 |
if err != nil { |
| 67 |
return nil, err |
| 68 |
} |
| 69 |
return NewCompositedCompilerFromTemplate(compositionContext), nil |
| 70 |
} |
| 71 |
|
| 72 |
func NewCompositedCompilerFromTemplate(context *CompositionEnv) *CompositedCompiler { |
| 73 |
context = &CompositionEnv{ |
| 74 |
MapType: context.MapType, |
| 75 |
EnvSet: context.EnvSet, |
| 76 |
CompiledVariables: map[string]CompilationResult{}, |
| 77 |
} |
| 78 |
compiler := NewCompiler(context.EnvSet) |
| 79 |
conditionCompiler := &conditionCompiler{compiler} |
| 80 |
mutation := &mutatingCompiler{compiler} |
| 81 |
return &CompositedCompiler{ |
| 82 |
Compiler: compiler, |
| 83 |
ConditionCompiler: conditionCompiler, |
| 84 |
MutatingCompiler: mutation, |
| 85 |
CompositionEnv: context, |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
func (c *CompositedCompiler) CompileAndStoreVariables(variables []NamedExpressionAccessor, options OptionalVariableDeclarations, mode environment.Type) { |
| 90 |
for _, v := range variables { |
| 91 |
_ = c.CompileAndStoreVariable(v, options, mode) |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
func (c *CompositedCompiler) CompileAndStoreVariable(variable NamedExpressionAccessor, options OptionalVariableDeclarations, mode environment.Type) CompilationResult { |
| 96 |
result := c.Compiler.CompileCELExpression(variable, options, mode) |
| 97 |
c.CompositionEnv.AddField(variable.GetName(), result.OutputType) |
| 98 |
c.CompositionEnv.CompiledVariables[variable.GetName()] = result |
| 99 |
return result |
| 100 |
} |
| 101 |
|
| 102 |
func (c *CompositedCompiler) CompileCondition(expressions []ExpressionAccessor, optionalDecls OptionalVariableDeclarations, envType environment.Type) ConditionEvaluator { |
| 103 |
condition := c.ConditionCompiler.CompileCondition(expressions, optionalDecls, envType) |
| 104 |
return &CompositedConditionEvaluator{ |
| 105 |
ConditionEvaluator: condition, |
| 106 |
compositionEnv: c.CompositionEnv, |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
// CompileEvaluator compiles an mutatingEvaluator for the given expression, options and environment. |
| 111 |
func (c *CompositedCompiler) CompileMutatingEvaluator(expression ExpressionAccessor, optionalDecls OptionalVariableDeclarations, envType environment.Type) MutatingEvaluator { |
| 112 |
mutation := c.MutatingCompiler.CompileMutatingEvaluator(expression, optionalDecls, envType) |
| 113 |
return &CompositedEvaluator{ |
| 114 |
MutatingEvaluator: mutation, |
| 115 |
compositionEnv: c.CompositionEnv, |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
type CompositionEnv struct { |
| 120 |
*environment.EnvSet |
| 121 |
|
| 122 |
MapType *apiservercel.DeclType |
| 123 |
CompiledVariables map[string]CompilationResult |
| 124 |
} |
| 125 |
|
| 126 |
func (c *CompositionEnv) AddField(name string, celType *cel.Type) { |
| 127 |
c.MapType.Fields[name] = apiservercel.NewDeclField(name, convertCelTypeToDeclType(celType), true, nil, nil) |
| 128 |
} |
| 129 |
|
| 130 |
func NewCompositionEnv(typeName string, baseEnvSet *environment.EnvSet) (*CompositionEnv, error) { |
| 131 |
declType := apiservercel.NewObjectType(typeName, map[string]*apiservercel.DeclField{}) |
| 132 |
envSet, err := baseEnvSet.Extend(environment.VersionedOptions{ |
| 133 |
// set to 1.0 because composition is one of the fundamental components |
| 134 |
IntroducedVersion: version.MajorMinor(1, 0), |
| 135 |
EnvOptions: []cel.EnvOption{ |
| 136 |
cel.Variable("variables", declType.CelType()), |
| 137 |
}, |
| 138 |
DeclTypes: []*apiservercel.DeclType{ |
| 139 |
declType, |
| 140 |
}, |
| 141 |
}) |
| 142 |
if err != nil { |
| 143 |
return nil, err |
| 144 |
} |
| 145 |
return &CompositionEnv{ |
| 146 |
MapType: declType, |
| 147 |
EnvSet: envSet, |
| 148 |
CompiledVariables: map[string]CompilationResult{}, |
| 149 |
}, nil |
| 150 |
} |
| 151 |
|
| 152 |
func (c *CompositionEnv) CreateContext(parent context.Context) CompositionContext { |
| 153 |
return &compositionContext{ |
| 154 |
Context: parent, |
| 155 |
compositionEnv: c, |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
type CompositionContext interface { |
| 160 |
context.Context |
| 161 |
Variables(activation any) ref.Val |
| 162 |
GetAndResetCost() int64 |
| 163 |
} |
| 164 |
|
| 165 |
type compositionContext struct { |
| 166 |
context.Context |
| 167 |
|
| 168 |
compositionEnv *CompositionEnv |
| 169 |
accumulatedCost int64 |
| 170 |
} |
| 171 |
|
| 172 |
func (c *compositionContext) Variables(activation any) ref.Val { |
| 173 |
lazyMap := lazy.NewMapValue(c.compositionEnv.MapType) |
| 174 |
for name, result := range c.compositionEnv.CompiledVariables { |
| 175 |
accessor := &variableAccessor{ |
| 176 |
name: name, |
| 177 |
result: result, |
| 178 |
activation: activation, |
| 179 |
context: c, |
| 180 |
} |
| 181 |
lazyMap.Append(name, accessor.Callback) |
| 182 |
} |
| 183 |
return lazyMap |
| 184 |
} |
| 185 |
|
| 186 |
func (f *CompositedConditionEvaluator) ForInput(ctx context.Context, versionedAttr *admission.VersionedAttributes, request *v1.AdmissionRequest, optionalVars OptionalVariableBindings, namespace *corev1.Namespace, runtimeCELCostBudget int64) ([]EvaluationResult, int64, error) { |
| 187 |
ctx = f.compositionEnv.CreateContext(ctx) |
| 188 |
return f.ConditionEvaluator.ForInput(ctx, versionedAttr, request, optionalVars, namespace, runtimeCELCostBudget) |
| 189 |
} |
| 190 |
|
| 191 |
func (c *compositionContext) reportCost(cost int64) { |
| 192 |
c.accumulatedCost += cost |
| 193 |
} |
| 194 |
|
| 195 |
func (c *compositionContext) GetAndResetCost() int64 { |
| 196 |
cost := c.accumulatedCost |
| 197 |
c.accumulatedCost = 0 |
| 198 |
return cost |
| 199 |
} |
| 200 |
|
| 201 |
type variableAccessor struct { |
| 202 |
name string |
| 203 |
result CompilationResult |
| 204 |
activation any |
| 205 |
context *compositionContext |
| 206 |
} |
| 207 |
|
| 208 |
func (a *variableAccessor) Callback(_ *lazy.MapValue) ref.Val { |
| 209 |
if a.result.Error != nil { |
| 210 |
return types.NewErr("composited variable %q fails to compile: %v", a.name, a.result.Error) |
| 211 |
} |
| 212 |
|
| 213 |
v, details, err := a.result.Program.ContextEval(a.context, a.activation) |
| 214 |
if details == nil { |
| 215 |
return types.NewErr("unable to get evaluation details of variable %q", a.name) |
| 216 |
} |
| 217 |
costPtr := details.ActualCost() |
| 218 |
if costPtr == nil { |
| 219 |
return types.NewErr("unable to calculate cost of variable %q", a.name) |
| 220 |
} |
| 221 |
cost := int64(*costPtr) |
| 222 |
if *costPtr > math.MaxInt64 { |
| 223 |
cost = math.MaxInt64 |
| 224 |
} |
| 225 |
a.context.reportCost(cost) |
| 226 |
|
| 227 |
if err != nil { |
| 228 |
return types.NewErr("composited variable %q fails to evaluate: %v", a.name, err) |
| 229 |
} |
| 230 |
return v |
| 231 |
} |
| 232 |
|
| 233 |
// convertCelTypeToDeclType converts a cel.Type to DeclType, for the use of |
| 234 |
// the TypeProvider and the cost estimator. |
| 235 |
// List and map types are created on-demand with their parameters converted recursively. |
| 236 |
func convertCelTypeToDeclType(celType *cel.Type) *apiservercel.DeclType { |
| 237 |
if celType == nil { |
| 238 |
return apiservercel.DynType |
| 239 |
} |
| 240 |
switch celType { |
| 241 |
case cel.AnyType: |
| 242 |
return apiservercel.AnyType |
| 243 |
case cel.BoolType: |
| 244 |
return apiservercel.BoolType |
| 245 |
case cel.BytesType: |
| 246 |
return apiservercel.BytesType |
| 247 |
case cel.DoubleType: |
| 248 |
return apiservercel.DoubleType |
| 249 |
case cel.DurationType: |
| 250 |
return apiservercel.DurationType |
| 251 |
case cel.IntType: |
| 252 |
return apiservercel.IntType |
| 253 |
case cel.NullType: |
| 254 |
return apiservercel.NullType |
| 255 |
case cel.StringType: |
| 256 |
return apiservercel.StringType |
| 257 |
case cel.TimestampType: |
| 258 |
return apiservercel.TimestampType |
| 259 |
case cel.UintType: |
| 260 |
return apiservercel.UintType |
| 261 |
default: |
| 262 |
if celType.HasTrait(traits.ContainerType) && celType.HasTrait(traits.IndexerType) { |
| 263 |
parameters := celType.Parameters() |
| 264 |
switch len(parameters) { |
| 265 |
case 1: |
| 266 |
elemType := convertCelTypeToDeclType(parameters[0]) |
| 267 |
return apiservercel.NewListType(elemType, -1) |
| 268 |
case 2: |
| 269 |
keyType := convertCelTypeToDeclType(parameters[0]) |
| 270 |
valueType := convertCelTypeToDeclType(parameters[1]) |
| 271 |
return apiservercel.NewMapType(keyType, valueType, -1) |
| 272 |
} |
| 273 |
} |
| 274 |
return apiservercel.DynType |
| 275 |
} |
| 276 |
} |