Debian Codegraph @

pkg/cel/library/quantity.go

raw
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 library
18
19 import (
20 "errors"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/common/types"
24 "github.com/google/cel-go/common/types/ref"
25
26 "k8s.io/apimachinery/pkg/api/resource"
27 apiservercel "k8s.io/apiserver/pkg/cel"
28 )
29
30 // Quantity provides a CEL function library extension of Kubernetes
31 // resource.Quantity parsing functions. See `resource.Quantity`
32 // documentation for more detailed information about the format itself:
33 // https://pkg.go.dev/k8s.io/apimachinery/pkg/api/resource#Quantity
34 //
35 // quantity
36 //
37 // Converts a string to a Quantity or results in an error if the string is not a valid Quantity. Refer
38 // to resource.Quantity documentation for information on accepted patterns.
39 //
40 // quantity(<string>) <Quantity>
41 //
42 // Examples:
43 //
44 // quantity('1.5G') // returns a Quantity
45 // quantity('200k') // returns a Quantity
46 // quantity('200K') // error
47 // quantity('Three') // error
48 // quantity('Mi') // error
49 //
50 // isQuantity
51 //
52 // Returns true if a string is a valid Quantity. isQuantity returns true if and
53 // only if quantity does not result in error.
54 //
55 // isQuantity( <string>) <bool>
56 //
57 // Examples:
58 //
59 // isQuantity('1.3G') // returns true
60 // isQuantity('1.3Gi') // returns true
61 // isQuantity('1,3G') // returns false
62 // isQuantity('10000k') // returns true
63 // isQuantity('200K') // returns false
64 // isQuantity('Three') // returns false
65 // isQuantity('Mi') // returns false
66 //
67 // Conversion to Scalars:
68 //
69 // - isInteger: returns true if and only if asInteger is safe to call without an error
70 //
71 // - asInteger: returns a representation of the current value as an int64 if
72 // possible or results in an error if conversion would result in overflow
73 // or loss of precision.
74 //
75 // - asApproximateFloat: returns a float64 representation of the quantity which may
76 // lose precision. If the value of the quantity is outside the range of a float64
77 // +Inf/-Inf will be returned.
78 //
79 // <Quantity>.isInteger() <bool>
80 // <Quantity>.asInteger() <int>
81 // <Quantity>.asApproximateFloat() <float>
82 //
83 // Examples:
84 //
85 // quantity("50000000G").isInteger() // returns true
86 // quantity("50k").isInteger() // returns true
87 // quantity("9999999999999999999999999999999999999G").asInteger() // error: cannot convert value to integer
88 // quantity("9999999999999999999999999999999999999G").isInteger() // returns false
89 // quantity("50k").asInteger() == 50000 // returns true
90 // quantity("50k").sub(20000).asApproximateFloat() == 30000 // returns true
91 //
92 // Arithmetic
93 //
94 // - sign: Returns `1` if the quantity is positive, `-1` if it is negative. `0` if it is zero
95 //
96 // - add: Returns sum of two quantities or a quantity and an integer
97 //
98 // - sub: Returns difference between two quantities or a quantity and an integer
99 //
100 // <Quantity>.sign() <int>
101 // <Quantity>.add(<quantity>) <quantity>
102 // <Quantity>.add(<integer>) <quantity>
103 // <Quantity>.sub(<quantity>) <quantity>
104 // <Quantity>.sub(<integer>) <quantity>
105 //
106 // Examples:
107 //
108 // quantity("50k").add("20k") == quantity("70k") // returns true
109 // quantity("50k").add(20) == quantity("50020") // returns true
110 // quantity("50k").sub("20k") == quantity("30k") // returns true
111 // quantity("50k").sub(20000) == quantity("30k") // returns true
112 // quantity("50k").add(20).sub(quantity("100k")).sub(-50000) == quantity("20") // returns true
113 //
114 // Comparisons
115 //
116 // - isGreaterThan: Returns true if and only if the receiver is greater than the operand
117 //
118 // - isLessThan: Returns true if and only if the receiver is less than the operand
119 //
120 // - compareTo: Compares receiver to operand and returns 0 if they are equal, 1 if the receiver is greater, or -1 if the receiver is less than the operand
121 //
122 //
123 // <Quantity>.isLessThan(<quantity>) <bool>
124 // <Quantity>.isGreaterThan(<quantity>) <bool>
125 // <Quantity>.compareTo(<quantity>) <int>
126 //
127 // Examples:
128 //
129 // quantity("200M").compareTo(quantity("0.2G")) // returns 0
130 // quantity("50M").compareTo(quantity("50Mi")) // returns -1
131 // quantity("50Mi").compareTo(quantity("50M")) // returns 1
132 // quantity("150Mi").isGreaterThan(quantity("100Mi")) // returns true
133 // quantity("50Mi").isGreaterThan(quantity("100Mi")) // returns false
134 // quantity("50M").isLessThan(quantity("100M")) // returns true
135 // quantity("100M").isLessThan(quantity("50M")) // returns false
136
137 func Quantity() cel.EnvOption {
138 return cel.Lib(quantityLib)
139 }
140
141 var quantityLib = &quantity{}
142
143 type quantity struct{}
144
145 func (*quantity) LibraryName() string {
146 return "kubernetes.quantity"
147 }
148
149 func (*quantity) Types() []*cel.Type {
150 return []*cel.Type{apiservercel.QuantityType}
151 }
152
153 func (*quantity) declarations() map[string][]cel.FunctionOpt {
154 return quantityLibraryDecls
155 }
156
157 var quantityLibraryDecls = map[string][]cel.FunctionOpt{
158 "quantity": {
159 cel.Overload("string_to_quantity", []*cel.Type{cel.StringType}, apiservercel.QuantityType, cel.UnaryBinding((stringToQuantity))),
160 },
161 "isQuantity": {
162 cel.Overload("is_quantity_string", []*cel.Type{cel.StringType}, cel.BoolType, cel.UnaryBinding(isQuantity)),
163 },
164 "sign": {
165 cel.Overload("quantity_sign", []*cel.Type{apiservercel.QuantityType}, cel.IntType, cel.UnaryBinding(quantityGetSign)),
166 },
167 "isGreaterThan": {
168 cel.MemberOverload("quantity_is_greater_than", []*cel.Type{apiservercel.QuantityType, apiservercel.QuantityType}, cel.BoolType, cel.BinaryBinding(quantityIsGreaterThan)),
169 },
170 "isLessThan": {
171 cel.MemberOverload("quantity_is_less_than", []*cel.Type{apiservercel.QuantityType, apiservercel.QuantityType}, cel.BoolType, cel.BinaryBinding(quantityIsLessThan)),
172 },
173 "compareTo": {
174 cel.MemberOverload("quantity_compare_to", []*cel.Type{apiservercel.QuantityType, apiservercel.QuantityType}, cel.IntType, cel.BinaryBinding(quantityCompareTo)),
175 },
176 "asApproximateFloat": {
177 cel.MemberOverload("quantity_get_float", []*cel.Type{apiservercel.QuantityType}, cel.DoubleType, cel.UnaryBinding(quantityGetApproximateFloat)),
178 },
179 "asInteger": {
180 cel.MemberOverload("quantity_get_int", []*cel.Type{apiservercel.QuantityType}, cel.IntType, cel.UnaryBinding(quantityGetValue)),
181 },
182 "isInteger": {
183 cel.MemberOverload("quantity_is_integer", []*cel.Type{apiservercel.QuantityType}, cel.BoolType, cel.UnaryBinding(quantityCanValue)),
184 },
185 "add": {
186 cel.MemberOverload("quantity_add", []*cel.Type{apiservercel.QuantityType, apiservercel.QuantityType}, apiservercel.QuantityType, cel.BinaryBinding(quantityAdd)),
187 cel.MemberOverload("quantity_add_int", []*cel.Type{apiservercel.QuantityType, cel.IntType}, apiservercel.QuantityType, cel.BinaryBinding(quantityAddInt)),
188 },
189 "sub": {
190 cel.MemberOverload("quantity_sub", []*cel.Type{apiservercel.QuantityType, apiservercel.QuantityType}, apiservercel.QuantityType, cel.BinaryBinding(quantitySub)),
191 cel.MemberOverload("quantity_sub_int", []*cel.Type{apiservercel.QuantityType, cel.IntType}, apiservercel.QuantityType, cel.BinaryBinding(quantitySubInt)),
192 },
193 }
194
195 func (*quantity) CompileOptions() []cel.EnvOption {
196 options := make([]cel.EnvOption, 0, len(quantityLibraryDecls))
197 for name, overloads := range quantityLibraryDecls {
198 options = append(options, cel.Function(name, overloads...))
199 }
200 return options
201 }
202
203 func (*quantity) ProgramOptions() []cel.ProgramOption {
204 return []cel.ProgramOption{}
205 }
206
207 func isQuantity(arg ref.Val) ref.Val {
208 str, ok := arg.Value().(string)
209 if !ok {
210 return types.MaybeNoSuchOverloadErr(arg)
211 }
212
213 _, err := resource.ParseQuantity(str)
214 if err != nil {
215 return types.Bool(false)
216 }
217
218 return types.Bool(true)
219 }
220
221 func stringToQuantity(arg ref.Val) ref.Val {
222 str, ok := arg.Value().(string)
223 if !ok {
224 return types.MaybeNoSuchOverloadErr(arg)
225 }
226
227 q, err := resource.ParseQuantity(str)
228 if err != nil {
229 return types.WrapErr(err)
230 }
231
232 return apiservercel.Quantity{Quantity: &q}
233 }
234
235 func quantityGetApproximateFloat(arg ref.Val) ref.Val {
236 q, ok := arg.Value().(*resource.Quantity)
237 if !ok {
238 return types.MaybeNoSuchOverloadErr(arg)
239 }
240 return types.Double(q.AsApproximateFloat64())
241 }
242
243 func quantityCanValue(arg ref.Val) ref.Val {
244 q, ok := arg.Value().(*resource.Quantity)
245 if !ok {
246 return types.MaybeNoSuchOverloadErr(arg)
247 }
248 _, success := q.AsInt64()
249 return types.Bool(success)
250 }
251
252 func quantityGetValue(arg ref.Val) ref.Val {
253 q, ok := arg.Value().(*resource.Quantity)
254 if !ok {
255 return types.MaybeNoSuchOverloadErr(arg)
256 }
257 v, success := q.AsInt64()
258 if !success {
259 return types.WrapErr(errors.New("cannot convert value to integer"))
260 }
261 return types.Int(v)
262 }
263
264 func quantityGetSign(arg ref.Val) ref.Val {
265 q, ok := arg.Value().(*resource.Quantity)
266 if !ok {
267 return types.MaybeNoSuchOverloadErr(arg)
268 }
269 return types.Int(q.Sign())
270 }
271
272 func quantityIsGreaterThan(arg ref.Val, other ref.Val) ref.Val {
273 q, ok := arg.Value().(*resource.Quantity)
274 if !ok {
275 return types.MaybeNoSuchOverloadErr(arg)
276 }
277
278 q2, ok := other.Value().(*resource.Quantity)
279 if !ok {
280 return types.MaybeNoSuchOverloadErr(arg)
281 }
282
283 return types.Bool(q.Cmp(*q2) == 1)
284 }
285
286 func quantityIsLessThan(arg ref.Val, other ref.Val) ref.Val {
287 q, ok := arg.Value().(*resource.Quantity)
288 if !ok {
289 return types.MaybeNoSuchOverloadErr(arg)
290 }
291
292 q2, ok := other.Value().(*resource.Quantity)
293 if !ok {
294 return types.MaybeNoSuchOverloadErr(arg)
295 }
296
297 return types.Bool(q.Cmp(*q2) == -1)
298 }
299
300 func quantityCompareTo(arg ref.Val, other ref.Val) ref.Val {
301 q, ok := arg.Value().(*resource.Quantity)
302 if !ok {
303 return types.MaybeNoSuchOverloadErr(arg)
304 }
305
306 q2, ok := other.Value().(*resource.Quantity)
307 if !ok {
308 return types.MaybeNoSuchOverloadErr(arg)
309 }
310
311 return types.Int(q.Cmp(*q2))
312 }
313
314 func quantityAdd(arg ref.Val, other ref.Val) ref.Val {
315 q, ok := arg.Value().(*resource.Quantity)
316 if !ok {
317 return types.MaybeNoSuchOverloadErr(arg)
318 }
319
320 q2, ok := other.Value().(*resource.Quantity)
321 if !ok {
322 return types.MaybeNoSuchOverloadErr(arg)
323 }
324
325 copy := *q
326 copy.Add(*q2)
327 return &apiservercel.Quantity{
328 Quantity: &copy,
329 }
330 }
331
332 func quantityAddInt(arg ref.Val, other ref.Val) ref.Val {
333 q, ok := arg.Value().(*resource.Quantity)
334 if !ok {
335 return types.MaybeNoSuchOverloadErr(arg)
336 }
337
338 q2, ok := other.Value().(int64)
339 if !ok {
340 return types.MaybeNoSuchOverloadErr(arg)
341 }
342
343 q2Converted := *resource.NewQuantity(q2, resource.DecimalExponent)
344
345 copy := *q
346 copy.Add(q2Converted)
347 return &apiservercel.Quantity{
348 Quantity: &copy,
349 }
350 }
351
352 func quantitySub(arg ref.Val, other ref.Val) ref.Val {
353 q, ok := arg.Value().(*resource.Quantity)
354 if !ok {
355 return types.MaybeNoSuchOverloadErr(arg)
356 }
357
358 q2, ok := other.Value().(*resource.Quantity)
359 if !ok {
360 return types.MaybeNoSuchOverloadErr(arg)
361 }
362
363 copy := *q
364 copy.Sub(*q2)
365 return &apiservercel.Quantity{
366 Quantity: &copy,
367 }
368 }
369
370 func quantitySubInt(arg ref.Val, other ref.Val) ref.Val {
371 q, ok := arg.Value().(*resource.Quantity)
372 if !ok {
373 return types.MaybeNoSuchOverloadErr(arg)
374 }
375
376 q2, ok := other.Value().(int64)
377 if !ok {
378 return types.MaybeNoSuchOverloadErr(arg)
379 }
380
381 q2Converted := *resource.NewQuantity(q2, resource.DecimalExponent)
382
383 copy := *q
384 copy.Sub(q2Converted)
385 return &apiservercel.Quantity{
386 Quantity: &copy,
387 }
388 }