-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
tabletserver.go
2162 lines (1935 loc) · 80.2 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"
"math"
"net/http"
"os"
"os/signal"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"vitess.io/vitess/go/acl"
"vitess.io/vitess/go/mysql/sqlerror"
"vitess.io/vitess/go/pools/smartconnpool"
"vitess.io/vitess/go/sqltypes"
"vitess.io/vitess/go/stats"
"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"
"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/vtenv"
"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/throttle/throttlerapp"
"vitess.io/vitess/go/vt/vttablet/tabletserver/txserializer"
"vitess.io/vitess/go/vt/vttablet/tabletserver/txthrottler"
"vitess.io/vitess/go/vt/vttablet/tabletserver/vstreamer"
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"
)
// 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 and 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 atomic.Int64
TerseErrors bool
TruncateErrorLen int
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
// This field is only stored for testing
checkMysqlGaugeFunc *stats.GaugeFunc
env *vtenv.Environment
}
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(ctx context.Context, env *vtenv.Environment, name string, topoServer *topo.Server, alias *topodatapb.TabletAlias) *TabletServer {
return NewTabletServer(ctx, env, 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(ctx context.Context, env *vtenv.Environment, 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,
TerseErrors: config.TerseErrors,
TruncateErrorLen: config.TruncateErrorLen,
enableHotRowProtection: config.HotRowProtection.Mode != tabletenv.Disable,
topoServer: topoServer,
alias: alias.CloneVT(),
env: env,
}
tsv.QueryTimeout.Store(config.Oltp.QueryTimeout.Nanoseconds())
tsOnce.Do(func() { srvTopoServer = srvtopo.NewResilientServer(ctx, topoServer, "TabletSrvTopo") })
tabletTypeFunc := func() topodatapb.TabletType {
if tsv.sm == nil || tsv.sm.Target() == nil {
return topodatapb.TabletType_UNKNOWN
}
return tsv.sm.Target().TabletType
}
tsv.statelessql = NewQueryList("oltp-stateless", env.Parser())
tsv.statefulql = NewQueryList("oltp-stateful", env.Parser())
tsv.olapql = NewQueryList("olap", env.Parser())
tsv.se = schema.NewEngine(tsv)
tsv.hs = newHealthStreamer(tsv, alias, tsv.se)
tsv.rt = repltracker.NewReplTracker(tsv, alias)
tsv.lagThrottler = throttle.NewThrottler(tsv, srvTopoServer, topoServer, alias.Cell, tsv.rt.HeartbeatWriter(), tabletTypeFunc)
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, topoServer)
tsv.te = NewTxEngine(tsv)
tsv.messager = messager.NewEngine(tsv, tsv.se, tsv.vstreamer)
tsv.tableGC = gc.NewTableGC(tsv, topoServer, tsv.lagThrottler)
tsv.onlineDDLExecutor = onlineddl.NewExecutor(tsv, alias, topoServer, tsv.lagThrottler, tabletTypeFunc, tsv.onlineDDLExecutorToggleTableBuffer, tsv.tableGC.RequestChecks)
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.checkMysqlGaugeFunc = tsv.exporter.NewGaugeFunc("CheckMySQLRunning", "Check MySQL operation currently in progress", tsv.sm.isCheckMySQLRunning)
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.loadQueryTimeout)
tsv.registerHealthzHealthHandler()
tsv.registerDebugHealthHandler()
tsv.registerQueryzHandler()
tsv.registerQuerylogzHandler()
tsv.registerTxlogzHandler()
tsv.registerQueryListHandlers([]*QueryList{tsv.statelessql, tsv.statefulql, tsv.olapql})
tsv.registerTwopczHandler()
tsv.registerMigrationStatusHandler()
tsv.registerThrottlerHandlers()
tsv.registerDebugEnvHandler()
return tsv
}
func (tsv *TabletServer) loadQueryTimeout() time.Duration {
return time.Duration(tsv.QueryTimeout.Load())
}
// onlineDDLExecutorToggleTableBuffer is called by onlineDDLExecutor as a callback function. onlineDDLExecutor
// uses it to start/stop query buffering for a given table.
// It is onlineDDLExecutor's responsibility to make sure buffering is stopped after some definite amount of time.
// There are two layers to buffering/unbuffering:
// 1. the creation and destruction of a QueryRuleSource. The existence of such source affects query plan rules
// for all new queries (see Execute() function and call to GetPlan())
// 2. affecting already existing rules: a Rule has a context.WithCancel, that is cancelled by onlineDDLExecutor
func (tsv *TabletServer) onlineDDLExecutorToggleTableBuffer(bufferingCtx context.Context, tableName string, timeout time.Duration, bufferQueries bool) {
queryRuleSource := fmt.Sprintf("onlineddl/%s", tableName)
if bufferQueries {
tsv.RegisterQueryRuleSource(queryRuleSource)
bufferRules := rules.New()
bufferRules.Add(rules.NewBufferedTableQueryRule(bufferingCtx, tableName, timeout, "buffered for cut-over"))
tsv.SetQueryRules(queryRuleSource, bufferRules)
} else {
tsv.UnRegisterQueryRuleSource(queryRuleSource) // new rules will not have buffering. Existing rules will be affected by bufferingContext.Done()
}
}
// 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 = target.CloneVT()
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
}
// Environment satisfies tabletenv.Env.
func (tsv *TabletServer) Environment() *vtenv.Environment {
return tsv.env
}
// 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, ptsTimestamp time.Time, serving bool, reason string) error {
state := StateNotServing
if serving {
state = StateServing
}
return tsv.sm.SetServingType(tabletType, ptsTimestamp, 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, _, _, _ []*schema.Table) {
onSchemaChange <- struct{}{}
}, true)
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
}
// 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) (state queryservice.TransactionState, err error) {
return tsv.begin(ctx, target, nil, 0, nil, options)
}
func (tsv *TabletServer) begin(ctx context.Context, target *querypb.Target, savepointQueries []string, reservedID int64, settings []string, options *querypb.ExecuteOptions) (state queryservice.TransactionState, err error) {
state.TabletAlias = tsv.alias
err = tsv.execRequest(
ctx, tsv.loadQueryTimeout(),
"Begin", "begin", nil,
target, options, false, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
startTime := time.Now()
if tsv.txThrottler.Throttle(tsv.getPriorityFromOptions(options), options.GetWorkloadName()) {
return errTxThrottled
}
var connSetting *smartconnpool.Setting
if len(settings) > 0 {
connSetting, err = tsv.qe.GetConnSetting(ctx, settings)
if err != nil {
return err
}
}
transactionID, beginSQL, sessionStateChanges, err := tsv.te.Begin(ctx, savepointQueries, reservedID, connSetting, options)
state.TransactionID = transactionID
state.SessionStateChanges = sessionStateChanges
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)
targetType, err := tsv.resolveTargetType(ctx, target)
if err != nil {
return err
}
tsv.stats.QueryTimingsByTabletType.Record(targetType.String(), startTime)
} else {
logStats.Method = ""
}
return err
},
)
return state, err
}
func (tsv *TabletServer) getPriorityFromOptions(options *querypb.ExecuteOptions) int {
priority := tsv.config.TxThrottlerDefaultPriority
if options == nil {
return priority
}
if options.Priority == "" {
return priority
}
optionsPriority, err := strconv.Atoi(options.Priority)
// This should never error out, as the value for Priority has been validated in the vtgate already.
// Still, handle it just to make sure.
if err != nil {
log.Errorf(
"The value of the %s query directive could not be converted to integer, using the "+
"default value. Error was: %s",
sqlparser.DirectivePriority, priority, err)
return priority
}
return optionsPriority
}
// resolveTargetType returns the appropriate target tablet type for a
// TabletServer request. If the caller has a local context then it's
// an internal request and the target is the local tablet's current
// target. If it's not a local context then there should always be a
// non-nil target specified.
func (tsv *TabletServer) resolveTargetType(ctx context.Context, target *querypb.Target) (topodatapb.TabletType, error) {
if target != nil {
return target.TabletType, nil
}
if !tabletenv.IsLocalContext(ctx) {
return topodatapb.TabletType_UNKNOWN, ErrNoTarget
}
if tsv.sm.Target() == nil {
return topodatapb.TabletType_UNKNOWN, nil // This is true, and does not block the request
}
return tsv.sm.Target().TabletType, nil
}
// 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.loadQueryTimeout(),
"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)
targetType, err := tsv.resolveTargetType(ctx, target)
if err != nil {
return err
}
tsv.stats.QueryTimingsByTabletType.Record(targetType.String(), 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.loadQueryTimeout(),
"Rollback", "rollback", nil,
target, nil, true, /* allowOnShutdown */
func(ctx context.Context, logStats *tabletenv.LogStats) error {
defer tsv.stats.QueryTimings.Record("ROLLBACK", time.Now())
targetType, err := tsv.resolveTargetType(ctx, target)
if err != nil {
return err
}
defer tsv.stats.QueryTimingsByTabletType.Record(targetType.String(), 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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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.loadQueryTimeout(),
"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")
}
return tsv.execute(ctx, target, sql, bindVariables, transactionID, reservedID, nil, options)
}
func (tsv *TabletServer) execute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, reservedID int64, settings []string, options *querypb.ExecuteOptions) (result *sqltypes.Result, err error) {
allowOnShutdown := false
timeout := tsv.loadQueryTimeout()
if transactionID != 0 {
allowOnShutdown = true
// Execute calls happen for OLTP only, so we can directly fetch the
// OLTP TX timeout.
txTimeout := tsv.config.TxTimeoutForWorkload(querypb.ExecuteOptions_OLTP)
// 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, txTimeout)
}
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))
if err != nil {
return err
}
if err = plan.IsValid(reservedID != 0, len(settings) > 0); 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
var connSetting *smartconnpool.Setting
if len(settings) > 0 {
connSetting, err = tsv.qe.GetConnSetting(ctx, settings)
if err != nil {
return err
}
}
targetType, err := tsv.resolveTargetType(ctx, target)
if err != nil {
return err
}
qre := &QueryExecutor{
query: query,
marginComments: comments,
bindVars: bindVariables,
connID: connID,
options: options,
plan: plan,
ctx: ctx,
logStats: logStats,
tsv: tsv,
targetTabletType: targetType,
setting: connSetting,
}
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
}
return min(t1, 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")
}
return tsv.streamExecute(ctx, target, sql, bindVariables, transactionID, reservedID, nil, options, callback)
}
func (tsv *TabletServer) streamExecute(ctx context.Context, target *querypb.Target, sql string, bindVariables map[string]*querypb.BindVariable, transactionID int64, reservedID int64, settings []string, options *querypb.ExecuteOptions, callback func(*sqltypes.Result) error) error {
allowOnShutdown := false
var timeout time.Duration
if transactionID != 0 {
allowOnShutdown = true
// Use the transaction timeout. StreamExecute calls happen for OLAP only,
// so we can directly fetch the OLAP TX timeout.
timeout = tsv.config.TxTimeoutForWorkload(querypb.ExecuteOptions_OLAP)
}
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)
plan, err := tsv.qe.GetStreamPlan(ctx, logStats, query, skipQueryPlanCache(options))
if err != nil {
return err
}
if err = plan.IsValid(reservedID != 0, len(settings) > 0); 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
var connSetting *smartconnpool.Setting
if len(settings) > 0 {
connSetting, err = tsv.qe.GetConnSetting(ctx, settings)
if err != nil {
return err
}
}
qre := &QueryExecutor{
query: query,
marginComments: comments,
bindVars: bindVariables,
connID: connID,
options: options,
plan: plan,
ctx: ctx,
logStats: logStats,
tsv: tsv,
targetTabletType: target.GetTabletType(),
setting: connSetting,
}
return qre.Stream(callback)
},
)
}
// 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) (queryservice.TransactionState, *sqltypes.Result, 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 queryservice.TransactionState{}, nil, err
}
if txDone != nil {
defer txDone()
}
}
state, err := tsv.begin(ctx, target, preQueries, reservedID, nil, options)
if err != nil {
return state, nil, err
}
result, err := tsv.Execute(ctx, target, sql, bindVariables, state.TransactionID, reservedID, options)
return state, result, 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,