forked from dolthub/vitess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_rules.go
1022 lines (940 loc) · 25.6 KB
/
query_rules.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 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tabletserver
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
"strconv"
"github.com/youtube/vitess/go/vt/key"
"github.com/youtube/vitess/go/vt/tabletserver/planbuilder"
topodatapb "github.com/youtube/vitess/go/vt/proto/topodata"
vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)
//-----------------------------------------------
// QueryRules is used to store and execute rules for the tabletserver.
type QueryRules struct {
rules []*QueryRule
}
// NewQueryRules creates a new QueryRules.
func NewQueryRules() *QueryRules {
return &QueryRules{}
}
// Copy performs a deep copy of QueryRules.
// A nil input produces a nil output.
func (qrs *QueryRules) Copy() (newqrs *QueryRules) {
newqrs = NewQueryRules()
if qrs.rules != nil {
newqrs.rules = make([]*QueryRule, 0, len(qrs.rules))
for _, qr := range qrs.rules {
newqrs.rules = append(newqrs.rules, qr.Copy())
}
}
return newqrs
}
// Append merges the rules from another QueryRules into the receiver
func (qrs *QueryRules) Append(otherqrs *QueryRules) {
for _, qr := range otherqrs.rules {
qrs.rules = append(qrs.rules, qr)
}
}
// Add adds a QueryRule to QueryRules. It does not check
// for duplicates.
func (qrs *QueryRules) Add(qr *QueryRule) {
qrs.rules = append(qrs.rules, qr)
}
// Find finds the first occurrence of a QueryRule by matching
// the Name field. It returns nil if the rule was not found.
func (qrs *QueryRules) Find(name string) (qr *QueryRule) {
for _, qr = range qrs.rules {
if qr.Name == name {
return qr
}
}
return nil
}
// Delete deletes a QueryRule by name and returns the rule
// that was deleted. It returns nil if the rule was not found.
func (qrs *QueryRules) Delete(name string) (qr *QueryRule) {
for i, qr := range qrs.rules {
if qr.Name == name {
for j := i; j < len(qrs.rules)-i-1; j++ {
qrs.rules[j] = qrs.rules[j+1]
}
qrs.rules = qrs.rules[:len(qrs.rules)-1]
return qr
}
}
return nil
}
// UnmarshalJSON unmarshals QueryRules.
func (qrs *QueryRules) UnmarshalJSON(data []byte) (err error) {
var rulesInfo []map[string]interface{}
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
err = dec.Decode(&rulesInfo)
if err != nil {
// TODO(aaijazi): There doesn't seem to be a better error code for this, but
// we consider InternalErrors to be retriable (which this error shouldn't be).
// Ideally, we should have an error code that means "This isn't the query's
// fault, but don't retry either, as this will be a global problem".
// (true for all INTERNAL_ERRORS in query_rules)
return NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "%v", err)
}
for _, ruleInfo := range rulesInfo {
qr, err := BuildQueryRule(ruleInfo)
if err != nil {
return err
}
qrs.Add(qr)
}
return nil
}
// MarshalJSON marshals to JSON.
func (qrs *QueryRules) MarshalJSON() ([]byte, error) {
b := bytes.NewBuffer(nil)
_, _ = b.WriteString("[")
for i, rule := range qrs.rules {
if i != 0 {
_, _ = b.WriteString(",")
}
safeEncode(b, "", rule)
}
_, _ = b.WriteString("]")
return b.Bytes(), nil
}
// filterByPlan creates a new QueryRules by prefiltering on the query and planId. This allows
// us to create query plan specific QueryRules out of the original QueryRules. In the new rules,
// query, plans and tableNames predicates are empty.
func (qrs *QueryRules) filterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqrs *QueryRules) {
var newrules []*QueryRule
for _, qr := range qrs.rules {
if newrule := qr.filterByPlan(query, planid, tableName); newrule != nil {
newrules = append(newrules, newrule)
}
}
return &QueryRules{newrules}
}
func (qrs *QueryRules) getAction(ip, user string, bindVars map[string]interface{}) (action Action, desc string) {
for _, qr := range qrs.rules {
if act := qr.getAction(ip, user, bindVars); act != QRContinue {
return act, qr.Description
}
}
return QRContinue, ""
}
//-----------------------------------------------
// QueryRule represents one rule (conditions-action).
// Name is meant to uniquely identify a rule.
// Description is a human readable comment that describes the rule.
// For a QueryRule to fire, all conditions of the QueryRule
// have to match. For example, an empty QueryRule will match
// all requests.
// Every QueryRule has an associated Action. If all the conditions
// of the QueryRule are met, then the Action is triggerred.
type QueryRule struct {
Description string
Name string
// All defined conditions must match for the rule to fire (AND).
// Regexp conditions. nil conditions are ignored (TRUE).
requestIP, user, query namedRegexp
// Any matched plan will make this condition true (OR)
plans []planbuilder.PlanType
// Any matched tableNames will make this condition true (OR)
tableNames []string
// All BindVar conditions have to be fulfilled to make this true (AND)
bindVarConds []BindVarCond
// Action to be performed on trigger
act Action
}
type namedRegexp struct {
name string
*regexp.Regexp
}
// MarshalJSON marshals to JSON.
func (nr namedRegexp) MarshalJSON() ([]byte, error) {
return json.Marshal(nr.name)
}
// NewQueryRule creates a new QueryRule.
func NewQueryRule(description, name string, act Action) (qr *QueryRule) {
// We ignore act because there's only one action right now
return &QueryRule{Description: description, Name: name, act: act}
}
// Copy performs a deep copy of a QueryRule.
func (qr *QueryRule) Copy() (newqr *QueryRule) {
newqr = &QueryRule{
Description: qr.Description,
Name: qr.Name,
requestIP: qr.requestIP,
user: qr.user,
query: qr.query,
act: qr.act,
}
if qr.plans != nil {
newqr.plans = make([]planbuilder.PlanType, len(qr.plans))
copy(newqr.plans, qr.plans)
}
if qr.tableNames != nil {
newqr.tableNames = make([]string, len(qr.tableNames))
copy(newqr.tableNames, qr.tableNames)
}
if qr.bindVarConds != nil {
newqr.bindVarConds = make([]BindVarCond, len(qr.bindVarConds))
copy(newqr.bindVarConds, qr.bindVarConds)
}
return newqr
}
// MarshalJSON marshals to JSON.
func (qr *QueryRule) MarshalJSON() ([]byte, error) {
b := bytes.NewBuffer(nil)
safeEncode(b, `{"Description":`, qr.Description)
safeEncode(b, `,"Name":`, qr.Name)
if qr.requestIP.Regexp != nil {
safeEncode(b, `,"RequestIP":`, qr.requestIP)
}
if qr.user.Regexp != nil {
safeEncode(b, `,"User":`, qr.user)
}
if qr.query.Regexp != nil {
safeEncode(b, `,"Query":`, qr.query)
}
if qr.plans != nil {
safeEncode(b, `,"Plans":`, qr.plans)
}
if qr.tableNames != nil {
safeEncode(b, `,"TableNames":`, qr.tableNames)
}
if qr.bindVarConds != nil {
safeEncode(b, `,"BindVarConds":`, qr.bindVarConds)
}
if qr.act != QRContinue {
safeEncode(b, `,"Action":`, qr.act)
}
_, _ = b.WriteString("}")
return b.Bytes(), nil
}
// SetIPCond adds a regular expression condition for the client IP.
// It has to be a full match (not substring).
func (qr *QueryRule) SetIPCond(pattern string) (err error) {
qr.requestIP.name = pattern
qr.requestIP.Regexp, err = regexp.Compile(makeExact(pattern))
return err
}
// SetUserCond adds a regular expression condition for the user name
// used by the client.
func (qr *QueryRule) SetUserCond(pattern string) (err error) {
qr.user.name = pattern
qr.user.Regexp, err = regexp.Compile(makeExact(pattern))
return
}
// AddPlanCond adds to the list of plans that can be matched for
// the rule to fire.
// This function acts as an OR: Any plan id match is considered a match.
func (qr *QueryRule) AddPlanCond(planType planbuilder.PlanType) {
qr.plans = append(qr.plans, planType)
}
// AddTableCond adds to the list of tableNames that can be matched for
// the rule to fire.
// This function acts as an OR: Any tableName match is considered a match.
func (qr *QueryRule) AddTableCond(tableName string) {
qr.tableNames = append(qr.tableNames, tableName)
}
// SetQueryCond adds a regular expression condition for the query.
func (qr *QueryRule) SetQueryCond(pattern string) (err error) {
qr.query.name = pattern
qr.query.Regexp, err = regexp.Compile(makeExact(pattern))
return
}
// makeExact forces a full string match for the regex instead of substring
func makeExact(pattern string) string {
return fmt.Sprintf("^%s$", pattern)
}
// AddBindVarCond adds a bind variable restriction to the QueryRule.
// All bind var conditions have to be satisfied for the QueryRule
// to be a match.
// name represents the name (not regexp) of the bind variable.
// onAbsent specifies the value of the condition if the
// bind variable is absent.
// onMismatch specifies the value of the condition if there's
// a type mismatch on the condition.
// For inequalities, the bindvar is the left operand and the value
// in the condition is the right operand: bindVar Operator value.
// Value & operator rules
// Type Operators Bindvar
// nil "" any type
// uint64 ==, !=, <, >=, >, <= whole numbers
// int64 ==, !=, <, >=, >, <= whole numbers
// string ==, !=, <, >=, >, <=, MATCH, NOMATCH []byte, string
// KeyRange IN, NOTIN whole numbers
// whole numbers can be: int, int8, int16, int32, int64, uint64
func (qr *QueryRule) AddBindVarCond(name string, onAbsent, onMismatch bool, op Operator, value interface{}) error {
var converted bvcValue
if op == QRNoOp {
qr.bindVarConds = append(qr.bindVarConds, BindVarCond{name, onAbsent, onMismatch, op, nil})
return nil
}
switch v := value.(type) {
case uint64:
if op < QREqual || op > QRLessEqual {
goto Error
}
converted = bvcuint64(v)
case int64:
if op < QREqual || op > QRLessEqual {
goto Error
}
converted = bvcint64(v)
case string:
if op >= QREqual && op <= QRLessEqual {
converted = bvcstring(v)
} else if op >= QRMatch && op <= QRNoMatch {
var err error
// Change the value to compiled regexp
re, err := regexp.Compile(makeExact(v))
if err != nil {
return NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "processing %s: %v", v, err)
}
converted = bvcre{re}
} else {
goto Error
}
case *topodatapb.KeyRange:
if op < QRIn || op > QRNotIn {
goto Error
}
b := bvcKeyRange(*v)
converted = &b
default:
return NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "type %T not allowed as condition operand (%v)", value, value)
}
qr.bindVarConds = append(qr.bindVarConds, BindVarCond{name, onAbsent, onMismatch, op, converted})
return nil
Error:
return NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "invalid operator %s for type %T (%v)", op, value, value)
}
// filterByPlan returns a new QueryRule if the query and planid match.
// The new QueryRule will contain all the original constraints other
// than the plan and query. If the plan and query don't match the QueryRule,
// then it returns nil.
func (qr *QueryRule) filterByPlan(query string, planid planbuilder.PlanType, tableName string) (newqr *QueryRule) {
if !reMatch(qr.query.Regexp, query) {
return nil
}
if !planMatch(qr.plans, planid) {
return nil
}
if !tableMatch(qr.tableNames, tableName) {
return nil
}
newqr = qr.Copy()
newqr.query = namedRegexp{}
newqr.plans = nil
newqr.tableNames = nil
return newqr
}
func (qr *QueryRule) getAction(ip, user string, bindVars map[string]interface{}) Action {
if !reMatch(qr.requestIP.Regexp, ip) {
return QRContinue
}
if !reMatch(qr.user.Regexp, user) {
return QRContinue
}
for _, bvcond := range qr.bindVarConds {
if !bvMatch(bvcond, bindVars) {
return QRContinue
}
}
return qr.act
}
func reMatch(re *regexp.Regexp, val string) bool {
return re == nil || re.MatchString(val)
}
func planMatch(plans []planbuilder.PlanType, plan planbuilder.PlanType) bool {
if plans == nil {
return true
}
for _, p := range plans {
if p == plan {
return true
}
}
return false
}
func tableMatch(tableNames []string, tableName string) bool {
if tableNames == nil {
return true
}
for _, t := range tableNames {
if t == tableName {
return true
}
}
return false
}
func bvMatch(bvcond BindVarCond, bindVars map[string]interface{}) bool {
bv, ok := bindVars[bvcond.name]
if !ok {
return bvcond.onAbsent
}
if bvcond.op == QRNoOp {
return !bvcond.onAbsent
}
return bvcond.value.eval(bv, bvcond.op, bvcond.onMismatch)
}
//-----------------------------------------------
// Support types for QueryRule
// Action speficies the list of actions to perform
// when a QueryRule is triggered.
type Action int
// These are actions.
const (
QRContinue = Action(iota)
QRFail
QRFailRetry
)
// MarshalJSON marshals to JSON.
func (act Action) MarshalJSON() ([]byte, error) {
// If we add more actions, we'll need to use a map.
var str string
switch act {
case QRFail:
str = "FAIL"
case QRFailRetry:
str = "FAIL_RETRY"
default:
str = "INVALID"
}
return json.Marshal(str)
}
// BindVarCond represents a bind var condition.
type BindVarCond struct {
name string
onAbsent bool
onMismatch bool
op Operator
value bvcValue
}
// MarshalJSON marshals to JSON.
func (bvc BindVarCond) MarshalJSON() ([]byte, error) {
b := bytes.NewBuffer(nil)
safeEncode(b, `{"Name":`, bvc.name)
safeEncode(b, `,"OnAbsent":`, bvc.onAbsent)
if bvc.op != QRNoOp {
safeEncode(b, `,"OnMismatch":`, bvc.onMismatch)
}
safeEncode(b, `,"Operator":`, bvc.op)
if bvc.op != QRNoOp {
safeEncode(b, `,"Value":`, bvc.value)
}
_, _ = b.WriteString("}")
return b.Bytes(), nil
}
// Operator represents the list of operators.
type Operator int
// These are comparison operators.
const (
QRNoOp = Operator(iota)
QREqual
QRNotEqual
QRLessThan
QRGreaterEqual
QRGreaterThan
QRLessEqual
QRMatch
QRNoMatch
QRIn
QRNotIn
QRNumOp
)
var opmap = map[string]Operator{
"": QRNoOp,
"==": QREqual,
"!=": QRNotEqual,
"<": QRLessThan,
">=": QRGreaterEqual,
">": QRGreaterThan,
"<=": QRLessEqual,
"MATCH": QRMatch,
"NOMATCH": QRNoMatch,
"IN": QRIn,
"NOTIN": QRNotIn,
}
var opnames []string
func init() {
opnames = make([]string, QRNumOp)
for k, v := range opmap {
opnames[v] = k
}
}
// These are return statii.
const (
QROK = iota
QRMismatch
QROutOfRange
)
// MarshalJSON marshals to JSON.
func (op Operator) MarshalJSON() ([]byte, error) {
return json.Marshal(opnames[op])
}
// bvcValue defines the common interface
// for all bind var condition values
type bvcValue interface {
eval(bv interface{}, op Operator, onMismatch bool) bool
}
type bvcuint64 uint64
func (uval bvcuint64) eval(bv interface{}, op Operator, onMismatch bool) bool {
num, status := getuint64(bv)
switch op {
case QREqual:
switch status {
case QROK:
return num == uint64(uval)
case QROutOfRange:
return false
}
case QRNotEqual:
switch status {
case QROK:
return num != uint64(uval)
case QROutOfRange:
return true
}
case QRLessThan:
switch status {
case QROK:
return num < uint64(uval)
case QROutOfRange:
return true
}
case QRGreaterEqual:
switch status {
case QROK:
return num >= uint64(uval)
case QROutOfRange:
return false
}
case QRGreaterThan:
switch status {
case QROK:
return num > uint64(uval)
case QROutOfRange:
return false
}
case QRLessEqual:
switch status {
case QROK:
return num <= uint64(uval)
case QROutOfRange:
return true
}
default:
panic("unexpected:")
}
return onMismatch
}
type bvcint64 int64
func (ival bvcint64) eval(bv interface{}, op Operator, onMismatch bool) bool {
num, status := getint64(bv)
switch op {
case QREqual:
switch status {
case QROK:
return num == int64(ival)
case QROutOfRange:
return false
}
case QRNotEqual:
switch status {
case QROK:
return num != int64(ival)
case QROutOfRange:
return true
}
case QRLessThan:
switch status {
case QROK:
return num < int64(ival)
case QROutOfRange:
return false
}
case QRGreaterEqual:
switch status {
case QROK:
return num >= int64(ival)
case QROutOfRange:
return true
}
case QRGreaterThan:
switch status {
case QROK:
return num > int64(ival)
case QROutOfRange:
return true
}
case QRLessEqual:
switch status {
case QROK:
return num <= int64(ival)
case QROutOfRange:
return false
}
default:
panic("unexpected:")
}
return onMismatch
}
type bvcstring string
func (sval bvcstring) eval(bv interface{}, op Operator, onMismatch bool) bool {
str, status := getstring(bv)
if status != QROK {
return onMismatch
}
switch op {
case QREqual:
return str == string(sval)
case QRNotEqual:
return str != string(sval)
case QRLessThan:
return str < string(sval)
case QRGreaterEqual:
return str >= string(sval)
case QRGreaterThan:
return str > string(sval)
case QRLessEqual:
return str <= string(sval)
}
panic("unexpected:")
}
type bvcre struct {
re *regexp.Regexp
}
func (reval bvcre) eval(bv interface{}, op Operator, onMismatch bool) bool {
str, status := getstring(bv)
if status != QROK {
return onMismatch
}
switch op {
case QRMatch:
return reval.re.MatchString(str)
case QRNoMatch:
return !reval.re.MatchString(str)
}
panic("unexpected:")
}
type bvcKeyRange topodatapb.KeyRange
func (krval *bvcKeyRange) eval(bv interface{}, op Operator, onMismatch bool) bool {
switch op {
case QRIn:
switch num, status := getuint64(bv); status {
case QROK:
k := key.Uint64Key(num).Bytes()
return key.KeyRangeContains((*topodatapb.KeyRange)(krval), k)
case QROutOfRange:
return false
}
// Not a number. Check string.
switch str, status := getstring(bv); status {
case QROK:
return key.KeyRangeContains((*topodatapb.KeyRange)(krval), []byte(str))
}
case QRNotIn:
switch num, status := getuint64(bv); status {
case QROK:
k := key.Uint64Key(num).Bytes()
return !key.KeyRangeContains((*topodatapb.KeyRange)(krval), k)
case QROutOfRange:
return true
}
// Not a number. Check string.
switch str, status := getstring(bv); status {
case QROK:
return !key.KeyRangeContains((*topodatapb.KeyRange)(krval), []byte(str))
}
default:
panic("unexpected:")
}
return onMismatch
}
// getuint64 returns QROutOfRange for negative values
func getuint64(val interface{}) (uv uint64, status int) {
switch v := val.(type) {
case int:
if v < 0 {
return 0, QROutOfRange
}
return uint64(v), QROK
case int8:
if v < 0 {
return 0, QROutOfRange
}
return uint64(v), QROK
case int16:
if v < 0 {
return 0, QROutOfRange
}
return uint64(v), QROK
case int32:
if v < 0 {
return 0, QROutOfRange
}
return uint64(v), QROK
case int64:
if v < 0 {
return 0, QROutOfRange
}
return uint64(v), QROK
case uint64:
return v, QROK
}
return 0, QRMismatch
}
// getint64 returns QROutOfRange if a uint64 is too large
func getint64(val interface{}) (iv int64, status int) {
switch v := val.(type) {
case int:
return int64(v), QROK
case int8:
return int64(v), QROK
case int16:
return int64(v), QROK
case int32:
return int64(v), QROK
case int64:
return int64(v), QROK
case uint64:
if v > 0x7FFFFFFFFFFFFFFF { // largest int64
return 0, QROutOfRange
}
return int64(v), QROK
}
return 0, QRMismatch
}
func getstring(val interface{}) (sv string, status int) {
switch v := val.(type) {
case []byte:
return string(v), QROK
case string:
return v, QROK
}
return "", QRMismatch
}
//-----------------------------------------------
// Support functions for JSON
// MapStrOperator maps a string representation to an Operator.
func MapStrOperator(strop string) (op Operator, err error) {
if op, ok := opmap[strop]; ok {
return op, nil
}
return QRNoOp, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "invalid Operator %s", strop)
}
// BuildQueryRule builds a query rule from a ruleInfo.
func BuildQueryRule(ruleInfo map[string]interface{}) (qr *QueryRule, err error) {
qr = NewQueryRule("", "", QRFail)
for k, v := range ruleInfo {
var sv string
var lv []interface{}
var ok bool
switch k {
case "Name", "Description", "RequestIP", "User", "Query", "Action":
sv, ok = v.(string)
if !ok {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for %s", k)
}
case "Plans", "BindVarConds", "TableNames":
lv, ok = v.([]interface{})
if !ok {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want list for %s", k)
}
default:
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "unrecognized tag %s", k)
}
switch k {
case "Name":
qr.Name = sv
case "Description":
qr.Description = sv
case "RequestIP":
err = qr.SetIPCond(sv)
if err != nil {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "could not set IP condition: %v", sv)
}
case "User":
err = qr.SetUserCond(sv)
if err != nil {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "could not set User condition: %v", sv)
}
case "Query":
err = qr.SetQueryCond(sv)
if err != nil {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "could not set Query condition: %v", sv)
}
case "Plans":
for _, p := range lv {
pv, ok := p.(string)
if !ok {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for Plans")
}
pt, ok := planbuilder.PlanByName(pv)
if !ok {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "invalid plan name: %s", pv)
}
qr.AddPlanCond(pt)
}
case "TableNames":
for _, t := range lv {
tableName, ok := t.(string)
if !ok {
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for TableNames")
}
qr.AddTableCond(tableName)
}
case "BindVarConds":
for _, bvc := range lv {
name, onAbsent, onMismatch, op, value, err := buildBindVarCondition(bvc)
if err != nil {
return nil, err
}
err = qr.AddBindVarCond(name, onAbsent, onMismatch, op, value)
if err != nil {
return nil, err
}
}
case "Action":
switch sv {
case "FAIL":
qr.act = QRFail
case "FAIL_RETRY":
qr.act = QRFailRetry
default:
return nil, NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "invalid Action %s", sv)
}
}
}
return qr, nil
}
func buildBindVarCondition(bvc interface{}) (name string, onAbsent, onMismatch bool, op Operator, value interface{}, err error) {
bvcinfo, ok := bvc.(map[string]interface{})
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want json object for bind var conditions")
return
}
var v interface{}
v, ok = bvcinfo["Name"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "Name missing in BindVarConds")
return
}
name, ok = v.(string)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for Name in BindVarConds")
return
}
v, ok = bvcinfo["OnAbsent"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "OnAbsent missing in BindVarConds")
return
}
onAbsent, ok = v.(bool)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want bool for OnAbsent")
return
}
v, ok = bvcinfo["Operator"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "Operator missing in BindVarConds")
return
}
strop, ok := v.(string)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for Operator")
return
}
op, err = MapStrOperator(strop)
if err != nil {
return
}
if op == QRNoOp {
return
}
v, ok = bvcinfo["Value"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "Value missing in BindVarConds")
return
}
if op >= QREqual && op <= QRLessEqual {
switch v := v.(type) {
case json.Number:
value, err = v.Int64()
if err != nil {
// Maybe uint64
value, err = strconv.ParseUint(string(v), 10, 64)
if err != nil {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want int64/uint64: %s", string(v))
return
}
}
case string:
value = v
default:
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string or number: %v", v)
return
}
} else if op == QRMatch || op == QRNoMatch {
strvalue, ok := v.(string)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string: %v", v)
return
}
value = strvalue
} else if op == QRIn || op == QRNotIn {
kr, ok := v.(map[string]interface{})
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want keyrange for Value")
return
}
keyrange := &topodatapb.KeyRange{}
strstart, ok := kr["Start"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "Start missing in KeyRange")
return
}
start, ok := strstart.(string)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for Start")
return
}
keyrange.Start = []byte(start)
strend, ok := kr["End"]
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "End missing in KeyRange")
return
}
end, ok := strend.(string)
if !ok {
err = NewTabletError(ErrFail, vtrpcpb.ErrorCode_INTERNAL_ERROR, "want string for End")
return
}
keyrange.End = []byte(end)
value = keyrange