-
Notifications
You must be signed in to change notification settings - Fork 38.8k
/
compile.go
228 lines (206 loc) · 6.96 KB
/
compile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/*
Copyright 2022 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cel
import (
"context"
"fmt"
"reflect"
"github.com/blang/semver/v4"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/google/cel-go/common/types/traits"
resourceapi "k8s.io/api/resource/v1alpha2"
"k8s.io/apimachinery/pkg/util/version"
celconfig "k8s.io/apiserver/pkg/apis/cel"
apiservercel "k8s.io/apiserver/pkg/cel"
"k8s.io/apiserver/pkg/cel/environment"
)
const (
attributesVarPrefix = "attributes."
)
var (
Compiler = newCompiler()
)
// CompilationResult represents a compiled expression.
type CompilationResult struct {
Program cel.Program
Error *apiservercel.Error
Expression string
OutputType *cel.Type
Environment *cel.Env
}
type compiler struct {
envset *environment.EnvSet
}
func newCompiler() *compiler {
return &compiler{envset: mustBuildEnv()}
}
// CompileCELExpression returns a compiled CEL expression. It evaluates to bool.
func (c compiler) CompileCELExpression(expression string, envType environment.Type) CompilationResult {
resultError := func(errorString string, errType apiservercel.ErrorType) CompilationResult {
return CompilationResult{
Error: &apiservercel.Error{
Type: errType,
Detail: errorString,
},
Expression: expression,
}
}
env, err := c.envset.Env(envType)
if err != nil {
return resultError(fmt.Sprintf("unexpected error loading CEL environment: %v", err), apiservercel.ErrorTypeInternal)
}
ast, issues := env.Compile(expression)
if issues != nil {
return resultError("compilation failed: "+issues.String(), apiservercel.ErrorTypeInvalid)
}
expectedReturnType := cel.BoolType
if ast.OutputType() != expectedReturnType {
return resultError(fmt.Sprintf("must evaluate to %v", expectedReturnType.String()), apiservercel.ErrorTypeInvalid)
}
_, err = cel.AstToCheckedExpr(ast)
if err != nil {
// should be impossible since env.Compile returned no issues
return resultError("unexpected compilation error: "+err.Error(), apiservercel.ErrorTypeInternal)
}
prog, err := env.Program(ast,
cel.InterruptCheckFrequency(celconfig.CheckFrequency),
)
if err != nil {
return resultError("program instantiation failed: "+err.Error(), apiservercel.ErrorTypeInternal)
}
return CompilationResult{
Program: prog,
Expression: expression,
OutputType: ast.OutputType(),
Environment: env,
}
}
var valueTypes = map[string]struct {
celType *cel.Type
// get returns nil if the attribute doesn't have the type, otherwise
// the value of that type.
get func(attr resourceapi.NamedResourcesAttribute) (any, error)
}{
"quantity": {apiservercel.QuantityType, func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.QuantityValue == nil {
return nil, nil
}
return apiservercel.Quantity{Quantity: attr.QuantityValue}, nil
}},
"bool": {cel.BoolType, func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.BoolValue == nil {
return nil, nil
}
return *attr.BoolValue, nil
}},
"int": {cel.IntType, func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.IntValue == nil {
return nil, nil
}
return *attr.IntValue, nil
}},
"intslice": {types.NewListType(cel.IntType), func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.IntSliceValue == nil {
return nil, nil
}
return attr.IntSliceValue.Ints, nil
}},
"string": {cel.StringType, func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.StringValue == nil {
return nil, nil
}
return *attr.StringValue, nil
}},
"stringslice": {types.NewListType(cel.StringType), func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.StringSliceValue == nil {
return nil, nil
}
return attr.StringSliceValue.Strings, nil
}},
"version": {SemVerType, func(attr resourceapi.NamedResourcesAttribute) (any, error) {
if attr.VersionValue == nil {
return nil, nil
}
v, err := semver.Parse(*attr.VersionValue)
if err != nil {
return nil, fmt.Errorf("parse semantic version: %v", err)
}
return SemVer{Version: v}, nil
}},
}
var boolType = reflect.TypeOf(true)
func (c CompilationResult) Evaluate(ctx context.Context, attributes []resourceapi.NamedResourcesAttribute) (bool, error) {
variables := make(map[string]any, len(valueTypes))
for name, valueType := range valueTypes {
m, err := buildValueMapper(c.Environment.CELTypeAdapter(), attributes, valueType.get)
if err != nil {
return false, fmt.Errorf("extract attributes with type %s: %v", name, err)
}
variables[attributesVarPrefix+name] = m
}
result, _, err := c.Program.ContextEval(ctx, variables)
if err != nil {
return false, err
}
resultAny, err := result.ConvertToNative(boolType)
if err != nil {
return false, fmt.Errorf("CEL result of type %s could not be converted to bool: %w", result.Type().TypeName(), err)
}
resultBool, ok := resultAny.(bool)
if !ok {
return false, fmt.Errorf("CEL native result value should have been a bool, got instead: %T", resultAny)
}
return resultBool, nil
}
func mustBuildEnv() *environment.EnvSet {
envset := environment.MustBaseEnvSet(environment.DefaultCompatibilityVersion())
versioned := []environment.VersionedOptions{
{
IntroducedVersion: version.MajorMinor(1, 30),
EnvOptions: append(buildVersionedAttributes(),
SemVerLib(),
),
},
}
envset, err := envset.Extend(versioned...)
if err != nil {
panic(fmt.Errorf("internal error building CEL environment: %w", err))
}
return envset
}
func buildVersionedAttributes() []cel.EnvOption {
options := make([]cel.EnvOption, 0, len(valueTypes))
for name, valueType := range valueTypes {
options = append(options, cel.Variable(attributesVarPrefix+name, types.NewMapType(cel.StringType, valueType.celType)))
}
return options
}
func buildValueMapper(adapter types.Adapter, attributes []resourceapi.NamedResourcesAttribute, get func(resourceapi.NamedResourcesAttribute) (any, error)) (traits.Mapper, error) {
// This implementation constructs a map and then let's cel handle the
// lookup and iteration. This is done for the sake of simplicity.
// Whether it's faster than writing a custom mapper depends on
// real-world attribute sets and CEL expressions and would have to be
// benchmarked.
valueMap := make(map[string]any)
for name, attribute := range attributes {
value, err := get(attribute)
if err != nil {
return nil, fmt.Errorf("attribute %q: %v", name, err)
}
if value != nil {
valueMap[attribute.Name] = value
}
}
return types.NewStringInterfaceMap(adapter, valueMap), nil
}