-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
tabletserver.go
1997 lines (1791 loc) · 71.1 KB
/
tabletserver.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 2019 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tabletserver
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"sort"
"strings"
"sync"
"syscall"
"time"
"google.golang.org/protobuf/proto"
"vitess.io/vitess/go/acl"
"vitess.io/vitess/go/mysql"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/stats"
"vitess.io/vitess/go/sync2"
"vitess.io/vitess/go/tb"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/callerid"
"vitess.io/vitess/go/vt/dbconfigs"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/logutil"
"vitess.io/vitess/go/vt/mysqlctl"
binlogdatapb "vitess.io/vitess/go/vt/proto/binlogdata"
querypb "vitess.io/vitess/go/vt/proto/query"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
"vitess.io/vitess/go/vt/servenv"
"vitess.io/vitess/go/vt/sqlparser"
"vitess.io/vitess/go/vt/srvtopo"
"vitess.io/vitess/go/vt/tableacl"
"vitess.io/vitess/go/vt/topo"
"vitess.io/vitess/go/vt/topo/topoproto"
"vitess.io/vitess/go/vt/vterrors"
"vitess.io/vitess/go/vt/vttablet/onlineddl"
"vitess.io/vitess/go/vt/vttablet/queryservice"
"vitess.io/vitess/go/vt/vttablet/tabletserver/gc"
"vitess.io/vitess/go/vt/vttablet/tabletserver/messager"
"vitess.io/vitess/go/vt/vttablet/tabletserver/planbuilder"
"vitess.io/vitess/go/vt/vttablet/tabletserver/repltracker"
"vitess.io/vitess/go/vt/vttablet/tabletserver/rules"
"vitess.io/vitess/go/vt/vttablet/tabletserver/schema"
"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
"vitess.io/vitess/go/vt/vttablet/tabletserver/throttle"
"vitess.io/vitess/go/vt/vttablet/tabletserver/txserializer"
"vitess.io/vitess/go/vt/vttablet/tabletserver/txthrottler"
"vitess.io/vitess/go/vt/vttablet/tabletserver/vstreamer"
"vitess.io/vitess/go/vt/vttablet/vexec"
)
// logPoolFull is for throttling transaction / query pool full messages in the log.
var logPoolFull = logutil.NewThrottledLogger("PoolFull", 1*time.Minute)
var logComputeRowSerializerKey = logutil.NewThrottledLogger("ComputeRowSerializerKey", 1*time.Minute)
// TabletServer implements the RPC interface for the query service.
// TabletServer is initialized in the following sequence:
// NewTabletServer->InitDBConfig->SetServingType.
// Subcomponents of TabletServer are initialized using one of the
// following sequences:
// New->InitDBConfig->Init->Open, or New->InitDBConfig->Open.
// Essentially, InitDBConfig is a continuation of New. However,
// the db config is not initially available. For this reason,
// the initialization is done in two phases.
// Some subcomponents have Init functions. Such functions usually
// perform one-time initializations like creating metadata tables
// in the sidecar database. These functions must be idempotent.
// Open and Close can be called repeatedly during the lifetime of
// a subcomponent. These should also be idempotent.
type TabletServer struct {
exporter *servenv.Exporter
config *tabletenv.TabletConfig
stats *tabletenv.Stats
QueryTimeout sync2.AtomicDuration
txTimeout sync2.AtomicDuration
TerseErrors bool
enableHotRowProtection bool
topoServer *topo.Server
// These are sub-components of TabletServer.
statelessql *QueryList
statefulql *QueryList
olapql *QueryList
se *schema.Engine
rt *repltracker.ReplTracker
vstreamer *vstreamer.Engine
tracker *schema.Tracker
watcher *BinlogWatcher
qe *QueryEngine
txThrottler *txthrottler.TxThrottler
te *TxEngine
messager *messager.Engine
hs *healthStreamer
lagThrottler *throttle.Throttler
tableGC *gc.TableGC
// sm manages state transitions.
sm *stateManager
onlineDDLExecutor *onlineddl.Executor
// alias is used for identifying this tabletserver in healthcheck responses.
alias *topodatapb.TabletAlias
}
var _ queryservice.QueryService = (*TabletServer)(nil)
// RegisterFunctions is a list of all the
// RegisterFunction that will be called upon
// Register() on a TabletServer
var RegisterFunctions []func(Controller)
// NewServer creates a new TabletServer based on the command line flags.
func NewServer(name string, topoServer *topo.Server, alias *topodatapb.TabletAlias) *TabletServer {
return NewTabletServer(name, tabletenv.NewCurrentConfig(), topoServer, alias)
}
var (
tsOnce sync.Once
srvTopoServer srvtopo.Server
)
// NewTabletServer creates an instance of TabletServer. Only the first
// instance of TabletServer will expose its state variables.
func NewTabletServer(name string, config *tabletenv.TabletConfig, topoServer *topo.Server, alias *topodatapb.TabletAlias) *TabletServer {
exporter := servenv.NewExporter(name, "Tablet")
tsv := &TabletServer{
exporter: exporter,
stats: tabletenv.NewStats(exporter),
config: config,
QueryTimeout: sync2.NewAtomicDuration(config.Oltp.QueryTimeoutSeconds.Get()),
txTimeout: sync2.NewAtomicDuration(config.Oltp.TxTimeoutSeconds.Get()),
TerseErrors: config.TerseErrors,
enableHotRowProtection: config.HotRowProtection.Mode != tabletenv.Disable,
topoServer: topoServer,
alias: proto.Clone(alias).(*topodatapb.TabletAlias),
}
tsOnce.Do(func() { srvTopoServer = srvtopo.NewResilientServer(topoServer, "TabletSrvTopo") })
tabletTypeFunc := func() topodatapb.TabletType {
if tsv.sm == nil {
return topodatapb.TabletType_UNKNOWN
}
return tsv.sm.Target().TabletType
}
tsv.statelessql = NewQueryList("oltp-stateless")
tsv.statefulql = NewQueryList("oltp-stateful")
tsv.olapql = NewQueryList("olap")
tsv.lagThrottler = throttle.NewThrottler(tsv, topoServer, tabletTypeFunc)
tsv.hs = newHealthStreamer(tsv, alias)
tsv.se = schema.NewEngine(tsv)
tsv.rt = repltracker.NewReplTracker(tsv, alias)
tsv.vstreamer = vstreamer.NewEngine(tsv, srvTopoServer, tsv.se, tsv.lagThrottler, alias.Cell)
tsv.tracker = schema.NewTracker(tsv, tsv.vstreamer, tsv.se)
tsv.watcher = NewBinlogWatcher(tsv, tsv.vstreamer, tsv.config)
tsv.qe = NewQueryEngine(tsv, tsv.se)
tsv.txThrottler = txthrottler.NewTxThrottler(tsv.config, topoServer)
tsv.te = NewTxEngine(tsv)
tsv.messager = messager.NewEngine(tsv, tsv.se, tsv.vstreamer)
tsv.onlineDDLExecutor = onlineddl.NewExecutor(tsv, alias, topoServer, tabletTypeFunc)
tsv.tableGC = gc.NewTableGC(tsv, topoServer, tabletTypeFunc, tsv.lagThrottler)
tsv.sm = &stateManager{
statelessql: tsv.statelessql,
statefulql: tsv.statefulql,
olapql: tsv.olapql,
hs: tsv.hs,
se: tsv.se,
rt: tsv.rt,
vstreamer: tsv.vstreamer,
tracker: tsv.tracker,
watcher: tsv.watcher,
qe: tsv.qe,
txThrottler: tsv.txThrottler,
te: tsv.te,
messager: tsv.messager,
ddle: tsv.onlineDDLExecutor,
throttler: tsv.lagThrottler,
tableGC: tsv.tableGC,
}
tsv.exporter.NewGaugeFunc("TabletState", "Tablet server state", func() int64 { return int64(tsv.sm.State()) })
tsv.exporter.Publish("TabletStateName", stats.StringFunc(tsv.sm.IsServingString))
// TabletServerState exports the same information as the above two stats (TabletState / TabletStateName),
// but exported with TabletStateName as a label for Prometheus, which doesn't support exporting strings as stat values.
tsv.exporter.NewGaugesFuncWithMultiLabels("TabletServerState", "Tablet server state labeled by state name", []string{"name"}, func() map[string]int64 {
return map[string]int64{tsv.sm.IsServingString(): 1}
})
tsv.exporter.NewGaugeDurationFunc("QueryTimeout", "Tablet server query timeout", tsv.QueryTimeout.Get)
tsv.registerHealthzHealthHandler()
tsv.registerDebugHealthHandler()
tsv.registerQueryzHandler()
tsv.registerQueryListHandlers([]*QueryList{tsv.statelessql, tsv.statefulql, tsv.olapql})
tsv.registerTwopczHandler()
tsv.registerMigrationStatusHandler()
tsv.registerThrottlerHandlers()
tsv.registerDebugEnvHandler()
return tsv
}
// InitDBConfig initializes the db config variables for TabletServer. You must call this function
// to complete the creation of TabletServer.
func (tsv *TabletServer) InitDBConfig(target *querypb.Target, dbcfgs *dbconfigs.DBConfigs, mysqld mysqlctl.MysqlDaemon) error {
if tsv.sm.State() != StateNotConnected {
return vterrors.NewErrorf(vtrpcpb.Code_UNAVAILABLE, vterrors.ServerNotAvailable, "Server isn't available")
}
tsv.sm.Init(tsv, target)
tsv.sm.target = proto.Clone(target).(*querypb.Target)
tsv.config.DB = dbcfgs
tsv.se.InitDBConfig(tsv.config.DB.DbaWithDB())
tsv.rt.InitDBConfig(target, mysqld)
tsv.txThrottler.InitDBConfig(target)
tsv.vstreamer.InitDBConfig(target.Keyspace, target.Shard)
tsv.hs.InitDBConfig(target, tsv.config.DB.DbaWithDB())
tsv.onlineDDLExecutor.InitDBConfig(target.Keyspace, target.Shard, dbcfgs.DBName)
tsv.lagThrottler.InitDBConfig(target.Keyspace, target.Shard)
tsv.tableGC.InitDBConfig(target.Keyspace, target.Shard, dbcfgs.DBName)
return nil
}
// Register prepares TabletServer for serving by calling
// all the registrations functions.
func (tsv *TabletServer) Register() {
for _, f := range RegisterFunctions {
f(tsv)
}
}
// Exporter satisfies tabletenv.Env.
func (tsv *TabletServer) Exporter() *servenv.Exporter {
return tsv.exporter
}
// Config satisfies tabletenv.Env.
func (tsv *TabletServer) Config() *tabletenv.TabletConfig {
return tsv.config
}
// Stats satisfies tabletenv.Env.
func (tsv *TabletServer) Stats() *tabletenv.Stats {
return tsv.stats
}
// LogError satisfies tabletenv.Env.
func (tsv *TabletServer) LogError() {
if x := recover(); x != nil {
log.Errorf("Uncaught panic:\n%v\n%s", x, tb.Stack(4))
tsv.stats.InternalErrors.Add("Panic", 1)
}
}
// RegisterQueryRuleSource registers ruleSource for setting query rules.
func (tsv *TabletServer) RegisterQueryRuleSource(ruleSource string) {
tsv.qe.queryRuleSources.RegisterSource(ruleSource)
}
// UnRegisterQueryRuleSource unregisters ruleSource from query rules.
func (tsv *TabletServer) UnRegisterQueryRuleSource(ruleSource string) {
tsv.qe.queryRuleSources.UnRegisterSource(ruleSource)
}
// SetQueryRules sets the query rules for a registered ruleSource.
func (tsv *TabletServer) SetQueryRules(ruleSource string, qrs *rules.Rules) error {
err := tsv.qe.queryRuleSources.SetRules(ruleSource, qrs)
if err != nil {
return err
}
tsv.qe.ClearQueryPlanCache()
return nil
}
func (tsv *TabletServer) initACL(tableACLConfigFile string, enforceTableACLConfig bool) {
// tabletacl.Init loads ACL from file if *tableACLConfig is not empty
err := tableacl.Init(
tableACLConfigFile,
func() {
tsv.ClearQueryPlanCache()
},
)
if err != nil {
log.Errorf("Fail to initialize Table ACL: %v", err)
if enforceTableACLConfig {
log.Exit("Need a valid initial Table ACL when enforce-tableacl-config is set, exiting.")
}
}
}
// InitACL loads the table ACL and sets up a SIGHUP handler for reloading it.
func (tsv *TabletServer) InitACL(tableACLConfigFile string, enforceTableACLConfig bool, reloadACLConfigFileInterval time.Duration) {
tsv.initACL(tableACLConfigFile, enforceTableACLConfig)
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGHUP)
go func() {
for range sigChan {
tsv.initACL(tableACLConfigFile, enforceTableACLConfig)
}
}()
if reloadACLConfigFileInterval != 0 {
ticker := time.NewTicker(reloadACLConfigFileInterval)
go func() {
for range ticker.C {
sigChan <- syscall.SIGHUP
}
}()
}
}
// SetServingType changes the serving type of the tabletserver. It starts or
// stops internal services as deemed necessary.
// Returns true if the state of QueryService or the tablet type changed.
func (tsv *TabletServer) SetServingType(tabletType topodatapb.TabletType, terTimestamp time.Time, serving bool, reason string) error {
state := StateNotServing
if serving {
state = StateServing
}
return tsv.sm.SetServingType(tabletType, terTimestamp, state, reason)
}
// StartService is a convenience function for InitDBConfig->SetServingType
// with serving=true.
func (tsv *TabletServer) StartService(target *querypb.Target, dbcfgs *dbconfigs.DBConfigs, mysqld mysqlctl.MysqlDaemon) error {
if err := tsv.InitDBConfig(target, dbcfgs, mysqld); err != nil {
return err
}
// StartService is only used for testing. So, we cheat by aggressively setting replication to healthy.
return tsv.sm.SetServingType(target.TabletType, time.Time{}, StateServing, "")
}
// StopService shuts down the tabletserver to the uninitialized state.
// It first transitions to StateShuttingDown, then waits for active
// services to shut down. Then it shuts down the rest. This function
// should be called before process termination, or if MySQL is unreachable.
// Under normal circumstances, SetServingType should be called.
func (tsv *TabletServer) StopService() {
tsv.sm.StopService()
}
// IsHealthy returns nil for non-serving types or if the query service is healthy (able to
// connect to the database and serving traffic), or an error explaining
// the unhealthiness otherwise.
func (tsv *TabletServer) IsHealthy() error {
if topoproto.IsServingType(tsv.sm.Target().TabletType) {
_, err := tsv.Execute(
tabletenv.LocalContext(),
nil,
"/* health */ select 1 from dual",
nil,
0,
0,
nil,
)
return err
}
return nil
}
// ReloadSchema reloads the schema.
func (tsv *TabletServer) ReloadSchema(ctx context.Context) error {
return tsv.se.Reload(ctx)
}
// WaitForSchemaReset blocks the TabletServer until there's been at least `timeout` duration without
// any schema changes. This is useful for tests that need to wait for all the currently existing schema
// changes to finish being applied.
func (tsv *TabletServer) WaitForSchemaReset(timeout time.Duration) {
onSchemaChange := make(chan struct{}, 1)
tsv.se.RegisterNotifier("_tsv_wait", func(_ map[string]*schema.Table, _, _, _ []string) {
onSchemaChange <- struct{}{}
})
defer tsv.se.UnregisterNotifier("_tsv_wait")
after := time.NewTimer(timeout)
defer after.Stop()
for {
select {
case <-after.C:
return
case <-onSchemaChange:
if !after.Stop() {
<-after.C
}
after.Reset(timeout)
}
}
}
// ClearQueryPlanCache clears internal query plan cache
func (tsv *TabletServer) ClearQueryPlanCache() {
// We should ideally bracket this with start & endErequest,
// but query plan cache clearing is safe to call even if the
// tabletserver is down.
tsv.qe.ClearQueryPlanCache()
}
// QueryService returns the QueryService part of TabletServer.
func (tsv *TabletServer) QueryService() queryservice.QueryService {
return tsv
}
// OnlineDDLExecutor returns the onlineddl.Executor part of TabletServer.
func (tsv *TabletServer) OnlineDDLExecutor() vexec.Executor {
return tsv.onlineDDLExecutor
}
// LagThrottler returns the throttle.Throttler part of TabletServer.
func (tsv *TabletServer) LagThrottler() *throttle.Throttler {
return tsv.lagThrottler
}
// TableGC returns the tableDropper part of TabletServer.
func (tsv *TabletServer) TableGC() *gc.TableGC {
return tsv.tableGC
}
// TwoPCEngineWait waits until the TwoPC engine has been opened, and the redo read
func (tsv *TabletServer) TwoPCEngineWait() {
tsv.te.twoPCReady.Wait()
}
// SchemaEngine returns the SchemaEngine part of TabletServer.
func (tsv *TabletServer) SchemaEngine() *schema.Engine {
return tsv.se
}
// Begin starts a new transaction. This is allowed only if the state is StateServing.
func (tsv *TabletServer) Begin(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions) (transactionID int64, tablet *topodatapb.TabletAlias, err error) {
return tsv.begin(ctx, target, nil, 0, options)
}
func (tsv *TabletServer) begin(ctx context.Context, target *querypb.Target, preQueries []string, reservedID int64, options *querypb.ExecuteOptions) (transactionID int64, tablet *topodatapb.TabletAlias, err error) {
err = tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"Begin", "begin", nil,
target, options, false, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
startTime := time.Now()
if tsv.txThrottler.Throttle() {
return vterrors.Errorf(vtrpcpb.Code_RESOURCE_EXHAUSTED, "Transaction throttled")
}
var beginSQL string
transactionID, beginSQL, err = tsv.te.Begin(ctx, preQueries, reservedID, options)
logStats.TransactionID = transactionID
logStats.ReservedID = reservedID
// Record the actual statements that were executed in the logStats.
// If nothing was actually executed, don't count the operation in
// the tablet metrics, and clear out the logStats Method so that
// handlePanicAndSendLogStats doesn't log the no-op.
logStats.OriginalSQL = beginSQL
if beginSQL != "" {
tsv.stats.QueryTimings.Record("BEGIN", startTime)
} else {
logStats.Method = ""
}
return err
},
)
return transactionID, tsv.alias, err
}
// Commit commits the specified transaction.
func (tsv *TabletServer) Commit(ctx context.Context, target *querypb.Target, transactionID int64) (newReservedID int64, err error) {
err = tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"Commit", "commit", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
startTime := time.Now()
logStats.TransactionID = transactionID
var commitSQL string
newReservedID, commitSQL, err = tsv.te.Commit(ctx, transactionID)
if newReservedID > 0 {
// commit executed on old reserved id.
logStats.ReservedID = transactionID
}
// If nothing was actually executed, don't count the operation in
// the tablet metrics, and clear out the logStats Method so that
// handlePanicAndSendLogStats doesn't log the no-op.
if commitSQL != "" {
tsv.stats.QueryTimings.Record("COMMIT", startTime)
} else {
logStats.Method = ""
}
return err
},
)
return newReservedID, err
}
// Rollback rollsback the specified transaction.
func (tsv *TabletServer) Rollback(ctx context.Context, target *querypb.Target, transactionID int64) (newReservedID int64, err error) {
err = tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"Rollback", "rollback", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
defer tsv.stats.QueryTimings.Record("ROLLBACK", time.Now())
logStats.TransactionID = transactionID
newReservedID, err = tsv.te.Rollback(ctx, transactionID)
if newReservedID > 0 {
// rollback executed on old reserved id.
logStats.ReservedID = transactionID
}
return err
},
)
return newReservedID, err
}
// Prepare prepares the specified transaction.
func (tsv *TabletServer) Prepare(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"Prepare", "prepare", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.Prepare(transactionID, dtid)
},
)
}
// CommitPrepared commits the prepared transaction.
func (tsv *TabletServer) CommitPrepared(ctx context.Context, target *querypb.Target, dtid string) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"CommitPrepared", "commit_prepared", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.CommitPrepared(dtid)
},
)
}
// RollbackPrepared commits the prepared transaction.
func (tsv *TabletServer) RollbackPrepared(ctx context.Context, target *querypb.Target, dtid string, originalID int64) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"RollbackPrepared", "rollback_prepared", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.RollbackPrepared(dtid, originalID)
},
)
}
// CreateTransaction creates the metadata for a 2PC transaction.
func (tsv *TabletServer) CreateTransaction(ctx context.Context, target *querypb.Target, dtid string, participants []*querypb.Target) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"CreateTransaction", "create_transaction", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.CreateTransaction(dtid, participants)
},
)
}
// StartCommit atomically commits the transaction along with the
// decision to commit the associated 2pc transaction.
func (tsv *TabletServer) StartCommit(ctx context.Context, target *querypb.Target, transactionID int64, dtid string) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"StartCommit", "start_commit", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.StartCommit(transactionID, dtid)
},
)
}
// SetRollback transitions the 2pc transaction to the Rollback state.
// If a transaction id is provided, that transaction is also rolled back.
func (tsv *TabletServer) SetRollback(ctx context.Context, target *querypb.Target, dtid string, transactionID int64) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"SetRollback", "set_rollback", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.SetRollback(dtid, transactionID)
},
)
}
// ConcludeTransaction deletes the 2pc transaction metadata
// essentially resolving it.
func (tsv *TabletServer) ConcludeTransaction(ctx context.Context, target *querypb.Target, dtid string) (err error) {
return tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"ConcludeTransaction", "conclude_transaction", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
return txe.ConcludeTransaction(dtid)
},
)
}
// ReadTransaction returns the metadata for the specified dtid.
func (tsv *TabletServer) ReadTransaction(ctx context.Context, target *querypb.Target, dtid string) (metadata *querypb.TransactionMetadata, err error) {
err = tsv.execRequest(
ctx, tsv.QueryTimeout.Get(),
"ReadTransaction", "read_transaction", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
txe := &TxExecutor{
ctx: ctx,
logStats: logStats,
te: tsv.te,
}
metadata, err = txe.ReadTransaction(dtid)
return err
},
)
return metadata, err
}
// Execute executes the query and returns the result as response.
func (tsv *TabletServer) Execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID, reservedID int64, options *querypb.ExecuteOptions) (result *sqltypes.Result, err error) {
span, ctx := trace.NewSpan(ctx, "TabletServer.Execute")
trace.AnnotateSQL(span, sqlparser.Preview(sql))
defer span.Finish()
if transactionID != 0 && reservedID != 0 && transactionID != reservedID {
return nil, vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] transactionID and reserveID must match if both are non-zero")
}
allowOnShutdown := false
timeout := tsv.QueryTimeout.Get()
if transactionID != 0 {
allowOnShutdown = true
// Use the smaller of the two values (0 means infinity).
// TODO(sougou): Assign deadlines to each transaction and set query timeout accordingly.
timeout = smallerTimeout(timeout, tsv.txTimeout.Get())
}
err = tsv.execRequest(
ctx, timeout,
"Execute", sql, bindVariables,
target, options, allowOnShutdown,
func(ctx context.Context, logStats *tabletenv.LogStats) error {
if bindVariables == nil {
bindVariables = make(map[string]*querypb.BindVariable)
}
query, comments := sqlparser.SplitMarginComments(sql)
plan, err := tsv.qe.GetPlan(ctx, logStats, query, skipQueryPlanCache(options), reservedID != 0)
if err != nil {
return err
}
// If both the values are non-zero then by design they are same value. So, it is safe to overwrite.
connID := reservedID
if transactionID != 0 {
connID = transactionID
}
logStats.ReservedID = reservedID
logStats.TransactionID = transactionID
qre := &QueryExecutor{
query: query,
marginComments: comments,
bindVars: bindVariables,
connID: connID,
options: options,
plan: plan,
ctx: ctx,
logStats: logStats,
tsv: tsv,
tabletType: target.GetTabletType(),
}
result, err = qre.Execute()
if err != nil {
return err
}
result = result.StripMetadata(sqltypes.IncludeFieldsOrDefault(options))
// Change database name in mysql output to the keyspace name
if tsv.sm.target.Keyspace != tsv.config.DB.DBName && sqltypes.IncludeFieldsOrDefault(options) == querypb.ExecuteOptions_ALL {
switch qre.plan.PlanID {
case planbuilder.PlanSelect, planbuilder.PlanSelectImpossible:
dbName := tsv.config.DB.DBName
ksName := tsv.sm.target.Keyspace
for _, f := range result.Fields {
if f.Database == dbName {
f.Database = ksName
}
}
}
}
return nil
},
)
return result, err
}
// smallerTimeout returns the smaller of the two timeouts.
// 0 is treated as infinity.
func smallerTimeout(t1, t2 time.Duration) time.Duration {
if t1 == 0 {
return t2
}
if t2 == 0 {
return t1
}
if t1 < t2 {
return t1
}
return t2
}
// StreamExecute executes the query and streams the result.
// The first QueryResult will have Fields set (and Rows nil).
// The subsequent QueryResult will have Rows set (and Fields nil).
func (tsv *TabletServer) StreamExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, reservedID int64, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) (err error) {
if transactionID != 0 && reservedID != 0 && transactionID != reservedID {
return vterrors.New(vtrpcpb.Code_INTERNAL, "[BUG] transactionID and reserveID must match if both are non-zero")
}
allowOnShutdown := false
var timeout time.Duration
if transactionID != 0 {
allowOnShutdown = true
// Use the transaction timeout.
timeout = tsv.txTimeout.Get()
}
return tsv.execRequest(
ctx, timeout,
"StreamExecute", sql, bindVariables,
target, options, allowOnShutdown,
func(ctx context.Context, logStats *tabletenv.LogStats) error {
if bindVariables == nil {
bindVariables = make(map[string]*querypb.BindVariable)
}
query, comments := sqlparser.SplitMarginComments(sql)
// TODO: update the isReservedConn logic when StreamExecute supports reserved connections.
plan, err := tsv.qe.GetStreamPlan(query, false /* isReservedConn */)
if err != nil {
return err
}
// If both the values are non-zero then by design they are same value. So, it is safe to overwrite.
connID := reservedID
if transactionID != 0 {
connID = transactionID
}
qre := &QueryExecutor{
query: query,
marginComments: comments,
bindVars: bindVariables,
connID: connID,
options: options,
plan: plan,
ctx: ctx,
logStats: logStats,
tsv: tsv,
}
return qre.Stream(callback)
},
)
}
// ExecuteBatch executes a group of queries and returns their results as a list.
// ExecuteBatch can be called for an existing transaction, or it can be called with
// the AsTransaction flag which will execute all statements inside an independent
// transaction. If AsTransaction is true, TransactionId must be 0.
// TODO(reserve-conn): Validate the use-case and Add support for reserve connection in ExecuteBatch
func (tsv *TabletServer) ExecuteBatch(ctx context.Context, target *querypb.Target, queries []*querypb.BoundQuery, asTransaction bool, transactionID int64, options *querypb.ExecuteOptions) (results []sqltypes.Result, err error) {
span, ctx := trace.NewSpan(ctx, "TabletServer.ExecuteBatch")
defer span.Finish()
if len(queries) == 0 {
return nil, vterrors.NewErrorf(vtrpcpb.Code_INVALID_ARGUMENT, vterrors.EmptyQuery, "Query was empty")
}
if asTransaction && transactionID != 0 {
return nil, vterrors.NewErrorf(vtrpcpb.Code_FAILED_PRECONDITION, vterrors.CantDoThisInTransaction, "You are not allowed to execute this command in a transaction")
}
if tsv.enableHotRowProtection && asTransaction {
// Serialize transactions which target the same hot row range.
// NOTE: We put this intentionally at this place *before* StartRequest()
// gets called below. Otherwise, the StartRequest()/EndRequest() section from
// below would overlap with the StartRequest()/EndRequest() section executed
// by tsv.beginWaitForSameRangeTransactions().
txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, queries[0].Sql, queries[0].BindVariables)
if err != nil {
return nil, err
}
if txDone != nil {
defer txDone()
}
}
allowOnShutdown := transactionID != 0
// TODO(sougou): Convert StartRequest/EndRequest pattern to use wrapper
// function tsv.execRequest() instead.
// Note that below we always return "err" right away and do not call
// tsv.convertAndLogError. That's because the methods which returned "err",
// e.g. tsv.Execute(), already called that function and therefore already
// converted and logged the error.
if err = tsv.sm.StartRequest(ctx, target, allowOnShutdown); err != nil {
return nil, err
}
defer tsv.sm.EndRequest()
defer tsv.handlePanicAndSendLogStats("batch", nil, nil)
if options == nil {
options = &querypb.ExecuteOptions{}
}
// When all these conditions are met, we send the queries directly
// to the MySQL without creating a transaction. This optimization
// yields better throughput.
// Setting ExecuteOptions_AUTOCOMMIT will get a connection out of the
// pool without actually begin/commit the transaction.
if (options.TransactionIsolation == querypb.ExecuteOptions_DEFAULT) &&
asTransaction &&
planbuilder.PassthroughDMLs {
options.TransactionIsolation = querypb.ExecuteOptions_AUTOCOMMIT
}
if asTransaction {
// We ignore the return alias because this transaction only exists in the scope of this call
transactionID, _, err = tsv.Begin(ctx, target, options)
if err != nil {
return nil, err
}
// If transaction was not committed by the end, it means
// that there was an error, roll it back.
defer func() {
if transactionID != 0 {
tsv.Rollback(ctx, target, transactionID)
}
}()
}
results = make([]sqltypes.Result, 0, len(queries))
for _, bound := range queries {
localReply, err := tsv.Execute(ctx, target, bound.Sql, bound.BindVariables, transactionID, 0, options)
if err != nil {
return nil, err
}
results = append(results, *localReply)
}
if asTransaction {
if _, err = tsv.Commit(ctx, target, transactionID); err != nil {
transactionID = 0
return nil, err
}
transactionID = 0
}
return results, nil
}
// BeginExecute combines Begin and Execute.
func (tsv *TabletServer) BeginExecute(ctx context.Context, target *querypb.Target, preQueries []string, sql string, bindVariables map[string]*querypb.BindVariable, reservedID int64, options *querypb.ExecuteOptions) (*sqltypes.Result, int64, *topodatapb.TabletAlias, error) {
// Disable hot row protection in case of reserve connection.
if tsv.enableHotRowProtection && reservedID == 0 {
txDone, err := tsv.beginWaitForSameRangeTransactions(ctx, target, options, sql, bindVariables)
if err != nil {
return nil, 0, nil, err
}
if txDone != nil {
defer txDone()
}
}
transactionID, alias, err := tsv.begin(ctx, target, preQueries, reservedID, options)
if err != nil {
return nil, 0, nil, err
}
result, err := tsv.Execute(ctx, target, sql, bindVariables, transactionID, reservedID, options)
return result, transactionID, alias, err
}
// BeginStreamExecute combines Begin and StreamExecute.
func (tsv *TabletServer) BeginStreamExecute(
ctx context.Context,
target *querypb.Target,
preQueries []string,
sql string,
bindVariables map[string]*querypb.BindVariable,
reservedID int64,
options *querypb.ExecuteOptions,
callback func(*sqltypes.Result) error,
) (int64, *topodatapb.TabletAlias, error) {
transactionID, alias, err := tsv.begin(ctx, target, preQueries, reservedID, options)
if err != nil {
return 0, nil, err
}
err = tsv.StreamExecute(ctx, target, sql, bindVariables, transactionID, reservedID, options, callback)
return transactionID, alias, err
}
func (tsv *TabletServer) beginWaitForSameRangeTransactions(ctx context.Context, target *querypb.Target, options *querypb.ExecuteOptions, sql string, bindVariables map[string]*querypb.BindVariable) (txserializer.DoneFunc, error) {
// Serialize the creation of new transactions *if* the first
// UPDATE or DELETE query has the same WHERE clause as a query which is
// already running in a transaction (only other BeginExecute() calls are
// considered). This avoids exhausting all txpool slots due to a hot row.
//
// Known Issue: There can be more than one transaction pool slot in use for
// the same row because the next transaction is unblocked after this
// BeginExecute() call is done and before Commit() on this transaction has
// been called. Due to the additional MySQL locking, this should result into
// two transaction pool slots per row at most. (This transaction pending on
// COMMIT, the next one waiting for MySQL in BEGIN+EXECUTE.)
var txDone txserializer.DoneFunc
err := tsv.execRequest(
// Use (potentially longer) -queryserver-config-query-timeout and not
// -queryserver-config-txpool-timeout (defaults to 1s) to limit the waiting.
ctx, tsv.QueryTimeout.Get(),
"", "waitForSameRangeTransactions", nil,
target, options, false, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
k, table := tsv.computeTxSerializerKey(ctx, logStats, sql, bindVariables)
if k == "" {
// Query is not subject to tx serialization/hot row protection.
return nil
}
startTime := time.Now()
done, waited, waitErr := tsv.qe.txSerializer.Wait(ctx, k, table)
txDone = done
if waited {
tsv.stats.WaitTimings.Record("TxSerializer", startTime)
}
return waitErr
})
return txDone, err
}
// computeTxSerializerKey returns a unique string ("key") used to determine
// whether two queries would update the same row (range).