-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
vtgate.go
1190 lines (1049 loc) · 43.1 KB
/
vtgate.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 2017 Google Inc.
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 vtgate provides query routing rpc services
// for vttablets.
package vtgate
import (
"flag"
"fmt"
"math"
"net/http"
"time"
"golang.org/x/net/context"
"vitess.io/vitess/go/acl"
"vitess.io/vitess/go/flagutil"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/stats"
"vitess.io/vitess/go/tb"
"vitess.io/vitess/go/vt/discovery"
"vitess.io/vitess/go/vt/key"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/sqlannotation"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/srvtopo"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vtgate/gateway"
"vitess.io/vitess/go/vt/vtgate/vtgateservice"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vtgatepb "vitess.io/vitess/go/vt/proto/vtgate"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
)
var (
transactionMode = flag.String("transaction_mode", "MULTI", "SINGLE: disallow multi-db transactions, MULTI: allow multi-db transactions with best effort commit, TWOPC: allow multi-db transactions with 2pc commit")
normalizeQueries = flag.Bool("normalize_queries", true, "Rewrite queries with bind vars. Turn this off if the app itself sends normalized queries with bind vars.")
terseErrors = flag.Bool("vtgate-config-terse-errors", false, "prevent bind vars from escaping in returned errors")
streamBufferSize = flag.Int("stream_buffer_size", 32*1024, "the number of bytes sent from vtgate for each stream call. It's recommended to keep this value in sync with vttablet's query-server-config-stream-buffer-size.")
queryPlanCacheSize = flag.Int64("gate_query_cache_size", 10000, "gate server query cache size, maximum number of queries to be cached. vtgate analyzes every incoming query and generate a query plan, these plans are being cached in a lru cache. This config controls the capacity of the lru cache.")
legacyAutocommit = flag.Bool("legacy_autocommit", false, "DEPRECATED: set this flag to true to get the legacy behavior: all transactions will need an explicit begin, and DMLs outside transactions will return an error.")
enableForwarding = flag.Bool("enable_forwarding", false, "if specified, this process will also expose a QueryService interface that allows other vtgates to talk through this vtgate to the underlying tablets.")
l2vtgateAddrs flagutil.StringListValue
disableLocalGateway = flag.Bool("disable_local_gateway", false, "if specified, this process will not route any queries to local tablets in the local cell")
)
func getTxMode() vtgatepb.TransactionMode {
switch *transactionMode {
case "SINGLE":
log.Infof("Transaction mode: '%s'", *transactionMode)
return vtgatepb.TransactionMode_SINGLE
case "MULTI":
log.Infof("Transaction mode: '%s'", *transactionMode)
return vtgatepb.TransactionMode_MULTI
case "TWOPC":
log.Infof("Transaction mode: '%s'", *transactionMode)
return vtgatepb.TransactionMode_TWOPC
default:
log.Warningf("Unrecognized transactionMode '%s'. Continuing with default 'MULTI'", *transactionMode)
return vtgatepb.TransactionMode_MULTI
}
}
var (
rpcVTGate *VTGate
qpsByOperation *stats.Rates
qpsByKeyspace *stats.Rates
qpsByDbType *stats.Rates
vschemaCounters *stats.CountersWithSingleLabel
errorsByOperation *stats.Rates
errorsByKeyspace *stats.Rates
errorsByDbType *stats.Rates
errorsByCode *stats.Rates
// Error counters should be global so they can be set from anywhere
errorCounts *stats.CountersWithMultiLabels
warnings *stats.CountersWithSingleLabel
)
// VTGate is the rpc interface to vtgate. Only one instance
// can be created. It implements vtgateservice.VTGateService
// VTGate exposes multiple generations of interfaces. The V3
// interface is the latest one, which is capable of processing
// queries with no additional hints. V2 functions require
// the keyspace id or keyrange to be specified. V1 functions
// require shard info. V0 functions are informational that
// return topo information. Often, 'V2' or 'legacy' is used
// to refer to all legacy versions of the API (V2, V1 and V0).
type VTGate struct {
// Dependency: executor->resolver->scatterConn->txConn->gateway.
// VTGate still needs resolver and txConn to support legacy functions.
executor *Executor
resolver *Resolver
txConn *TxConn
gw gateway.Gateway
l2vtgate *L2VTGate
// stats objects.
// TODO(sougou): This needs to be cleaned up. There
// are global vars that depend on this member var.
timings *stats.MultiTimings
rowsReturned *stats.CountersWithMultiLabels
// the throttled loggers for all errors, one per API entry
logExecute *logutil.ThrottledLogger
logStreamExecute *logutil.ThrottledLogger
logExecuteShards *logutil.ThrottledLogger
logExecuteKeyspaceIds *logutil.ThrottledLogger
logExecuteKeyRanges *logutil.ThrottledLogger
logExecuteEntityIds *logutil.ThrottledLogger
logExecuteBatchShards *logutil.ThrottledLogger
logExecuteBatchKeyspaceIds *logutil.ThrottledLogger
logStreamExecuteKeyspaceIds *logutil.ThrottledLogger
logStreamExecuteKeyRanges *logutil.ThrottledLogger
logStreamExecuteShards *logutil.ThrottledLogger
logUpdateStream *logutil.ThrottledLogger
logMessageStream *logutil.ThrottledLogger
}
// RegisterVTGate defines the type of registration mechanism.
type RegisterVTGate func(vtgateservice.VTGateService)
// RegisterVTGates stores register funcs for VTGate server.
var RegisterVTGates []RegisterVTGate
// Init initializes VTGate server.
func Init(ctx context.Context, hc discovery.HealthCheck, serv srvtopo.Server, cell string, retryCount int, tabletTypesToWait []topodatapb.TabletType) *VTGate {
if rpcVTGate != nil {
log.Fatalf("VTGate already initialized")
}
// vschemaCounters needs to be initialized before planner to
// catch the initial load stats.
vschemaCounters = stats.NewCountersWithSingleLabel("VtgateVSchemaCounts", "Vtgate vschema counts", "changes")
// Build objects from low to high level.
// Start with the gateway. If we can't reach the topology service,
// we can't go on much further, so we log.Fatal out.
var gw gateway.Gateway
var l2vtgate *L2VTGate
if !*disableLocalGateway {
gw = gateway.GetCreator()(hc, serv, cell, retryCount)
gw.RegisterStats()
if err := gateway.WaitForTablets(gw, tabletTypesToWait); err != nil {
log.Fatalf("gateway.WaitForTablets failed: %v", err)
}
// l2vtgate gives access to the underlying Gateway
// from an exported QueryService interface.
if *enableForwarding {
l2vtgate = initL2VTGate(gw)
}
}
// If we have other vtgate pools to connect to, create a
// HybridGateway to perform the routing.
if len(l2vtgateAddrs) > 0 {
hgw, err := gateway.NewHybridGateway(gw, l2vtgateAddrs, retryCount)
if err != nil {
log.Fatalf("gateway.NewHybridGateway failed: %v", err)
}
hgw.RegisterStats()
gw = hgw
}
// Check we have something to do.
if gw == nil {
log.Fatalf("'-disable_local_gateway' cannot be specified if 'l2vtgate_addrs' is also empty, otherwise this vtgate has no backend")
}
tc := NewTxConn(gw, getTxMode())
// ScatterConn depends on TxConn to perform forced rollbacks.
sc := NewScatterConn("VttabletCall", tc, gw, hc)
srvResolver := srvtopo.NewResolver(serv, gw, cell)
resolver := NewResolver(srvResolver, serv, cell, sc)
rpcVTGate = &VTGate{
executor: NewExecutor(ctx, serv, cell, "VTGateExecutor", resolver, *normalizeQueries, *streamBufferSize, *queryPlanCacheSize, *legacyAutocommit),
resolver: resolver,
txConn: tc,
gw: gw,
l2vtgate: l2vtgate,
timings: stats.NewMultiTimings(
"VtgateApi",
"VtgateApi timings",
[]string{"Operation", "Keyspace", "DbType"}),
rowsReturned: stats.NewCountersWithMultiLabels(
"VtgateApiRowsReturned",
"Rows returned through the VTgate API",
[]string{"Operation", "Keyspace", "DbType"}),
logExecute: logutil.NewThrottledLogger("Execute", 5*time.Second),
logStreamExecute: logutil.NewThrottledLogger("StreamExecute", 5*time.Second),
logExecuteShards: logutil.NewThrottledLogger("ExecuteShards", 5*time.Second),
logExecuteKeyspaceIds: logutil.NewThrottledLogger("ExecuteKeyspaceIds", 5*time.Second),
logExecuteKeyRanges: logutil.NewThrottledLogger("ExecuteKeyRanges", 5*time.Second),
logExecuteEntityIds: logutil.NewThrottledLogger("ExecuteEntityIds", 5*time.Second),
logExecuteBatchShards: logutil.NewThrottledLogger("ExecuteBatchShards", 5*time.Second),
logExecuteBatchKeyspaceIds: logutil.NewThrottledLogger("ExecuteBatchKeyspaceIds", 5*time.Second),
logStreamExecuteKeyspaceIds: logutil.NewThrottledLogger("StreamExecuteKeyspaceIds", 5*time.Second),
logStreamExecuteKeyRanges: logutil.NewThrottledLogger("StreamExecuteKeyRanges", 5*time.Second),
logStreamExecuteShards: logutil.NewThrottledLogger("StreamExecuteShards", 5*time.Second),
logUpdateStream: logutil.NewThrottledLogger("UpdateStream", 5*time.Second),
logMessageStream: logutil.NewThrottledLogger("MessageStream", 5*time.Second),
}
errorCounts = stats.NewCountersWithMultiLabels("VtgateApiErrorCounts", "Vtgate API error counts per error type", []string{"Operation", "Keyspace", "DbType", "Code"})
qpsByOperation = stats.NewRates("QPSByOperation", stats.CounterForDimension(rpcVTGate.timings, "Operation"), 15, 1*time.Minute)
qpsByKeyspace = stats.NewRates("QPSByKeyspace", stats.CounterForDimension(rpcVTGate.timings, "Keyspace"), 15, 1*time.Minute)
qpsByDbType = stats.NewRates("QPSByDbType", stats.CounterForDimension(rpcVTGate.timings, "DbType"), 15*60/5, 5*time.Second)
errorsByOperation = stats.NewRates("ErrorsByOperation", stats.CounterForDimension(errorCounts, "Operation"), 15, 1*time.Minute)
errorsByKeyspace = stats.NewRates("ErrorsByKeyspace", stats.CounterForDimension(errorCounts, "Keyspace"), 15, 1*time.Minute)
errorsByDbType = stats.NewRates("ErrorsByDbType", stats.CounterForDimension(errorCounts, "DbType"), 15, 1*time.Minute)
errorsByCode = stats.NewRates("ErrorsByCode", stats.CounterForDimension(errorCounts, "Code"), 15, 1*time.Minute)
warnings = stats.NewCountersWithSingleLabel("VtGateWarnings", "Vtgate warnings", "type", "IgnoredSet")
servenv.OnRun(func() {
for _, f := range RegisterVTGates {
f(rpcVTGate)
}
})
rpcVTGate.registerDebugHealthHandler()
err := initQueryLogger(rpcVTGate)
if err != nil {
log.Fatalf("error initializing query logger: %v", err)
}
initAPI(ctx, hc)
return rpcVTGate
}
func (vtg *VTGate) registerDebugHealthHandler() {
http.HandleFunc("/debug/health", func(w http.ResponseWriter, r *http.Request) {
if err := acl.CheckAccessHTTP(r, acl.MONITORING); err != nil {
acl.SendError(w, err)
return
}
w.Header().Set("Content-Type", "text/plain")
if err := vtg.IsHealthy(); err != nil {
w.Write([]byte("not ok"))
return
}
w.Write([]byte("ok"))
})
}
// IsHealthy returns nil if server is healthy.
// Otherwise, it returns an error indicating the reason.
func (vtg *VTGate) IsHealthy() error {
return nil
}
// Gateway returns the current gateway implementation. Mostly used for tests.
func (vtg *VTGate) Gateway() gateway.Gateway {
return vtg.gw
}
// L2VTGate returns the L2VTGate object. Mostly used for tests.
func (vtg *VTGate) L2VTGate() *L2VTGate {
return vtg.l2vtgate
}
// Execute executes a non-streaming query. This is a V3 function.
func (vtg *VTGate) Execute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable) (newSession *vtgatepb.Session, qr *sqltypes.Result, err error) {
// In this context, we don't care if we can't fully parse destination
destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString)
statsKey := []string{"Execute", destKeyspace, topoproto.TabletTypeLString(destTabletType)}
defer vtg.timings.Record(statsKey, time.Now())
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
qr, err = vtg.executor.Execute(ctx, "Execute", NewSafeSession(session), sql, bindVariables)
if err == nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
return session, qr, nil
}
handleError:
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Session": session,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecute)
return session, nil, err
}
// ExecuteBatch executes a batch of queries. This is a V3 function.
func (vtg *VTGate) ExecuteBatch(ctx context.Context, session *vtgatepb.Session, sqlList []string, bindVariablesList []map[string]*querypb.BindVariable) (*vtgatepb.Session, []sqltypes.QueryResponse, error) {
// In this context, we don't care if we can't fully parse destination
destKeyspace, destTabletType, _, _ := vtg.executor.ParseDestinationTarget(session.TargetString)
statsKey := []string{"ExecuteBatch", destKeyspace, topoproto.TabletTypeLString(destTabletType)}
defer vtg.timings.Record(statsKey, time.Now())
for _, bindVariables := range bindVariablesList {
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
return session, nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
}
}
qrl := make([]sqltypes.QueryResponse, len(sqlList))
for i, sql := range sqlList {
var bv map[string]*querypb.BindVariable
if len(bindVariablesList) != 0 {
bv = bindVariablesList[i]
}
session, qrl[i].QueryResult, qrl[i].QueryError = vtg.Execute(ctx, session, sql, bv)
if qr := qrl[i].QueryResult; qr != nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
}
}
return session, qrl, nil
}
// StreamExecute executes a streaming query. This is a V3 function.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines.
func (vtg *VTGate) StreamExecute(ctx context.Context, session *vtgatepb.Session, sql string, bindVariables map[string]*querypb.BindVariable, callback func(*sqltypes.Result) error) error {
// In this context, we don't care if we can't fully parse destination
destKeyspace, destTabletType, dest, _ := vtg.executor.ParseDestinationTarget(session.TargetString)
statsKey := []string{"StreamExecute", destKeyspace, topoproto.TabletTypeLString(destTabletType)}
defer vtg.timings.Record(statsKey, time.Now())
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
// TODO: This could be simplified to have a StreamExecute that takes
// a destTarget without explicit destination.
switch dest.(type) {
case key.DestinationShard:
err = vtg.resolver.StreamExecute(
ctx,
sql,
bindVariables,
destKeyspace,
destTabletType,
dest,
session.Options,
func(reply *sqltypes.Result) error {
vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows)))
return callback(reply)
})
default:
err = vtg.executor.StreamExecute(
ctx,
"StreamExecute",
NewSafeSession(session),
sql,
bindVariables,
querypb.Target{
Keyspace: destKeyspace,
TabletType: destTabletType,
},
func(reply *sqltypes.Result) error {
vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows)))
return callback(reply)
})
}
handleError:
if err != nil {
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Session": session,
}
return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecute)
}
return nil
}
// ExecuteShards executes a non-streaming query on the specified shards.
// This is a legacy function.
func (vtg *VTGate) ExecuteShards(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, shards []string, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteShards", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var qr *sqltypes.Result
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
sql = sqlannotation.AnnotateIfDML(sql, nil)
qr, err = vtg.resolver.Execute(
ctx,
sql,
bindVariables,
keyspace,
tabletType,
key.DestinationShards(shards),
session,
notInTransaction,
options,
nil,
)
if err == nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
return qr, nil
}
handleError:
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"Shards": shards,
"TabletType": ltt,
"Session": session,
"NotInTransaction": notInTransaction,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteShards)
return nil, err
}
// ExecuteKeyspaceIds executes a non-streaming query based on the specified keyspace ids. This is a legacy function.
func (vtg *VTGate) ExecuteKeyspaceIds(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyspaceIds [][]byte, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteKeyspaceIds", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var qr *sqltypes.Result
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
sql = sqlannotation.AnnotateIfDML(sql, keyspaceIds)
if sqlparser.IsDML(sql) && len(keyspaceIds) > 1 {
err = vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "DML should not span multiple keyspace_ids")
goto handleError
}
qr, err = vtg.resolver.Execute(ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyspaceIDs(keyspaceIds), session, notInTransaction, options, nil /* LogStats */)
if err == nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
return qr, nil
}
handleError:
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"KeyspaceIds": keyspaceIds,
"TabletType": ltt,
"Session": session,
"NotInTransaction": notInTransaction,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteKeyspaceIds)
return nil, err
}
// ExecuteKeyRanges executes a non-streaming query based on the specified keyranges. This is a legacy function.
func (vtg *VTGate) ExecuteKeyRanges(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyRanges []*topodatapb.KeyRange, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteKeyRanges", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var qr *sqltypes.Result
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
sql = sqlannotation.AnnotateIfDML(sql, nil)
qr, err = vtg.resolver.Execute(ctx, sql, bindVariables, keyspace, tabletType, key.DestinationKeyRanges(keyRanges), session, notInTransaction, options, nil /* LogStats */)
if err == nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
return qr, nil
}
handleError:
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"KeyRanges": keyRanges,
"TabletType": ltt,
"Session": session,
"NotInTransaction": notInTransaction,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteKeyRanges)
return nil, err
}
// ExecuteEntityIds excutes a non-streaming query based on given KeyspaceId map. This is a legacy function.
func (vtg *VTGate) ExecuteEntityIds(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, entityColumnName string, entityKeyspaceIDs []*vtgatepb.ExecuteEntityIdsRequest_EntityId, tabletType topodatapb.TabletType, session *vtgatepb.Session, notInTransaction bool, options *querypb.ExecuteOptions) (*sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteEntityIds", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var qr *sqltypes.Result
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
sql = sqlannotation.AnnotateIfDML(sql, nil)
qr, err = vtg.resolver.ExecuteEntityIds(ctx, sql, bindVariables, keyspace, entityColumnName, entityKeyspaceIDs, tabletType, session, notInTransaction, options)
if err == nil {
vtg.rowsReturned.Add(statsKey, int64(len(qr.Rows)))
return qr, nil
}
handleError:
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"EntityColumnName": entityColumnName,
"EntityKeyspaceIDs": entityKeyspaceIDs,
"TabletType": ltt,
"Session": session,
"NotInTransaction": notInTransaction,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteEntityIds)
return nil, err
}
// ExecuteBatchShards executes a group of queries on the specified shards. This is a legacy function.
func (vtg *VTGate) ExecuteBatchShards(ctx context.Context, queries []*vtgatepb.BoundShardQuery, tabletType topodatapb.TabletType, asTransaction bool, session *vtgatepb.Session, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteBatchShards", unambiguousKeyspaceBSQ(queries), ltt}
defer vtg.timings.Record(statsKey, startTime)
var qrs []sqltypes.Result
var err error
for _, query := range queries {
if bvErr := sqltypes.ValidateBindVariables(query.Query.BindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
}
annotateBoundShardQueriesAsUnfriendly(queries)
qrs, err = vtg.resolver.ExecuteBatch(
ctx,
tabletType,
asTransaction,
session,
options,
func() (*scatterBatchRequest, error) {
return boundShardQueriesToScatterBatchRequest(ctx, vtg.resolver.resolver, queries, tabletType)
})
if err == nil {
var rowCount int64
for _, qr := range qrs {
rowCount += int64(len(qr.Rows))
}
vtg.rowsReturned.Add(statsKey, rowCount)
return qrs, nil
}
handleError:
query := map[string]interface{}{
"Queries": queries,
"TabletType": ltt,
"AsTransaction": asTransaction,
"Session": session,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteBatchShards)
return nil, err
}
// ExecuteBatchKeyspaceIds executes a group of queries based on the specified keyspace ids. This is a legacy function.
func (vtg *VTGate) ExecuteBatchKeyspaceIds(ctx context.Context, queries []*vtgatepb.BoundKeyspaceIdQuery, tabletType topodatapb.TabletType, asTransaction bool, session *vtgatepb.Session, options *querypb.ExecuteOptions) ([]sqltypes.Result, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"ExecuteBatchKeyspaceIds", unambiguousKeyspaceBKSIQ(queries), ltt}
defer vtg.timings.Record(statsKey, startTime)
var qrs []sqltypes.Result
var err error
for _, query := range queries {
if bvErr := sqltypes.ValidateBindVariables(query.Query.BindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
}
annotateBoundKeyspaceIDQueries(queries)
qrs, err = vtg.resolver.ExecuteBatch(
ctx,
tabletType,
asTransaction,
session,
options,
func() (*scatterBatchRequest, error) {
return boundKeyspaceIDQueriesToScatterBatchRequest(ctx, vtg.resolver.resolver, queries, tabletType)
})
if err == nil {
var rowCount int64
for _, qr := range qrs {
rowCount += int64(len(qr.Rows))
}
vtg.rowsReturned.Add(statsKey, rowCount)
return qrs, nil
}
handleError:
query := map[string]interface{}{
"Queries": queries,
"TabletType": ltt,
"AsTransaction": asTransaction,
"Session": session,
"Options": options,
}
err = recordAndAnnotateError(err, statsKey, query, vtg.logExecuteBatchKeyspaceIds)
return nil, err
}
// StreamExecuteKeyspaceIds executes a streaming query on the specified KeyspaceIds.
// The KeyspaceIds are resolved to shards using the serving graph.
// This function currently temporarily enforces the restriction of executing on
// one shard since it cannot merge-sort the results to guarantee ordering of
// response which is needed for checkpointing.
// The api supports supplying multiple KeyspaceIds to make it future proof. This is a legacy function.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines.
func (vtg *VTGate) StreamExecuteKeyspaceIds(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyspaceIds [][]byte, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"StreamExecuteKeyspaceIds", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
err = vtg.resolver.StreamExecute(
ctx,
sql,
bindVariables,
keyspace,
tabletType,
key.DestinationKeyspaceIDs(keyspaceIds),
options,
func(reply *sqltypes.Result) error {
vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows)))
return callback(reply)
})
handleError:
if err != nil {
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"KeyspaceIds": keyspaceIds,
"TabletType": ltt,
"Options": options,
}
return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecuteKeyspaceIds)
}
return nil
}
// StreamExecuteKeyRanges executes a streaming query on the specified KeyRanges.
// The KeyRanges are resolved to shards using the serving graph.
// This function currently temporarily enforces the restriction of executing on
// one shard since it cannot merge-sort the results to guarantee ordering of
// response which is needed for checkpointing.
// The api supports supplying multiple keyranges to make it future proof. This is a legacy function.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines.
func (vtg *VTGate) StreamExecuteKeyRanges(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, keyRanges []*topodatapb.KeyRange, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"StreamExecuteKeyRanges", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
err = vtg.resolver.StreamExecute(
ctx,
sql,
bindVariables,
keyspace,
tabletType,
key.DestinationKeyRanges(keyRanges),
options,
func(reply *sqltypes.Result) error {
vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows)))
return callback(reply)
})
handleError:
if err != nil {
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"KeyRanges": keyRanges,
"TabletType": ltt,
"Options": options,
}
return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecuteKeyRanges)
}
return nil
}
// StreamExecuteShards executes a streaming query on the specified shards. This is a legacy function.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines.
func (vtg *VTGate) StreamExecuteShards(ctx context.Context, sql string, bindVariables map[string]*querypb.BindVariable, keyspace string, shards []string, tabletType topodatapb.TabletType, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(tabletType)
statsKey := []string{"StreamExecuteShards", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
var err error
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
err = vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
goto handleError
}
err = vtg.resolver.StreamExecute(
ctx,
sql,
bindVariables,
keyspace,
tabletType,
key.DestinationShards(shards),
options,
func(reply *sqltypes.Result) error {
vtg.rowsReturned.Add(statsKey, int64(len(reply.Rows)))
return callback(reply)
})
handleError:
if err != nil {
query := map[string]interface{}{
"Sql": sql,
"BindVariables": bindVariables,
"Keyspace": keyspace,
"Shards": shards,
"TabletType": ltt,
"Options": options,
}
return recordAndAnnotateError(err, statsKey, query, vtg.logStreamExecuteShards)
}
return nil
}
// Begin begins a transaction. This is a legacy function.
func (vtg *VTGate) Begin(ctx context.Context, singledb bool) (*vtgatepb.Session, error) {
if !singledb && vtg.txConn.mode == vtgatepb.TransactionMode_SINGLE {
return nil, vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "multi-db transaction disallowed")
}
return &vtgatepb.Session{
InTransaction: true,
SingleDb: singledb,
}, nil
}
// Commit commits a transaction. This is a legacy function.
func (vtg *VTGate) Commit(ctx context.Context, twopc bool, session *vtgatepb.Session) error {
if session == nil {
return formatError(vterrors.New(vtrpcpb.Code_INVALID_ARGUMENT, "cannot commit: empty session"))
}
if !session.InTransaction {
return formatError(vterrors.New(vtrpcpb.Code_ABORTED, "cannot commit: not in transaction"))
}
if twopc {
session.TransactionMode = vtgatepb.TransactionMode_TWOPC
}
return formatError(vtg.txConn.Commit(ctx, NewSafeSession(session)))
}
// Rollback rolls back a transaction. This is a legacy function.
func (vtg *VTGate) Rollback(ctx context.Context, session *vtgatepb.Session) error {
return formatError(vtg.txConn.Rollback(ctx, NewSafeSession(session)))
}
// ResolveTransaction resolves the specified 2PC transaction.
func (vtg *VTGate) ResolveTransaction(ctx context.Context, dtid string) error {
return formatError(vtg.txConn.Resolve(ctx, dtid))
}
// isKeyspaceRangeBasedSharded returns true if a keyspace is sharded
// by range. This is true when there is a ShardingColumnType defined
// in the SrvKeyspace (that is using the range-based sharding with the
// client specifying the sharding key), or when the VSchema for the
// keyspace is Sharded.
func (vtg *VTGate) isKeyspaceRangeBasedSharded(keyspace string, srvKeyspace *topodatapb.SrvKeyspace) bool {
if srvKeyspace.ShardingColumnType != topodatapb.KeyspaceIdType_UNSET {
// We are using range based sharding with the application
// providing the sharding key value.
return true
}
if vtg.executor.IsKeyspaceRangeBasedSharded(keyspace) {
// We are using range based sharding with the VSchema
// poviding the routing information
return true
}
// Not range based sharded, might be un-sharded or custom sharded.
return false
}
// SplitQuery implements the SplitQuery RPC. This is the new version that
// supports multiple split-columns and multiple splitting algorithms.
// See the documentation of SplitQueryRequest in "proto/vtgate.proto" for more
// information.
func (vtg *VTGate) SplitQuery(
ctx context.Context,
keyspace string,
sql string,
bindVariables map[string]*querypb.BindVariable,
splitColumns []string,
splitCount int64,
numRowsPerQueryPart int64,
algorithm querypb.SplitQueryRequest_Algorithm) ([]*vtgatepb.SplitQueryResponse_Part, error) {
if bvErr := sqltypes.ValidateBindVariables(bindVariables); bvErr != nil {
return nil, vterrors.Errorf(vtrpcpb.Code_INVALID_ARGUMENT, "%v", bvErr)
}
// TODO(erez): Add validation of SplitQuery parameters.
rss, srvKeyspace, err := vtg.resolver.resolver.GetAllShards(ctx, keyspace, topodatapb.TabletType_RDONLY)
if err != nil {
return nil, err
}
// If the caller specified a splitCount (vs. specifying 'numRowsPerQueryPart') scale it by the
// number of shards (otherwise it stays 0).
perShardSplitCount := int64(math.Ceil(float64(splitCount) / float64(len(rss))))
// Determine whether to return SplitQueryResponse_KeyRangeParts or SplitQueryResponse_ShardParts.
// We return 'KeyRangeParts' for sharded keyspaces that are not custom sharded. If the
// keyspace is custom sharded or unsharded we return 'ShardParts'.
var querySplitToQueryPartFunc func(
querySplit *querypb.QuerySplit, rs *srvtopo.ResolvedShard) (*vtgatepb.SplitQueryResponse_Part, error)
if vtg.isKeyspaceRangeBasedSharded(keyspace, srvKeyspace) {
querySplitToQueryPartFunc = func(querySplit *querypb.QuerySplit, rs *srvtopo.ResolvedShard) (*vtgatepb.SplitQueryResponse_Part, error) {
// Use ValidateShardName to extract the keyrange.
_, kr, err := topo.ValidateShardName(rs.Target.Shard)
if err != nil {
return nil, fmt.Errorf("cannot extract keyrange from shard name %v: %v", rs.Target.Shard, err)
}
if kr == nil {
// Keyrange can be nil for the shard (e.g. for single-sharded keyspaces during resharding).
// In this case we append an empty keyrange that represents the entire keyspace.
kr = &topodatapb.KeyRange{
Start: []byte{},
End: []byte{},
}
}
return &vtgatepb.SplitQueryResponse_Part{
Query: querySplit.Query,
KeyRangePart: &vtgatepb.SplitQueryResponse_KeyRangePart{
Keyspace: keyspace,
KeyRanges: []*topodatapb.KeyRange{kr},
},
Size: querySplit.RowCount,
}, nil
}
} else {
// Keyspace is either unsharded or custom-sharded.
querySplitToQueryPartFunc = func(querySplit *querypb.QuerySplit, rs *srvtopo.ResolvedShard) (*vtgatepb.SplitQueryResponse_Part, error) {
return &vtgatepb.SplitQueryResponse_Part{
Query: querySplit.Query,
ShardPart: &vtgatepb.SplitQueryResponse_ShardPart{
Keyspace: keyspace,
Shards: []string{rs.Target.Shard},
},
Size: querySplit.RowCount,
}, nil
}
}
return vtg.resolver.scatterConn.SplitQuery(
ctx,
sql,
bindVariables,
splitColumns,
perShardSplitCount,
numRowsPerQueryPart,
algorithm,
rss,
querySplitToQueryPartFunc)
}
// GetSrvKeyspace is part of the vtgate service API.
func (vtg *VTGate) GetSrvKeyspace(ctx context.Context, keyspace string) (*topodatapb.SrvKeyspace, error) {
return vtg.resolver.toposerv.GetSrvKeyspace(ctx, vtg.resolver.cell, keyspace)
}
// MessageStream is part of the vtgate service API. This is a V2 level API
// that's sent to the Resolver.
// Note we guarantee the callback will not be called concurrently
// by mutiple go routines.
func (vtg *VTGate) MessageStream(ctx context.Context, keyspace string, shard string, keyRange *topodatapb.KeyRange, name string, callback func(*sqltypes.Result) error) error {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(topodatapb.TabletType_MASTER)
statsKey := []string{"MessageStream", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)
err := vtg.executor.MessageStream(
ctx,
keyspace,
shard,
keyRange,
name,
callback,
)
if err != nil {
request := map[string]interface{}{
"Keyspace": keyspace,
"Shard": shard,
"KeyRange": keyRange,
"TabletType": ltt,
"MessageName": name,
}
recordAndAnnotateError(err, statsKey, request, vtg.logMessageStream)
}
return formatError(err)
}
// MessageAck is part of the vtgate service API. This is a V3 level API that's sent
// to the executor. The table name will be resolved using V3 rules, and the routing
// will make use of vindexes for sharded keyspaces.
// TODO(sougou): Deprecate this in favor of an SQL statement.
func (vtg *VTGate) MessageAck(ctx context.Context, keyspace string, name string, ids []*querypb.Value) (int64, error) {
startTime := time.Now()
ltt := topoproto.TabletTypeLString(topodatapb.TabletType_MASTER)
statsKey := []string{"MessageAck", keyspace, ltt}
defer vtg.timings.Record(statsKey, startTime)