/
functions.go
1849 lines (1776 loc) · 75.5 KB
/
functions.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2015 Comcast Cable Communications Management, LLC
*
* 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 jtl
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"fmt"
"hash/fnv"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"time"
. "github.com/Comcast/eel/util"
"github.com/Knetic/govaluate"
"github.com/robertkrimen/otto"
"golang.org/x/oauth2/clientcredentials"
)
type (
// JFunction represents built-in functions that can be used in jpath expressions.
JFunction struct {
fn func(ctx Context, doc *JDoc, params []string) interface{}
minNumParams int
maxNumParams int
}
)
// NewFunction gets function implementation by name.
func NewFunction(fn string) *JFunction {
//stats := gctx.Value(EelTotalStats).(*ServiceStats)
switch fn {
case "curl":
// hit external web service
// method - POST, GET etc.
// url - url of external service
// payload - payload to be sent to external service
// headers - headers to be sent to external service
// retries - if true, applies retry policy as specified in config.json in case of failure, no retries if false
// curl('<method>','<url>',['<payload>'],['<header-map>'],['<retries>'])
// example curl('POST', 'http://foo.com/bar/json', 'foo-{{/content/bar}}')
return &JFunction{fnCurl, 2, 5}
case "hmac":
// hmac("<hashFunc>", '<input>', '<key>')
return &JFunction{fnHmac, 3, 3}
case "oauth2":
// perform a HTTP request to a given url using 2-legged oauth2 authentication.
// url - the url
// oauth2Cred - the oauth2 credential in the custom property. It is expected to have the following 3 property
// values - ClientId, ClientSecret, TokenURL.
// method - optional. The http method. Default is GET
// payload - optional. The body payload normally for POST or PUT method
// oauth2("<url>", '<oauth2Cred>')
return &JFunction{fnOauth2, 2, 4}
case "loadfile":
// loadfile("<filename>')
return &JFunction{fnLoadFile, 1, 1}
case "uuid":
// returns UUID string
// uuid()
return &JFunction{fnUuid, 0, 0}
case "header":
// returns a value given the http request header key, or all headers if no key is given
// header('mykey')
return &JFunction{fnHeader, 0, 1}
case "param":
// returns a value given the http request query string parameter key, or all headers if no key is given
// param('mykey')
return &JFunction{fnParam, 0, 1}
case "ident":
// returns input parameter unchanged, for debugging only
// ident('foo')
return &JFunction{fnIdent, 1, 1}
case "upper":
// upper case input string, example upper('foo')
return &JFunction{fnUpper, 1, 1}
case "lower":
// lower case input string, example lower('foo')
return &JFunction{fnLower, 1, 1}
case "base64decode":
// base64 decode input string, example base64decode('foo')
return &JFunction{fnBase64Decode, 1, 1}
case "substr":
// substring by start and end index, example substr('foo', 0, 1)
return &JFunction{fnSubstr, 3, 3}
case "eval":
// evaluates simple path expression on current document and returns result
return &JFunction{fnEval, 1, 2}
case "prop":
// return property from CustomProperties section in config.json
return &JFunction{fnProp, 1, 1}
case "propexists":
// check whether or not a property exists
return &JFunction{fnPropExists, 1, 1}
case "js":
// execute arbitrary javascript and return result
return &JFunction{fnJs, 1, 100}
case "alt":
// return first non blank parameter (alternative)
return &JFunction{fnAlt, 2, 100}
case "case":
// simplification of nested ifte(equals(),'foo', ifte(equals(...),...)) cascade
// case('<path_1>','<comparison_value_1>','<return_value_1>', '<path_2>','<comparison_value_2>','<return_value_2>,...,'<default>')
return &JFunction{fnCase, 3, 100}
case "regex":
// apply regex to string value and return (first) result: regex('<string>', '<regex>')
return &JFunction{fnRegex, 2, 3}
case "match":
// apply regex to string value and return true if matches: match('<string>', '<regex>')
return &JFunction{fnMatch, 2, 2}
case "hassuffix":
// check whether or not a string has suffix: match('<string>', '<suffix>')
return &JFunction{fnHasSuffix, 2, 2}
case "and":
// boolean and: and('<bool>', '<bool>', ...)
return &JFunction{fnAnd, 1, 100}
case "or":
// boolean or: or('<bool>', '<bool>', ...)
return &JFunction{fnOr, 1, 100}
case "not":
// boolean not: not('<bool>')
return &JFunction{fnNot, 1, 1}
case "contains":
// checks if document contains another document: contains('<doc1>', ['<doc2>'])
return &JFunction{fnContains, 1, 2}
case "equals":
// checks if document is equal to another json document or if two strings are equal: equals('<doc1>',['<doc2>'])
return &JFunction{fnEquals, 1, 2}
case "join":
// merges two json documents into one, key conflicts are resolved at random
return &JFunction{fnJoin, 2, 2}
case "stringtojson":
// input is a string and output is json object
// input example:{\"timestamp\": 1602873483}
return &JFunction{fnStringToJson, 1, 1}
case "format":
// formats time string: format('<ms>',['<layout>'],['<timezone>']), example: format('1439962298000','Mon Jan 2 15:04:05 2006','PST')
return &JFunction{fnFormat, 1, 3}
case "ifte":
// if condition then this else that: ifte('<condition>','<then>',['<else>']), example: ifte('{{equals('{{/data/name}}','')}}','','by {{/data/name}}')
return &JFunction{fnIfte, 1, 3}
case "transform":
// apply transformation: transform('<name_of_transformation>', '<doc>', ['<pattern>'], ['<join>']), example: transform('my_transformation', '{{/content}}')
// - the transformation is selected by name from an optional transformation map in the handler config
// - if the document is an array, the transformation will be iteratively applied to all array elements
// - if a pattern is provided will only be applied if document is matching the pattern
// - if a join is provided it will be joined with the document before applying the transformation
return &JFunction{fnTransform, 1, 4}
case "itransform":
// apply transformation iteratively: transform('<name_of_transformation>', '<doc>', ['<pattern>'], ['<join>']), example: transform('my_transformation', '{{/content}}')
// - the transformation is selected by name from an optional transformation map in the handler config
// - if the document is an array, the transformation will be iteratively applied to all array elements
// - if a pattern is provided will only be applied if document is matching the pattern
// - if a join is provided it will be joined with the document before applying the transformation
return &JFunction{fnITransform, 1, 4}
case "etransform":
// apply external transformation and return single result (efficient shortcut for and equivalent to curl http://localhost:8080/proc)
return &JFunction{fnETransform, 1, 1}
case "ptransform":
// apply external transformation and execute publisher(s) (efficient shortcut for and equivalent to curl http://localhost:8080/proxy)
return &JFunction{fnPTransform, 1, 1}
case "true":
// returns always true, shorthand for equals('1', '1')
return &JFunction{fnTrue, 0, 0}
case "false":
// returns always false, shorthand for equals('1', '2')
return &JFunction{fnFalse, 0, 0}
case "time":
// returns current time as timestamp
return &JFunction{fnTime, 0, 0}
case "tenant":
// returns tenant of current handler
return &JFunction{fnTenant, 0, 0}
case "partner":
// returns partner of current handler
return &JFunction{fnPartner, 0, 0}
case "traceid":
// returns current trace id used for logging
return &JFunction{fnTraceId, 0, 0}
case "choose":
// chooses elements for list or array based on pattern
return &JFunction{fnChoose, 2, 2}
case "crush":
// collapse a JSON document into a flat array
return &JFunction{fnCrush, 1, 1}
case "len":
// returns length of object (string, array, map)
return &JFunction{fnLen, 1, 1}
case "string":
// returns length of object (string, array, map)
return &JFunction{fnString, 2, 2}
case "exists":
// returns true if path exists in document
return &JFunction{fnExists, 1, 2}
case "calc":
// evaluates simple arithmetic expressions in native go and returns result
return &JFunction{fnCalc, 1, 1}
case "log":
// logs parameter for debuging
return &JFunction{fnLog, 1, 1}
case "hash":
// hash a given string
return &JFunction{fnHash, 1, 1}
case "hashmod":
// hash a given string and then mod it by the given divider
return &JFunction{fnHashMod, 2, 2}
case "toTS":
//Take a timestamp string and convert it to unix ts in milliseconds
return &JFunction{fnToTS, 2, 2}
default:
//gctx.Log.Error("error_type", "func_", "op", fn, "cause", "not_implemented")
//stats.IncErrors()
return nil
}
}
var oauthClientCache map[string]*http.Client = make(map[string]*http.Client)
func fnOauth2(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 2 || len(params) > 4 {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to fnOauth2Get function"), "oauth2get", params})
return nil
}
method := "GET"
if len(params) > 2 {
method = params[2]
}
oauthCredName := params[1]
var oauth2Credentials map[string]string
cp := GetCustomProperties(ctx)
if cp != nil {
if creds, ok := cp[extractStringParam(oauthCredName)]; ok {
oauth2Credentials, ok = creds.(map[string]string)
if !ok {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "bad_oauth2_cred_format_handler", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("%s must be a properties of type map in handler", oauthCredName), "oauth2get", params})
return nil
}
}
}
props := GetConfig(ctx).CustomProperties
if props != nil {
if creds, ok := props[extractStringParam(oauthCredName)]; ok {
oauth2Credentials, ok = creds.(map[string]string)
if !ok {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "bad_oauth2_cred_format_settings", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("%s must be a properties of type map in settings", oauthCredName), "oauth2get", params})
return nil
}
}
}
if oauth2Credentials == nil {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "oauth2_cred_not_found", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("oauth2 credential %s not found", oauthCredName), "oauth2get", params})
return nil
}
clientId, ok := oauth2Credentials["ClientId"]
if !ok {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "client_id_not_found", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("ClientId not found for %s", oauthCredName), "oauth2get", params})
return nil
}
clientSecret, ok := oauth2Credentials["ClientSecret"]
if !ok {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "client_secret_not_found", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("ClientSecret not found for %s", oauthCredName), "oauth2get", params})
return nil
}
tokenUrl, ok := oauth2Credentials["TokenURL"]
if !ok {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "token_url_not_found", "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("TokenURL not found for %s", oauthCredName), "oauth2get", params})
return nil
}
scopeString, ok := oauth2Credentials["Scopes"]
var scopes []string
if ok {
scopes = strings.Split(scopeString, ",")
}
conf := &clientcredentials.Config{
ClientID: clientId,
ClientSecret: clientSecret,
TokenURL: tokenUrl,
Scopes: scopes,
}
var client *http.Client
if client, ok = oauthClientCache[oauthCredName]; !ok {
ctx.Log().Info("op", "cacheOauth2Client", "credName", oauthCredName)
client = conf.Client(context.Background())
oauthClientCache[oauthCredName] = client
}
var buf io.Reader
if len(params) > 3 {
body := params[3]
buf = bytes.NewBuffer([]byte(body))
}
req, err := http.NewRequest(method, extractStringParam(params[0]), buf)
if err != nil {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "bad_request", "params", params, "error", err)
AddError(ctx, SyntaxError{fmt.Sprintf("bad_request %s", err.Error()), "oauth2get", params})
return nil
}
resp, err := client.Do(req)
if err != nil {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "request_error", "params", params, "error", err)
AddError(ctx, SyntaxError{fmt.Sprintf("request_error %s", err.Error()), "oauth2get", params})
return nil
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "body_error", "params", params, "error", err, "status", resp.StatusCode)
AddError(ctx, SyntaxError{fmt.Sprintf("body_error %s", err.Error()), "oauth2get", params})
return nil
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "bad_status_code", "params", params, "statusCode", resp.StatusCode, "body", string(body))
AddError(ctx, SyntaxError{fmt.Sprintf("bad_status_code %d", resp.StatusCode), "oauth2get", params})
return nil
}
var ret interface{}
err = json.Unmarshal(body, &ret)
if err != nil {
ctx.Log().Error("error_type", "func_oauth2get", "op", "oauth2get", "cause", "json_unmarshal", "params", params, "error", err, "body", string(body))
AddError(ctx, SyntaxError{fmt.Sprintf("json_unmarshal_error %s", body), "oauth2get", params})
return nil
}
return ret
}
// fnRegex regular expression function returns first matching value.
func fnRegex(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) > 3 {
ctx.Log().Error("error_type", "func_regex", "op", "regex", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to regex function"), "regex", params})
return nil
}
reg, err := regexp.Compile(extractStringParam(params[1]))
if err != nil {
ctx.Log().Error("error_type", "func_regex", "op", "regex", "cause", "invalid_regex", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("invalid regex in call to regex function: %s", err.Error()), "regex", params})
return nil
}
all := false
if len(params) == 3 {
all, err = strconv.ParseBool(extractStringParam(params[2]))
if err != nil {
ctx.Log().Error("error_type", "func_regex", "op", "regex", "cause", "non_boolean_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non boolean parameters in call to regex function"), "regex", params})
return nil
}
}
if all {
items := reg.FindAllString(extractStringParam(params[0]), -1)
res := ""
for _, it := range items {
res += it
}
return res
} else {
return reg.FindString(extractStringParam(params[0]))
}
}
// fnLog write param to logs for debugging.
func fnLog(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_log", "op", "log", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to log function"), "log", params})
return nil
}
val := extractStringParam(params[0])
ctx.Log().Info("action", "logfn", "value", val)
return ""
}
// fnCalc regular expression function returns true if regex matches.
func fnCalc(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_calc", "op", "calc", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to calc function"), "calc", params})
return nil
}
functions := map[string]govaluate.ExpressionFunction{
"now": func(args ...interface{}) (interface{}, error) {
return float64(time.Now().UnixNano() / 1e6), nil
},
}
expr, err := govaluate.NewEvaluableExpressionWithFunctions(extractStringParam(params[0]), functions)
if err != nil {
ctx.Log().Error("error_type", "func_calc", "op", "calc", "cause", "invalid_expression", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("invalid expression in call to calc function: %s", err.Error()), "calc", params})
return nil
}
res, err := expr.Evaluate(nil)
if err != nil {
ctx.Log().Error("error_type", "func_calc", "op", "calc", "cause", "invalid_evaluation", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("invalid evaluation in call to calc function: %s", err.Error()), "calc", params})
return nil
}
return res
}
// fnMatch regular expression function returns true if regex matches.
func fnMatch(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 2 {
ctx.Log().Error("error_type", "func_match", "op", "match", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to match function"), "match", params})
return nil
}
reg, err := regexp.Compile(extractStringParam(params[1]))
if err != nil {
ctx.Log().Error("error_type", "func_match", "op", "match", "cause", "invalid_regex", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("invalid regex in call to match function: %s", err.Error()), "match", params})
return nil
}
return reg.MatchString(extractStringParam(params[0]))
}
// fnHasSuffix check whether a string ends with suffix.
func fnHasSuffix(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 2 {
ctx.Log().Error("error_type", "func_hassuffix", "op", "match", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to hassuffix function"), "hassuffix", params})
return nil
}
return strings.HasSuffix(extractStringParam(params[0]), extractStringParam(params[1]))
}
// fnAlt alternative function.
func fnAlt(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
ctx.Log().Error("error_type", "func_alt", "op", "alt", "cause", "now_implemented_in_parser", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("alt function now implemented in parser"), "alt", params})
return nil
}
// fnAnd boolean and function.
func fnAnd(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 1 {
ctx.Log().Error("error_type", "func_and", "op", "and", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to and function"), "and", params})
return nil
}
result := true
for i := 0; i < len(params); i++ {
b, err := strconv.ParseBool(extractStringParam(params[i]))
if err != nil {
ctx.Log().Error("error_type", "func_and", "op", "and", "cause", "non_boolean_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non boolean parameters in call to and function"), "and", params})
return nil
}
result = result && b
/*if result == false {
return result
}*/
}
return result
}
// fnOr boolean or function.
func fnOr(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 1 {
ctx.Log().Error("error_type", "func_or", "op", "or", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to or function"), "or", params})
return nil
}
result := false
for i := 0; i < len(params); i++ {
b, err := strconv.ParseBool(extractStringParam(params[i]))
if err != nil {
ctx.Log().Error("error_type", "func_or", "op", "or", "cause", "non_boolean_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non boolean parameters in call to or function"), "or", params})
return nil
}
result = result || b
/*if result == true {
return result
}*/
}
return result
}
// fnNot boolean not function.
func fnNot(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_not", "op", "not", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to not function"), "not", params})
return nil
}
result, err := strconv.ParseBool(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_not", "op", "not", "cause", "non_boolean_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non boolean parameters in call to not function"), "not", params})
return nil
}
return !result
}
// fnContains contains function.
func fnContains(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 1 || len(params) > 2 {
ctx.Log().Error("error_type", "func_contains", "op", "contains", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to contains function"), "contains", params})
return nil
}
if len(params) == 2 {
var err error
doc, err = NewJDocFromString(extractStringParam(params[1]))
if err != nil {
ctx.Log().Error("error_type", "func_contains", "op", "contains", "cause", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to contains function"), "contains", params})
return nil
}
}
containee, err := NewJDocFromString(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_contains", "op", "contains", "cause", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to contains function"), "contains", params})
return nil
}
matches, _ := doc.MatchesPattern(containee)
return matches
}
// fnChoose choose function.
func fnChoose(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 2 {
ctx.Log().Error("error_type", "func_choose", "op", "choose", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to choose function"), "choose", params})
return nil
}
mydoc, err := NewJDocFromString(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_choose", "op", "choose", "cause", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to choose function"), "choose", params})
return nil
}
pattern, err := NewJDocFromString(extractStringParam(params[1]))
if err != nil {
ctx.Log().Error("error_type", "func_choose", "op", "choose", "error", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to choose function"), "choose", params})
return nil
}
choice := doc.choose(mydoc.GetOriginalObject(), pattern.GetOriginalObject())
return choice
}
// fnCrush crush function.
func fnCrush(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_crush", "op", "crush", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to choose function"), "crush", params})
return nil
}
mydoc, err := NewJDocFromString(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_crush", "op", "crush", "cause", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to crush function"), "crush", params})
return nil
}
crush := doc.crush(mydoc.GetOriginalObject(), nil)
return crush
}
// fnEquals function. Performs deep equals on two JSON documents, otherwise a simple string comparison will be done.
func fnEquals(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 1 || len(params) > 2 {
ctx.Log().Error("error_type", "func_equals", "op", "equals", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to equals function"), "equals", params})
return nil
}
pattern, err := NewJDocFromString(extractStringParam(params[0]))
if err != nil && len(params) == 1 {
ctx.Log().Error("error_type", "func_equals", "op", "equals", "cause", "non_json_parameter", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("non json parameters in call to equals function"), "equals", params})
return nil
}
if len(params) == 2 {
doc, err = NewJDocFromString(extractStringParam(params[1]))
if err != nil {
// if not json, just do string comparison (only makes sense for the 2-param version, otherwise must be json)
return extractStringParam(params[0]) == extractStringParam(params[1])
}
}
return doc.Equals(pattern)
}
// fnIfte is an if-then-else function. The first parameter must evaluate to a boolean, the third parameter is optional.
func fnIfte(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
ctx.Log().Error("error_type", "func_ifte", "op", "ifte", "cause", "now_implemented_in_parser", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("ifte function now implemented in parser"), "ifte", params})
return nil
}
// fnCase is a simplification of a nested ifte(equals(),'foo', ifte(equals(...),...)) cascade.
// Example: case('<path_1>','<comparison_value_1>','<return_value_1>', '<path_2>','<comparison_value_2>','<return_value_2>,...,'<default>')
func fnCase(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
ctx.Log().Error("error_type", "func_case", "op", "case", "cause", "now_implemented_in_parser", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("case function now implemented in parser"), "case", params})
return nil
}
// fnJs JavaScript function. Kind of useful for everything that does not have a built-in function.
func fnJs(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 1 {
ctx.Log().Error("error_type", "func_js", "op", "js", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to js function"), "js", params})
return nil
}
vm := otto.New()
for i := 2; i < len(params)-1; i += 2 {
vm.Set(extractStringParam(params[i]), extractStringParam(params[i+1]))
}
//ctx.Log.Info("run", extractStringParam(params[0]))
value, err := vm.Run(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_js", "op", "js", "cause", "vm_error", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("js vm error: %s", err.Error()), "js", params})
return nil
}
if len(params) > 1 {
//ctx.Log.Info("get", extractStringParam(params[1]))
value, err = vm.Get(extractStringParam(params[1]))
if err != nil {
ctx.Log().Error("error_type", "func_js", "op", "js", "cause", "vm_val_error", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("js vm value error: %s", err.Error()), "js", params})
return nil
}
}
var ret interface{}
if value.IsString() {
ret, err = value.ToString()
} else if value.IsNumber() {
var i64ret int64
i64ret, err = value.ToInteger()
ret = int(i64ret)
} else if value.IsBoolean() {
ret, err = value.ToBoolean()
} else {
ret = value.String()
}
if err != nil {
ctx.Log().Error("error_type", "func_js", "op", "js", "cause", "vm_val_conv_error", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("js vm value conversion error: %s", err.Error()), "js", params})
return nil
}
return ret
}
// fnCurl provides curl-like functionality to reach out to helper web services. This function usually has grave performance consequences.
func fnCurl(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) < 2 || len(params) > 5 {
ctx.Log().Error("error_type", "func_curl", "op", "curl", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to curl function"), "curl", params})
return nil
}
var err error
retry := false
if len(params) >= 5 {
retry, err = strconv.ParseBool(extractStringParam(params[4]))
if err != nil {
stats.IncErrors()
ctx.Log().Error("error_type", "func_curl", "op", "curl", "cause", "non_boolean_parameter", "params", params, "error", err.Error())
AddError(ctx, SyntaxError{"non boolean parameter in call to curl function", "curl", params})
return nil
}
}
endpoint := extractStringParam(params[1])
// url encode query string
parsed, _ := url.Parse(endpoint)
parsed.RawQuery = parsed.Query().Encode()
endpoint = parsed.String()
if ctx.ConfigValue("debug.url") != nil {
endpoint = ctx.ConfigValue("debug.url").(string)
}
// compose http headers: at a minimum use trace header (if available), then add extra headers (if given in param #5)
hmap := make(map[string]interface{})
if len(params) >= 4 {
hdoc, err := NewJDocFromString(extractStringParam(params[3]))
if err != nil {
stats.IncErrors()
ctx.Log().Error("error_type", "func_curl", "op", "curl", "cause", "invalid_headers", "error", err.Error(), "params", params)
AddError(ctx, SyntaxError{fmt.Sprintf("invalid headers parameters in call to curl function"), "curl", params})
} else {
hmap = hdoc.GetMapValue("/")
}
}
headers := make(map[string]string, 0)
traceHeaderKey := GetConfig(ctx).HttpTransactionHeader
if traceHeaderKey != "" && ctx.Value(traceHeaderKey) != nil {
if _, ok := ctx.Value(traceHeaderKey).(string); ok {
headers[traceHeaderKey] = ctx.Value(traceHeaderKey).(string)
}
}
tenantHeaderKey := GetConfig(ctx).HttpTenantHeader
if tenantHeaderKey != "" && ctx.Value(tenantHeaderKey) != nil {
if _, ok := ctx.Value(tenantHeaderKey).(string); ok {
headers[tenantHeaderKey] = ctx.Value(tenantHeaderKey).(string)
}
}
debugHeaderKey := GetConfig(ctx).HttpDebugHeader
if debugHeaderKey != "" {
dlp := GetDebugLogParams(ctx)
if dlp != nil && dlp.IdWhiteList != nil && dlp.LogParams != nil {
wlistId := doc.ParseExpression(ctx, dlp.IdPath)
if wlistId != nil {
switch wlistId.(type) {
case string:
dlp.Lock.RLock()
defer dlp.Lock.RUnlock()
if _, ok := dlp.IdWhiteList[wlistId.(string)]; ok {
headers[GetConfig(ctx).HttpTransactionHeader] = "true"
}
}
}
}
}
if hmap != nil {
for k, v := range hmap {
if s, ok := v.(string); ok {
headers[k] = s
}
}
}
body := ""
if len(params) >= 3 {
body = extractStringParam(params[2])
}
ctx.AddLogValue("destination", "external_service")
var resp string
var status int
if retry {
resp, status, err = GetRetrier(ctx).RetryEndpoint(ctx, endpoint, body, extractStringParam(params[0]), headers, nil)
} else {
resp, status, err = HitEndpoint(ctx, endpoint, body, extractStringParam(params[0]), headers, nil)
}
if err != nil {
// this error will already be counted by hitEndpoint
ctx.Log().Error("error_type", "func_curl", "op", "curl", "cause", "curl_error", "status", strconv.Itoa(status), "error", err.Error(), "response", resp, "params", params)
AddError(ctx, NetworkError{endpoint, err.Error(), status})
return nil
}
if status < 200 || status >= 300 {
// this error will already be counted by hitEndpoint
ctx.Log().Error("error_type", "func_curl", "op", "curl", "cause", "curl_status", "status", strconv.Itoa(status), "response", resp, "params", params)
AddError(ctx, NetworkError{endpoint, "endpoint returned error", status})
return nil
}
ctx.Log().Debug("op", "curl", "resp", resp, "endpoint", endpoint, "body", body, "params", extractStringParam(params[0]), "headers", headers, "status", status)
var res interface{}
err = json.Unmarshal([]byte(resp), &res)
if err != nil {
return resp
} else {
return res
}
}
// fnHeader function to obtain http header value from incoming event by key.
func fnHeader(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) > 1 {
ctx.Log().Error("error_type", "func_header", "op", "header", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{"wrong number of parameters in call to header function", "header", params})
return ""
}
header := ctx.Value(EelRequestHeader)
if header == nil {
ctx.Log().Info("error_type", "func_header", "op", "header", "cause", "header_object_not_found")
stats.IncErrors()
AddError(ctx, RuntimeError{"header object not found in call to header function", "header", params})
return ""
}
h, ok := header.(http.Header)
if !ok {
ctx.Log().Info("error_type", "func_header", "op", "header", "cause", "header_object_not_valid")
AddError(ctx, RuntimeError{"header object not valid in call to header function", "header", params})
stats.IncErrors()
return ""
}
if len(params) == 1 && len(params[0]) > 2 {
key := extractStringParam(params[0])
return h.Get(key)
} else {
return h
}
}
// fnParam function to obtain request query string parameter value from incoming event by key.
func fnParam(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) > 1 {
ctx.Log().Error("error_type", "func_param", "op", "param", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{"wrong number of parameters in call to param function", "param", params})
return ""
}
query := ctx.Value(EelRequestQuery)
if query == nil {
ctx.Log().Info("error_type", "func_param", "op", "param", "cause", "param_object_not_found")
stats.IncErrors()
AddError(ctx, RuntimeError{"query string parameter object not found in call to param function", "param", params})
return ""
}
q, ok := query.(url.Values)
if !ok {
ctx.Log().Info("error_type", "func_param", "op", "param", "cause", "param_object_not_valid")
AddError(ctx, RuntimeError{"query string parameter object not valid in call to param function", "param", params})
stats.IncErrors()
return ""
}
if len(params) == 1 && len(params[0]) > 2 {
key := extractStringParam(params[0])
return q.Get(key)
} else {
return q
}
}
// fnUuid return a new uuid.
func fnUuid(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || params[0] != "" {
ctx.Log().Error("error_type", "func_uuid", "op", "uuid", "cause", "no_parameters_expected", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("no parameters expected in call to uuid function"), "uuid", params})
return ""
}
uuid, err := NewUUID()
if err != nil {
ctx.Log().Error("error_type", "func_uuid", "op", "uuid", "cause", "uuid_init", "params", params, "error", err.Error())
stats.IncErrors()
AddError(ctx, RuntimeError{fmt.Sprintf("uuid generator error in call to uuid function"), "uuid", params})
return ""
}
return uuid
}
// fnTraceId returns current tarce id used for logging.
func fnTraceId(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || params[0] != "" {
ctx.Log().Error("error_type", "func_traceid", "op", "traceid", "cause", "no_parameters_expected", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("no parameters expected in call to uuid function"), "traceid", params})
return ""
}
return ctx.LogValue("tx.traceId")
}
// fnTime return current time in milli-seconds.
func fnTime(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || params[0] != "" {
ctx.Log().Error("error_type", "func_time", "op", "time", "cause", "no_parameters_expected", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("no parameters expected in call to uuid function"), "time", params})
return ""
}
return time.Now().UnixNano() / 1e6
}
// fnIdent is a function that does nothing. Sometimes interesting for debugging.
func fnIdent(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_ident", "op", "ident", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to ident function"), "ident", params})
return ""
}
return extractStringParam(params[0])
}
// fnUpper function to uppercase a string.
func fnUpper(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_upper", "op", "upper", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to upper function"), "upper", params})
return ""
}
return strings.ToUpper(extractStringParam(params[0]))
}
// fnLower function to lowercase a string.
func fnLower(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_lower", "op", "lower", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to lower function"), "lower", params})
return ""
}
return strings.ToLower(extractStringParam(params[0]))
}
// fnBase64Decode function to decode a base64 string.
func fnBase64Decode(ctx Context, doc *JDoc, params []string) interface{} {
stats := ctx.Value(EelTotalStats).(*ServiceStats)
if params == nil || len(params) != 1 {
ctx.Log().Error("error_type", "func_base64decode", "op", "base64decode", "cause", "wrong_number_of_parameters", "params", params)
stats.IncErrors()
AddError(ctx, SyntaxError{fmt.Sprintf("wrong number of parameters in call to base64decode function"), "base64decode", params})
return ""
}
bs, err := base64.StdEncoding.DecodeString(extractStringParam(params[0]))
if err != nil {
ctx.Log().Error("error_type", "func_base64decode", "op", "base64decode", "cause", "error_decode", "params", params, "error", err.Error())
stats.IncErrors()