This repository has been archived by the owner on Feb 9, 2022. It is now read-only.
/
func.go
406 lines (354 loc) · 9.5 KB
/
func.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Copyright 2017 Istio 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 expr
import (
"bytes"
"errors"
"fmt"
"net"
"reflect"
"strings"
"time"
multierror "github.com/hashicorp/go-multierror"
config "istio.io/api/mixer/v1/config/descriptor"
"istio.io/mixer/pkg/attribute"
)
// FuncBase defines the interface that every expression function must implement.
type FuncBase interface {
// Name uniquely identifies the function.
Name() string
// ReturnType specifies the return type of this function.
ReturnType() config.ValueType
// ArgTypes specifies the argument types in order expected by the function.
ArgTypes() []config.ValueType
}
// Func implements a function call.
// It needs to know details about Expressions and attribute bag.
type Func interface {
FuncBase
// Call performs the function call. It is guaranteed
// that call will be made with correct arity.
// may panic.
Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error)
}
// baseFunc is basetype for many funcs
type baseFunc struct {
name string
argTypes []config.ValueType
retType config.ValueType
acceptsNulls bool
}
func (f *baseFunc) Name() string { return f.name }
func (f *baseFunc) ReturnType() config.ValueType { return f.retType }
func (f *baseFunc) ArgTypes() []config.ValueType { return f.argTypes }
type eqFunc struct {
*baseFunc
invert bool
}
// newEQ returns dynamically typed equality fn.
// treats strings specially with prefix and suffix '*' matches
func newEQ() Func {
return &eqFunc{
baseFunc: &baseFunc{
name: "EQ",
retType: config.BOOL,
argTypes: []config.ValueType{config.VALUE_TYPE_UNSPECIFIED, config.VALUE_TYPE_UNSPECIFIED},
},
}
}
// newNEQ returns inverse of newEQFunc fn.
func newNEQ() Func {
return &eqFunc{
baseFunc: &baseFunc{
name: "NEQ",
retType: config.BOOL,
argTypes: []config.ValueType{config.VALUE_TYPE_UNSPECIFIED, config.VALUE_TYPE_UNSPECIFIED},
},
invert: true,
}
}
func (f *eqFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
arg0, err := args[0].Eval(attrs, fMap)
if err != nil {
return nil, err
}
arg1, err := args[1].Eval(attrs, fMap)
if err != nil {
return nil, err
}
res := f.call(arg0, arg1)
if f.invert {
return !res, nil
}
return res, nil
}
func (f *eqFunc) call(args0 interface{}, args1 interface{}) bool {
switch s0 := args0.(type) {
default:
return reflect.DeepEqual(args0, args1)
case bool, int64, float64:
return args0 == args1
case string:
var s1 string
var ok bool
if s1, ok = args1.(string); !ok {
// s0 is string and s1 is not
return false
}
return matchWithWildcards(s0, s1)
case []byte:
s1 := args1.([]byte)
if len(s0) == net.IPv4len || len(s0) == net.IPv6len {
// TODO: have the types be net.IP earlier, so this hack isn't necessary
ip1 := net.IP(s0)
ip2 := net.IP(s1)
return ip1.Equal(ip2)
}
return bytes.Equal(s0, s1)
}
}
// matchWithWildcards s0 == ns1.* --> ns1 should be a prefix of s0
// s0 == *.ns1 --> ns1 should be a suffix of s0
// TODO allow escaping *
func matchWithWildcards(s0 string, s1 string) bool {
if strings.HasSuffix(s1, "*") {
return strings.HasPrefix(s0, s1[:len(s1)-1])
}
if strings.HasPrefix(s1, "*") {
return strings.HasSuffix(s0, s1[1:])
}
return s0 == s1
}
type lAndFunc struct {
*baseFunc
}
// newLAND returns a binary logical AND fn.
func newLAND() Func {
return &lAndFunc{
&baseFunc{
name: "LAND",
retType: config.BOOL,
argTypes: []config.ValueType{config.BOOL, config.BOOL},
},
}
}
// Call returns true if both elements true
// may panic
func (f *lAndFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
return logicalAndOr(false, attrs, args, fMap)
}
func logicalAndOr(exitVal bool, attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
for _, arg := range args {
ret, err := arg.Eval(attrs, fMap)
if err != nil {
return nil, err
}
if ret == exitVal {
return exitVal, nil
}
}
return !exitVal, nil
}
type lOrFunc struct {
*baseFunc
}
// newLOR returns logical OR fn.
func newLOR() Func {
return &lOrFunc{
&baseFunc{
name: "LOR",
retType: config.BOOL,
argTypes: []config.ValueType{config.BOOL, config.BOOL},
},
}
}
// Call should return true if at least one element is true
func (f *lOrFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
return logicalAndOr(true, attrs, args, fMap)
}
// applies to non bools.
type orFunc struct {
*baseFunc
}
// newOR returns an OR fn that selects first non empty argument.
// types can be anything, but all args must be of the same type.
func newOR() Func {
return &orFunc{
baseFunc: &baseFunc{
name: "OR",
retType: config.VALUE_TYPE_UNSPECIFIED,
argTypes: []config.ValueType{config.VALUE_TYPE_UNSPECIFIED, config.VALUE_TYPE_UNSPECIFIED},
acceptsNulls: true,
},
}
}
// Call selects first non empty argument / non erroneous
// may return nil
func (f *orFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
var me *multierror.Error
for i, arg := range args {
ret, err := arg.Eval(attrs, fMap)
if err != nil {
me = multierror.Append(me, err)
if i == len(args)-1 {
return nil, fmt.Errorf("error(s) evaluating OR: %v", me.ErrorOrNil())
}
continue
}
// treating empty strings as nil, since
// go strings cannot be nil
if ret != nil && ret != "" {
return ret, nil
}
}
return nil, nil
}
// func (Value) MapIndex
type indexFunc struct {
*baseFunc
}
// newIndex returns a map accessor fn.
func newIndex() Func {
return &indexFunc{
baseFunc: &baseFunc{
name: "INDEX",
retType: config.STRING,
argTypes: []config.ValueType{config.STRING_MAP, config.STRING},
},
}
}
func (f *indexFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
mp, err := args[0].Var.Eval(attrs)
if err != nil {
return nil, err
}
key, err := args[1].Eval(attrs, fMap)
if err != nil {
return nil, err
}
return mp.(map[string]string)[key.(string)], nil
}
// func (string) []uint8
type ipFunc struct {
*baseFunc
}
// func (string, string) bool
type matchFunc struct {
*baseFunc
}
// newIP returns a fn that converts strings to IP_ADDRESSes.
func newIP() Func {
return &ipFunc{
baseFunc: &baseFunc{
name: "ip",
retType: config.IP_ADDRESS,
argTypes: []config.ValueType{config.STRING},
},
}
}
// newMatch returns a fn that checks whether a string matches a given pattern.
func newMatch() Func {
return &matchFunc{
baseFunc: &baseFunc{
name: "match",
retType: config.BOOL,
argTypes: []config.ValueType{config.STRING, config.STRING},
},
}
}
// TODO: fix when proper net.IP support is added to Mixer.
func (f *ipFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
val, err := args[0].Eval(attrs, fMap)
if err != nil {
return nil, err
}
rawIP, ok := val.(string)
if !ok {
return nil, errors.New("input to 'ip' func was not a string")
}
if ip := net.ParseIP(rawIP); ip != nil {
return []uint8(ip), nil
}
return nil, fmt.Errorf("could not convert '%s' to IP_ADDRESS", rawIP)
}
func (f *matchFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
rawStr, err := args[0].Eval(attrs, fMap)
if err != nil {
return nil, err
}
rawPattern, err := args[1].Eval(attrs, fMap)
if err != nil {
return nil, err
}
str, ok := rawStr.(string)
if !ok {
return nil, errors.New("input 'str' to 'match' func was not a string")
}
pattern, ok := rawPattern.(string)
if !ok {
return nil, errors.New("input 'pattern' to 'match' func was not a string")
}
return matchWithWildcards(str, pattern), nil
}
// func (string) []uint8
type timestampFunc struct {
*baseFunc
}
// newTIMESTAMP returns a fn that converts strings to TIMESTAMPs.
func newTIMESTAMP() Func {
return ×tampFunc{
baseFunc: &baseFunc{
name: "timestamp",
retType: config.TIMESTAMP,
argTypes: []config.ValueType{config.STRING},
},
}
}
func (f *timestampFunc) Call(attrs attribute.Bag, args []*Expression, fMap map[string]FuncBase) (interface{}, error) {
val, err := args[0].Eval(attrs, fMap)
if err != nil {
return nil, err
}
rawTime, ok := val.(string)
if !ok {
return nil, errors.New("input to 'timestamp' func was not a string")
}
layout := time.RFC3339
t, err := time.Parse(layout, rawTime)
if err != nil {
return time.Time{}, fmt.Errorf("could not convert '%s' to TIMESTAMP. expected format: '%s'", rawTime, layout)
}
return t, nil
}
func inventory() []FuncBase {
return []FuncBase{
newEQ(),
newNEQ(),
newOR(),
newLOR(),
newLAND(),
newIndex(),
newIP(),
newTIMESTAMP(),
newMatch(),
}
}
// FuncMap provides inventory of available functions.
func FuncMap() map[string]FuncBase {
m := make(map[string]FuncBase)
for _, fn := range inventory() {
m[fn.Name()] = fn
}
return m
}