forked from vitessio/vitess
-
Notifications
You must be signed in to change notification settings - Fork 13
/
tabletserver.go
1068 lines (958 loc) · 32.9 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 2012, Google Inc. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package tabletserver
import (
"fmt"
"math/rand"
"net/http"
"strings"
"sync"
"time"
log "github.com/golang/glog"
"github.com/youtube/vitess/go/acl"
"github.com/youtube/vitess/go/mysql"
mproto "github.com/youtube/vitess/go/mysql/proto"
"github.com/youtube/vitess/go/stats"
"github.com/youtube/vitess/go/sync2"
"github.com/youtube/vitess/go/tb"
"github.com/youtube/vitess/go/vt/dbconfigs"
"github.com/youtube/vitess/go/vt/dbconnpool"
"github.com/youtube/vitess/go/vt/mysqlctl"
"github.com/youtube/vitess/go/vt/tabletserver/proto"
"github.com/youtube/vitess/go/vt/tabletserver/queryservice"
"golang.org/x/net/context"
pb "github.com/youtube/vitess/go/vt/proto/query"
"github.com/youtube/vitess/go/vt/proto/topodata"
"github.com/youtube/vitess/go/vt/proto/vtrpc"
)
const (
// StateNotConnected is the state where tabletserver is not
// connected to an underlying mysql instance.
StateNotConnected = iota
// StateNotServing is the state where tabletserver is connected
// to an underlying mysql instance, but is not serving queries.
StateNotServing
// StateServing is where queries are allowed.
StateServing
// StateTransitioning is a transient state indicating that
// the tabletserver is tranisitioning to a new state.
StateTransitioning
// StateShuttingDown is a transient state indicating that
// the tabletserver is shutting down. This state differs from
// StateTransitioning because we allow queries for transactions
// that are still in flight.
StateShuttingDown
)
// stateName names every state. The number of elements must
// match the number of states. Names can overlap.
var stateName = []string{
"NOT_SERVING",
"NOT_SERVING",
"SERVING",
"NOT_SERVING",
"SHUTTING_DOWN",
}
// TabletServer implements the RPC interface for the query service.
type TabletServer struct {
// config contains the original config values. TabletServer
// contains variables that are derived from the original config
// that can be subsequently changed. So, they may not always
// correspond to the original values.
config Config
QueryTimeout sync2.AtomicDuration
BeginTimeout sync2.AtomicDuration
// mu is used to access state. The lock should only be held
// for short periods. For longer periods, you have to transition
// the state to a transient value and release the lock.
// Once the operation is complete, you can then transition
// the state back to a stable value.
// Only the function that moved the state to a transient one is
// allowed to change it to a stable value.
mu sync.Mutex
state int64
requests sync.WaitGroup
// The following variables should be initialized only once
// before starting the tabletserver. For backward compatibility,
// we temporarily allow them to be changed until the migration
// to the new API is complete.
target *pb.Target
dbconfigs *dbconfigs.DBConfigs
schemaOverrides []SchemaOverride
mysqld mysqlctl.MysqlDaemon
// The following variables should only be accessed within
// the context of a startRequest-endRequest.
qe *QueryEngine
invalidator *RowcacheInvalidator
sessionID int64
// checkMySQLThrottler is used to throttle the number of
// requests sent to CheckMySQL.
checkMySQLThrottler *sync2.Semaphore
// streamHealthMutex protects all the following fields
streamHealthMutex sync.Mutex
streamHealthIndex int
streamHealthMap map[int]chan<- *pb.StreamHealthResponse
lastStreamHealthResponse *pb.StreamHealthResponse
}
// RegisterFunction is a callback type to be called when we
// Register() a TabletServer
type RegisterFunction func(Controller)
// RegisterFunctions is a list of all the
// RegisterFunction that will be called upon
// Register() on a TabletServer
var RegisterFunctions []RegisterFunction
// MySQLChecker defines the CheckMySQL interface that lower
// level objects can use to call back into TabletServer.
type MySQLChecker interface {
CheckMySQL()
}
// NewTabletServer creates an instance of TabletServer. Only one instance
// of TabletServer can be created per process.
func NewTabletServer(config Config) *TabletServer {
tsv := &TabletServer{
config: config,
QueryTimeout: sync2.NewAtomicDuration(time.Duration(config.QueryTimeout * 1e9)),
BeginTimeout: sync2.NewAtomicDuration(time.Duration(config.TxPoolTimeout * 1e9)),
checkMySQLThrottler: sync2.NewSemaphore(1, 0),
streamHealthMap: make(map[int]chan<- *pb.StreamHealthResponse),
sessionID: Rand(),
}
tsv.qe = NewQueryEngine(tsv, config)
tsv.invalidator = NewRowcacheInvalidator(config.StatsPrefix, tsv, tsv.qe, config.EnablePublishStats)
if config.EnablePublishStats {
stats.Publish(config.StatsPrefix+"TabletState", stats.IntFunc(func() int64 {
tsv.mu.Lock()
state := tsv.state
tsv.mu.Unlock()
return state
}))
stats.Publish(config.StatsPrefix+"QueryTimeout", stats.DurationFunc(tsv.QueryTimeout.Get))
stats.Publish(config.StatsPrefix+"BeginTimeout", stats.DurationFunc(tsv.BeginTimeout.Get))
stats.Publish(config.StatsPrefix+"TabletStateName", stats.StringFunc(tsv.GetState))
}
return tsv
}
// Register prepares TabletServer for serving by calling
// all the registrations functions.
func (tsv *TabletServer) Register() {
for _, f := range RegisterFunctions {
f(tsv)
}
tsv.registerDebugHealthHandler()
tsv.registerQueryzHandler()
tsv.registerSchemazHandler()
tsv.registerStreamQueryzHandlers()
}
// RegisterQueryRuleSource registers ruleSource for setting query rules.
func (tsv *TabletServer) RegisterQueryRuleSource(ruleSource string) {
tsv.qe.schemaInfo.queryRuleSources.RegisterQueryRuleSource(ruleSource)
}
// UnRegisterQueryRuleSource unregisters ruleSource from query rules.
func (tsv *TabletServer) UnRegisterQueryRuleSource(ruleSource string) {
tsv.qe.schemaInfo.queryRuleSources.UnRegisterQueryRuleSource(ruleSource)
}
// SetQueryRules sets the query rules for a registered ruleSource.
func (tsv *TabletServer) SetQueryRules(ruleSource string, qrs *QueryRules) error {
err := tsv.qe.schemaInfo.queryRuleSources.SetRules(ruleSource, qrs)
if err != nil {
return err
}
tsv.qe.schemaInfo.ClearQueryPlanCache()
return nil
}
// GetState returns the name of the current TabletServer state.
func (tsv *TabletServer) GetState() string {
tsv.mu.Lock()
name := stateName[tsv.state]
tsv.mu.Unlock()
return name
}
// setState changes the state and logs the event.
// It requires the caller to hold a lock on mu.
func (tsv *TabletServer) setState(state int64) {
log.Infof("TabletServer state: %v -> %v", stateName[tsv.state], stateName[state])
tsv.state = state
}
// IsServing returns true if TabletServer is in SERVING state.
func (tsv *TabletServer) IsServing() bool {
return tsv.GetState() == "SERVING"
}
// InitDBConfig inititalizes the db config variables for TabletServer. You must call this function before
// calling StartService or SetServingType.
func (tsv *TabletServer) InitDBConfig(target *pb.Target, dbconfigs *dbconfigs.DBConfigs, schemaOverrides []SchemaOverride, mysqld mysqlctl.MysqlDaemon) error {
tsv.mu.Lock()
defer tsv.mu.Unlock()
if tsv.state != StateNotConnected {
return NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "InitDBConfig failed, current state: %d", tsv.state)
}
tsv.target = target
tsv.dbconfigs = dbconfigs
tsv.schemaOverrides = schemaOverrides
tsv.mysqld = mysqld
return nil
}
// StartService starts the query service. It returns an
// error if the state is anything other than StateNotConnected.
// If it succeeds, the resulting state is StateServing.
// Otherwise, it reverts back to StateNotConnected.
func (tsv *TabletServer) StartService(target *pb.Target, dbconfigs *dbconfigs.DBConfigs, schemaOverrides []SchemaOverride, mysqld mysqlctl.MysqlDaemon) (err error) {
tsv.mu.Lock()
if tsv.state != StateNotConnected {
state := tsv.state
tsv.mu.Unlock()
return NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "cannot start tabletserver, current state: %d", state)
}
// Same as InitDBConfig
tsv.target = target
tsv.dbconfigs = dbconfigs
tsv.schemaOverrides = schemaOverrides
tsv.mysqld = mysqld
tsv.setState(StateTransitioning)
tsv.mu.Unlock()
return tsv.fullStart()
}
const (
actionNone = iota
actionFullStart
actionServeNewType
actionGracefulStop
)
// SetServingType changes the serving type of the tabletserver. It starts or
// stops internal services as deemed necessary.
func (tsv *TabletServer) SetServingType(tabletType topodata.TabletType, serving bool) error {
action, err := tsv.decideAction(tabletType, serving)
if err != nil {
return err
}
switch action {
case actionNone:
return nil
case actionFullStart:
return tsv.fullStart()
case actionServeNewType:
return tsv.serveNewType()
case actionGracefulStop:
tsv.gracefulStop()
return nil
}
panic("unreachable")
}
func (tsv *TabletServer) decideAction(tabletType topodata.TabletType, serving bool) (action int, err error) {
tsv.mu.Lock()
defer tsv.mu.Unlock()
if tsv.target == nil {
return actionNone, NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "cannot SetServingType if existing target is nil")
}
tsv.target.TabletType = tabletType
switch tsv.state {
case StateNotConnected:
if serving {
tsv.setState(StateTransitioning)
return actionFullStart, nil
}
case StateNotServing:
if serving {
tsv.setState(StateTransitioning)
return actionServeNewType, nil
}
case StateServing:
if !serving {
tsv.setState(StateShuttingDown)
return actionGracefulStop, nil
}
tsv.setState(StateTransitioning)
return actionServeNewType, nil
case StateTransitioning, StateShuttingDown:
return actionNone, NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "cannot SetServingType, current state: %s", tsv.state)
default:
panic("uncreachable")
}
return actionNone, nil
}
func (tsv *TabletServer) fullStart() (err error) {
defer func() {
if x := recover(); x != nil {
log.Errorf("Could not start tabletserver: %v", x)
tsv.qe.Close()
tsv.mu.Lock()
tsv.setState(StateNotConnected)
tsv.mu.Unlock()
err = x.(error)
}
}()
c, err := dbconnpool.NewDBConnection(&tsv.dbconfigs.App.ConnParams, tsv.qe.queryServiceStats.MySQLStats)
if err != nil {
panic(err)
}
c.Close()
tsv.qe.Open(tsv.dbconfigs, tsv.schemaOverrides)
return tsv.serveNewType()
}
func (tsv *TabletServer) serveNewType() (err error) {
defer func() {
if x := recover(); x != nil {
log.Errorf("Could not start tabletserver: %v", x)
tsv.qe.Close()
tsv.mu.Lock()
tsv.setState(StateNotConnected)
tsv.mu.Unlock()
err = x.(error)
}
}()
if needInvalidator(tsv.target, tsv.dbconfigs) {
tsv.invalidator.Open(tsv.dbconfigs.App.DbName, tsv.mysqld)
} else {
tsv.invalidator.Close()
}
tsv.sessionID = Rand()
log.Infof("Session id: %d", tsv.sessionID)
tsv.mu.Lock()
tsv.setState(StateServing)
tsv.mu.Unlock()
return nil
}
// needInvalidator returns true if the rowcache invalidator needs to be enabled.
func needInvalidator(target *pb.Target, dbconfigs *dbconfigs.DBConfigs) bool {
if !dbconfigs.App.EnableRowcache {
return false
}
if target == nil {
return dbconfigs.App.EnableInvalidator
}
return target.TabletType != topodata.TabletType_MASTER
}
func (tsv *TabletServer) gracefulStop() {
defer close(tsv.setTimeBomb())
tsv.qe.WaitForTxEmpty()
tsv.qe.streamQList.TerminateAll()
tsv.requests.Wait()
tsv.mu.Lock()
tsv.setState(StateNotServing)
tsv.mu.Unlock()
}
// StopService shuts down the tabletserver to the uninitialized state.
// It first transitions to StateShuttingDown, then waits for existing
// transactions to complete. Once all transactions are resolved, it shuts
// down the rest of the services nad transitions to StateNotConnected.
func (tsv *TabletServer) StopService() {
defer close(tsv.setTimeBomb())
defer logError(tsv.qe.queryServiceStats)
tsv.mu.Lock()
if tsv.state != StateServing && tsv.state != StateNotServing {
tsv.mu.Unlock()
return
}
tsv.setState(StateShuttingDown)
tsv.mu.Unlock()
// Same as gracefulStop.
log.Infof("Executing graceful transition to NotServing")
tsv.qe.WaitForTxEmpty()
tsv.qe.streamQList.TerminateAll()
tsv.requests.Wait()
defer func() {
tsv.mu.Lock()
tsv.setState(StateNotConnected)
tsv.mu.Unlock()
}()
log.Infof("Shutting down query service")
tsv.invalidator.Close()
tsv.qe.Close()
tsv.sessionID = Rand()
}
func (tsv *TabletServer) setTimeBomb() chan struct{} {
done := make(chan struct{})
go func() {
qt := tsv.QueryTimeout.Get()
if qt == 0 {
return
}
tmr := time.NewTimer(10 * qt)
defer tmr.Stop()
select {
case <-tmr.C:
log.Fatal("Shutdown took too long. Crashing")
case <-done:
}
}()
return done
}
// IsHealthy returns nil 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 {
return tsv.Execute(
context.Background(),
nil,
&proto.Query{
Sql: "select 1 from dual",
SessionId: tsv.sessionID,
},
new(mproto.QueryResult),
)
}
// CheckMySQL initiates a check to see if MySQL is reachable.
// If not, it shuts down the query service. The check is rate-limited
// to no more than once per second.
func (tsv *TabletServer) CheckMySQL() {
if !tsv.checkMySQLThrottler.TryAcquire() {
return
}
go func() {
defer func() {
logError(tsv.qe.queryServiceStats)
time.Sleep(1 * time.Second)
tsv.checkMySQLThrottler.Release()
}()
if tsv.isMySQLReachable() {
return
}
log.Info("Check MySQL failed. Shutting down query service")
tsv.StopService()
}()
}
// isMySQLReachable returns true if we can connect to MySQL.
// The function returns false only if the query service is
// in StateServing or StateNotServing.
func (tsv *TabletServer) isMySQLReachable() bool {
tsv.mu.Lock()
switch tsv.state {
case StateServing:
// Prevent transition out of this state by
// reserving a request.
tsv.requests.Add(1)
defer tsv.requests.Done()
case StateNotServing:
// Prevent transition out of this state by
// temporarily switching to StateTransitioning.
tsv.setState(StateTransitioning)
defer func() {
tsv.mu.Lock()
tsv.setState(StateNotServing)
tsv.mu.Unlock()
}()
default:
tsv.mu.Unlock()
return true
}
tsv.mu.Unlock()
return tsv.qe.IsMySQLReachable()
}
// ReloadSchema reloads the schema.
// If the query service is not running, it's a no-op.
func (tsv *TabletServer) ReloadSchema() {
defer logError(tsv.qe.queryServiceStats)
tsv.qe.schemaInfo.triggerReload()
}
// QueryService returns the QueryService part of TabletServer.
func (tsv *TabletServer) QueryService() queryservice.QueryService {
return tsv
}
// GetSessionId returns a sessionInfo response if the state is StateServing.
func (tsv *TabletServer) GetSessionId(sessionParams *proto.SessionParams, sessionInfo *proto.SessionInfo) error {
tsv.mu.Lock()
defer tsv.mu.Unlock()
if tsv.state != StateServing {
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "operation not allowed in state %s", stateName[tsv.state])
}
if sessionParams.Keyspace != tsv.dbconfigs.App.Keyspace {
return NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "Keyspace mismatch, expecting %v, received %v", tsv.dbconfigs.App.Keyspace, sessionParams.Keyspace)
}
if strings.ToLower(sessionParams.Shard) != strings.ToLower(tsv.dbconfigs.App.Shard) {
return NewTabletError(ErrFatal, vtrpc.ErrorCode_INTERNAL_ERROR, "Shard mismatch, expecting %v, received %v", tsv.dbconfigs.App.Shard, sessionParams.Shard)
}
sessionInfo.SessionId = tsv.sessionID
return nil
}
// Begin starts a new transaction. This is allowed only if the state is StateServing.
func (tsv *TabletServer) Begin(ctx context.Context, target *pb.Target, session *proto.Session, txInfo *proto.TransactionInfo) (err error) {
logStats := newLogStats("Begin", ctx)
logStats.OriginalSQL = "begin"
defer handleError(&err, logStats, tsv.qe.queryServiceStats)
if err = tsv.startRequest(target, session.SessionId, false); err != nil {
return err
}
ctx, cancel := withTimeout(ctx, tsv.BeginTimeout.Get())
defer func() {
tsv.qe.queryServiceStats.QueryStats.Record("BEGIN", time.Now())
cancel()
tsv.endRequest()
}()
txInfo.TransactionId = tsv.qe.txPool.Begin(ctx)
logStats.TransactionID = txInfo.TransactionId
return nil
}
// Commit commits the specified transaction.
func (tsv *TabletServer) Commit(ctx context.Context, target *pb.Target, session *proto.Session) (err error) {
logStats := newLogStats("Commit", ctx)
logStats.OriginalSQL = "commit"
logStats.TransactionID = session.TransactionId
defer handleError(&err, logStats, tsv.qe.queryServiceStats)
if err = tsv.startRequest(target, session.SessionId, true); err != nil {
return err
}
ctx, cancel := withTimeout(ctx, tsv.QueryTimeout.Get())
defer func() {
tsv.qe.queryServiceStats.QueryStats.Record("COMMIT", time.Now())
cancel()
tsv.endRequest()
}()
tsv.qe.Commit(ctx, logStats, session.TransactionId)
return nil
}
// Rollback rollsback the specified transaction.
func (tsv *TabletServer) Rollback(ctx context.Context, target *pb.Target, session *proto.Session) (err error) {
logStats := newLogStats("Rollback", ctx)
logStats.OriginalSQL = "rollback"
logStats.TransactionID = session.TransactionId
defer handleError(&err, logStats, tsv.qe.queryServiceStats)
if err = tsv.startRequest(target, session.SessionId, true); err != nil {
return err
}
ctx, cancel := withTimeout(ctx, tsv.QueryTimeout.Get())
defer func() {
tsv.qe.queryServiceStats.QueryStats.Record("ROLLBACK", time.Now())
cancel()
tsv.endRequest()
}()
tsv.qe.txPool.Rollback(ctx, session.TransactionId)
return nil
}
// handleExecError handles panics during query execution and sets
// the supplied error return value.
func (tsv *TabletServer) handleExecError(query *proto.Query, err *error, logStats *LogStats) {
if x := recover(); x != nil {
*err = tsv.handleExecErrorNoPanic(query, x, logStats)
}
if logStats != nil {
logStats.Send()
}
}
func (tsv *TabletServer) handleExecErrorNoPanic(query *proto.Query, err interface{}, logStats *LogStats) error {
var terr *TabletError
defer func() {
if logStats != nil {
logStats.Error = terr
}
}()
terr, ok := err.(*TabletError)
if !ok {
log.Errorf("Uncaught panic for %v:\n%v\n%s", query, err, tb.Stack(4))
tsv.qe.queryServiceStats.InternalErrors.Add("Panic", 1)
terr = NewTabletError(ErrFail, vtrpc.ErrorCode_UNKNOWN_ERROR, "%v: uncaught panic for %v", err, query)
return terr
}
var myError error
if tsv.config.TerseErrors && terr.SQLError != 0 && len(query.BindVariables) != 0 {
myError = fmt.Errorf("%s(errno %d) during query: %s", terr.Prefix(), terr.SQLError, query.Sql)
} else {
myError = terr
}
terr.RecordStats(tsv.qe.queryServiceStats)
logMethod := log.Warningf
// Suppress or demote some errors in logs
switch terr.ErrorType {
case ErrRetry, ErrTxPoolFull:
return myError
case ErrFatal:
logMethod = log.Errorf
}
// We want to suppress/demote some MySQL error codes (regardless of the ErrorType)
switch terr.SQLError {
case mysql.ErrDupEntry:
return myError
case mysql.ErrLockWaitTimeout, mysql.ErrLockDeadlock, mysql.ErrDataTooLong, mysql.ErrDataOutOfRange:
logMethod = log.Infof
case 0:
if strings.Contains(terr.Error(), "Row count exceeded") {
logMethod = log.Infof
}
}
logMethod("%v: %v", terr, query)
return myError
}
// Execute executes the query and returns the result as response.
func (tsv *TabletServer) Execute(ctx context.Context, target *pb.Target, query *proto.Query, reply *mproto.QueryResult) (err error) {
logStats := newLogStats("Execute", ctx)
defer tsv.handleExecError(query, &err, logStats)
allowShutdown := (query.TransactionId != 0)
if err = tsv.startRequest(target, query.SessionId, allowShutdown); err != nil {
return err
}
ctx, cancel := withTimeout(ctx, tsv.QueryTimeout.Get())
defer func() {
cancel()
tsv.endRequest()
}()
if query.BindVariables == nil {
query.BindVariables = make(map[string]interface{})
}
stripTrailing(query)
qre := &QueryExecutor{
query: query.Sql,
bindVars: query.BindVariables,
transactionID: query.TransactionId,
plan: tsv.qe.schemaInfo.GetPlan(ctx, logStats, query.Sql),
ctx: ctx,
logStats: logStats,
qe: tsv.qe,
tsv: tsv,
}
result, err := qre.Execute()
if err != nil {
return tsv.handleExecErrorNoPanic(query, err, logStats)
}
*reply = *result
return nil
}
// 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 *pb.Target, query *proto.Query, sendReply func(*mproto.QueryResult) error) (err error) {
// check cases we don't handle yet
if query.TransactionId != 0 {
return NewTabletError(ErrFail, vtrpc.ErrorCode_BAD_INPUT, "Transactions not supported with streaming")
}
logStats := newLogStats("StreamExecute", ctx)
defer tsv.handleExecError(query, &err, logStats)
if err = tsv.startRequest(target, query.SessionId, false); err != nil {
return err
}
defer tsv.endRequest()
if query.BindVariables == nil {
query.BindVariables = make(map[string]interface{})
}
stripTrailing(query)
qre := &QueryExecutor{
query: query.Sql,
bindVars: query.BindVariables,
transactionID: query.TransactionId,
plan: tsv.qe.schemaInfo.GetStreamPlan(query.Sql),
ctx: ctx,
logStats: logStats,
qe: tsv.qe,
tsv: tsv,
}
err = qre.Stream(sendReply)
if err != nil {
return tsv.handleExecErrorNoPanic(query, err, logStats)
}
return nil
}
// 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.
func (tsv *TabletServer) ExecuteBatch(ctx context.Context, target *pb.Target, queryList *proto.QueryList, reply *proto.QueryResultList) (err error) {
if len(queryList.Queries) == 0 {
return NewTabletError(ErrFail, vtrpc.ErrorCode_BAD_INPUT, "Empty query list")
}
if queryList.AsTransaction && queryList.TransactionId != 0 {
return NewTabletError(ErrFail, vtrpc.ErrorCode_BAD_INPUT, "cannot start a new transaction in the scope of an existing one")
}
allowShutdown := (queryList.TransactionId != 0)
if err = tsv.startRequest(target, queryList.SessionId, allowShutdown); err != nil {
return err
}
defer tsv.endRequest()
defer handleError(&err, nil, tsv.qe.queryServiceStats)
session := proto.Session{
TransactionId: queryList.TransactionId,
SessionId: queryList.SessionId,
}
if queryList.AsTransaction {
var txInfo proto.TransactionInfo
if err = tsv.Begin(ctx, target, &session, &txInfo); err != nil {
return err
}
session.TransactionId = txInfo.TransactionId
// If transaction was not committed by the end, it means
// that there was an error, roll it back.
defer func() {
if session.TransactionId != 0 {
tsv.Rollback(ctx, target, &session)
}
}()
}
reply.List = make([]mproto.QueryResult, 0, len(queryList.Queries))
for _, bound := range queryList.Queries {
query := proto.Query{
Sql: bound.Sql,
BindVariables: bound.BindVariables,
TransactionId: session.TransactionId,
SessionId: session.SessionId,
}
var localReply mproto.QueryResult
if err = tsv.Execute(ctx, target, &query, &localReply); err != nil {
return err
}
reply.List = append(reply.List, localReply)
}
if queryList.AsTransaction {
if err = tsv.Commit(ctx, target, &session); err != nil {
session.TransactionId = 0
return err
}
session.TransactionId = 0
}
return nil
}
// SplitQuery splits a BoundQuery into smaller queries that return a subset of rows from the original query.
func (tsv *TabletServer) SplitQuery(ctx context.Context, target *pb.Target, req *proto.SplitQueryRequest, reply *proto.SplitQueryResult) (err error) {
logStats := newLogStats("SplitQuery", ctx)
defer handleError(&err, logStats, tsv.qe.queryServiceStats)
if err = tsv.startRequest(target, req.SessionID, false); err != nil {
return err
}
ctx, cancel := withTimeout(ctx, tsv.QueryTimeout.Get())
defer func() {
cancel()
tsv.endRequest()
}()
splitter := NewQuerySplitter(&(req.Query), req.SplitColumn, req.SplitCount, tsv.qe.schemaInfo)
err = splitter.validateQuery()
if err != nil {
return NewTabletError(ErrFail, vtrpc.ErrorCode_BAD_INPUT, "splitQuery: query validation error: %s, request: %#v", err, req)
}
defer func(start time.Time) {
addUserTableQueryStats(tsv.qe.queryServiceStats, ctx, splitter.tableName, "SplitQuery", int64(time.Now().Sub(start)))
}(time.Now())
qre := &QueryExecutor{
ctx: ctx,
logStats: logStats,
qe: tsv.qe,
tsv: tsv,
}
columnType, err := getColumnType(qre, splitter.splitColumn, splitter.tableName)
if err != nil {
return err
}
var pkMinMax *mproto.QueryResult
switch columnType {
case mproto.VT_TINY, mproto.VT_SHORT, mproto.VT_LONG, mproto.VT_LONGLONG, mproto.VT_INT24, mproto.VT_FLOAT, mproto.VT_DOUBLE:
pkMinMax, err = getColumnMinMax(qre, splitter.splitColumn, splitter.tableName)
if err != nil {
return err
}
}
reply.Queries, err = splitter.split(columnType, pkMinMax)
if err != nil {
return NewTabletError(ErrFail, vtrpc.ErrorCode_BAD_INPUT, "splitQuery: query split error: %s, request: %#v", err, req)
}
return nil
}
// StreamHealthRegister is part of queryservice.QueryService interface
func (tsv *TabletServer) StreamHealthRegister(c chan<- *pb.StreamHealthResponse) (int, error) {
tsv.streamHealthMutex.Lock()
defer tsv.streamHealthMutex.Unlock()
id := tsv.streamHealthIndex
tsv.streamHealthIndex++
tsv.streamHealthMap[id] = c
if tsv.lastStreamHealthResponse != nil {
c <- tsv.lastStreamHealthResponse
}
return id, nil
}
// StreamHealthUnregister is part of queryservice.QueryService interface
func (tsv *TabletServer) StreamHealthUnregister(id int) error {
tsv.streamHealthMutex.Lock()
defer tsv.streamHealthMutex.Unlock()
delete(tsv.streamHealthMap, id)
return nil
}
// HandlePanic is part of the queryservice.QueryService interface
func (tsv *TabletServer) HandlePanic(err *error) {
if x := recover(); x != nil {
*err = fmt.Errorf("uncaught panic: %v", x)
}
}
// BroadcastHealth will broadcast the current health to all listeners
func (tsv *TabletServer) BroadcastHealth(terTimestamp int64, stats *pb.RealtimeStats) {
shr := &pb.StreamHealthResponse{
Target: tsv.target,
TabletExternallyReparentedTimestamp: terTimestamp,
RealtimeStats: stats,
}
tsv.streamHealthMutex.Lock()
defer tsv.streamHealthMutex.Unlock()
for _, c := range tsv.streamHealthMap {
// do not block on any write
select {
case c <- shr:
default:
}
}
tsv.lastStreamHealthResponse = shr
}
// startRequest validates the current state and sessionID and registers
// the request (a waitgroup) as started. Every startRequest requires one
// and only one corresponding endRequest. When the service shuts down,
// StopService will wait on this waitgroup to ensure that there are
// no requests in flight.
func (tsv *TabletServer) startRequest(target *pb.Target, sessionID int64, allowShutdown bool) (err error) {
tsv.mu.Lock()
defer tsv.mu.Unlock()
if tsv.state == StateServing {
goto verifySession
}
if allowShutdown && tsv.state == StateShuttingDown {
goto verifySession
}
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "operation not allowed in state %s", stateName[tsv.state])
verifySession:
if target != nil && tsv.target != nil {
// a valid target can be used instead of a valid session
if target.Keyspace != tsv.target.Keyspace {
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "Invalid keyspace %v", target.Keyspace)
}
if target.Shard != tsv.target.Shard {
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "Invalid shard %v", target.Shard)
}
if target.TabletType != tsv.target.TabletType {
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "Invalid tablet type %v", target.TabletType)
}
goto ok
}
if sessionID != tsv.sessionID {
return NewTabletError(ErrRetry, vtrpc.ErrorCode_QUERY_NOT_SERVED, "Invalid session Id %v", sessionID)
}
ok:
tsv.requests.Add(1)
return nil
}
// endRequest unregisters the current request (a waitgroup) as done.
func (tsv *TabletServer) endRequest() {
tsv.requests.Done()
}
func (tsv *TabletServer) 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 := tsv.IsHealthy(); err != nil {
w.Write([]byte("not ok"))
return
}
w.Write([]byte("ok"))
})
}
func (tsv *TabletServer) registerQueryzHandler() {
http.HandleFunc("/queryz", func(w http.ResponseWriter, r *http.Request) {
queryzHandler(tsv.qe.schemaInfo, w, r)
})
}
func (tsv *TabletServer) registerStreamQueryzHandlers() {
http.HandleFunc("/streamqueryz", func(w http.ResponseWriter, r *http.Request) {
streamQueryzHandler(tsv.qe.streamQList, w, r)
})
http.HandleFunc("/streamqueryz/terminate", func(w http.ResponseWriter, r *http.Request) {
streamQueryzTerminateHandler(tsv.qe.streamQList, w, r)
})
}
func (tsv *TabletServer) registerSchemazHandler() {
http.HandleFunc("/schemaz", func(w http.ResponseWriter, r *http.Request) {
schemazHandler(tsv.qe.schemaInfo.GetSchema(), w, r)
})
}
// SetPoolSize changes the pool size to the specified value.
func (tsv *TabletServer) SetPoolSize(val int) {
tsv.qe.connPool.SetCapacity(val)
}
// PoolSize returns the pool size.
func (tsv *TabletServer) PoolSize() int {
return int(tsv.qe.connPool.Capacity())
}
// SetTxPoolSize changes the tx pool size to the specified value.
func (tsv *TabletServer) SetTxPoolSize(val int) {
tsv.qe.txPool.pool.SetCapacity(val)
}
// TxPoolSize returns the tx pool size.
func (tsv *TabletServer) TxPoolSize() int {
return int(tsv.qe.txPool.pool.Capacity())
}
// SetTxTimeout changes the transaction timeout to the specified value.
func (tsv *TabletServer) SetTxTimeout(val time.Duration) {
tsv.qe.txPool.SetTimeout(val)
}
// TxTimeout returns the transaction timeout.
func (tsv *TabletServer) TxTimeout() time.Duration {
return tsv.qe.txPool.Timeout()
}
// SetQueryCacheCap changes the pool size to the specified value.
func (tsv *TabletServer) SetQueryCacheCap(val int) {
tsv.qe.schemaInfo.SetQueryCacheCap(val)
}
// QueryCacheCap returns the pool size.
func (tsv *TabletServer) QueryCacheCap() int {
return int(tsv.qe.schemaInfo.QueryCacheCap())
}
// SetStrictMode sets strict mode on or off.
func (tsv *TabletServer) SetStrictMode(strict bool) {
if strict {
tsv.qe.strictMode.Set(1)
} else {
tsv.qe.strictMode.Set(0)
}
}
// SetMaxResultSize changes the max result size to the specified value.