-
Notifications
You must be signed in to change notification settings - Fork 209
/
region_request.go
1883 lines (1729 loc) · 62 KB
/
region_request.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 2021 TiKV 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.
// NOTE: The code in this file is based on code from the
// TiDB project, licensed under the Apache License v 2.0
//
// https://github.com/pingcap/tidb/tree/cc5e161ac06827589c4966674597c137cc9e809c/store/tikv/locate/region_request.go
//
// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package locate
import (
"context"
"fmt"
"maps"
"math/rand"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/kvproto/pkg/coprocessor"
"github.com/pingcap/kvproto/pkg/errorpb"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pkg/errors"
"github.com/tikv/client-go/v2/config/retry"
tikverr "github.com/tikv/client-go/v2/error"
"github.com/tikv/client-go/v2/internal/client"
"github.com/tikv/client-go/v2/internal/logutil"
"github.com/tikv/client-go/v2/kv"
"github.com/tikv/client-go/v2/metrics"
"github.com/tikv/client-go/v2/tikvrpc"
"github.com/tikv/client-go/v2/util"
pderr "github.com/tikv/pd/client/errs"
)
// shuttingDown is a flag to indicate tidb-server is exiting (Ctrl+C signal
// receved for example). If this flag is set, tikv client should not retry on
// network error because tidb-server expect tikv client to exit as soon as possible.
var shuttingDown uint32
// randIntn is only use for testing.
var randIntn = rand.Intn
// StoreShuttingDown atomically stores ShuttingDown into v.
func StoreShuttingDown(v uint32) {
atomic.StoreUint32(&shuttingDown, v)
}
// LoadShuttingDown atomically loads ShuttingDown.
func LoadShuttingDown() uint32 {
return atomic.LoadUint32(&shuttingDown)
}
// RegionRequestSender sends KV/Cop requests to tikv server. It handles network
// errors and some region errors internally.
//
// Typically, a KV/Cop request is bind to a region, all keys that are involved
// in the request should be located in the region.
// The sending process begins with looking for the address of leader store's
// address of the target region from cache, and the request is then sent to the
// destination tikv server over TCP connection.
// If region is updated, can be caused by leader transfer, region split, region
// merge, or region balance, tikv server may not able to process request and
// send back a RegionError.
// RegionRequestSender takes care of errors that does not relevant to region
// range, such as 'I/O timeout', 'NotLeader', and 'ServerIsBusy'. If fails to
// send the request to all replicas, a fake rregion error may be returned.
// Caller which receives the error should retry the request.
//
// For other region errors, since region range have changed, the request may need to
// split, so we simply return the error to caller.
type RegionRequestSender struct {
regionCache *RegionCache
apiVersion kvrpcpb.APIVersion
client client.Client
storeAddr string
rpcError error
replicaSelector *replicaSelector
failStoreIDs map[uint64]struct{}
failProxyStoreIDs map[uint64]struct{}
Stats *RegionRequestRuntimeStats
AccessStats *ReplicaAccessStats
}
func (s *RegionRequestSender) String() string {
if s.replicaSelector == nil {
return fmt.Sprintf("{rpcError:%v, replicaSelector: <nil>}", s.rpcError)
}
return fmt.Sprintf("{rpcError:%v, replicaSelector: %v}", s.rpcError, s.replicaSelector.String())
}
// RegionRequestRuntimeStats records the runtime stats of send region requests.
type RegionRequestRuntimeStats struct {
RPCStats map[tikvrpc.CmdType]*RPCRuntimeStats
RequestErrorStats
}
// RequestErrorStats records the request error(region error and rpc error) count.
type RequestErrorStats struct {
// ErrStats record the region error and rpc error, and their count.
// Attention: avoid too many error types, ErrStats only record the first 16 different errors.
ErrStats map[string]int
OtherErrCnt int
}
// NewRegionRequestRuntimeStats returns a new RegionRequestRuntimeStats.
func NewRegionRequestRuntimeStats() *RegionRequestRuntimeStats {
return &RegionRequestRuntimeStats{
RPCStats: make(map[tikvrpc.CmdType]*RPCRuntimeStats),
}
}
// RPCRuntimeStats indicates the RPC request count and consume time.
type RPCRuntimeStats struct {
Count int64
// Send region request consume time.
Consume int64
}
// RecordRPCRuntimeStats uses to record the rpc count and duration stats.
func (r *RegionRequestRuntimeStats) RecordRPCRuntimeStats(cmd tikvrpc.CmdType, d time.Duration) {
stat, ok := r.RPCStats[cmd]
if !ok {
r.RPCStats[cmd] = &RPCRuntimeStats{
Count: 1,
Consume: int64(d),
}
return
}
stat.Count++
stat.Consume += int64(d)
}
// RecordRPCErrorStats uses to record the request error(region error label and rpc error) info and count.
func (r *RequestErrorStats) RecordRPCErrorStats(errLabel string) {
if r.ErrStats == nil {
// lazy init to avoid unnecessary allocation.
r.ErrStats = make(map[string]int)
}
if len(r.ErrStats) < 16 {
// Avoid too many error.
r.ErrStats[errLabel]++
} else {
r.OtherErrCnt++
}
}
// getErrMsg returns error message. if the error has cause error, then return cause error message.
func getErrMsg(err error) string {
if err == nil {
return ""
}
if causeErr := errors.Cause(err); causeErr != nil {
return causeErr.Error()
}
return err.Error()
}
// String implements fmt.Stringer interface.
func (r *RegionRequestRuntimeStats) String() string {
if r == nil {
return ""
}
var builder strings.Builder
for k, v := range r.RPCStats {
if builder.Len() > 0 {
builder.WriteByte(',')
}
builder.WriteString(k.String())
builder.WriteString(":{num_rpc:")
builder.WriteString(strconv.FormatInt(v.Count, 10))
builder.WriteString(", total_time:")
builder.WriteString(util.FormatDuration(time.Duration(v.Consume)))
builder.WriteString("}")
}
if errStatsStr := r.RequestErrorStats.String(); errStatsStr != "" {
builder.WriteString(", rpc_errors:")
builder.WriteString(errStatsStr)
}
return builder.String()
}
// String implements fmt.Stringer interface.
func (r *RequestErrorStats) String() string {
if len(r.ErrStats) == 0 {
return ""
}
var builder strings.Builder
builder.WriteString("{")
for err, cnt := range r.ErrStats {
if builder.Len() > 2 {
builder.WriteString(", ")
}
builder.WriteString(err)
builder.WriteString(":")
builder.WriteString(strconv.Itoa(cnt))
}
if r.OtherErrCnt > 0 {
builder.WriteString(", other_error:")
builder.WriteString(strconv.Itoa(r.OtherErrCnt))
}
builder.WriteString("}")
return builder.String()
}
// Clone returns a copy of itself.
func (r *RegionRequestRuntimeStats) Clone() *RegionRequestRuntimeStats {
newRs := NewRegionRequestRuntimeStats()
maps.Copy(newRs.RPCStats, r.RPCStats)
if len(r.ErrStats) > 0 {
newRs.ErrStats = make(map[string]int)
maps.Copy(newRs.ErrStats, r.ErrStats)
newRs.OtherErrCnt = r.OtherErrCnt
}
return newRs
}
// Merge merges other RegionRequestRuntimeStats.
func (r *RegionRequestRuntimeStats) Merge(rs *RegionRequestRuntimeStats) {
if rs == nil {
return
}
for cmd, v := range rs.RPCStats {
stat, ok := r.RPCStats[cmd]
if !ok {
r.RPCStats[cmd] = &RPCRuntimeStats{
Count: v.Count,
Consume: v.Consume,
}
continue
}
stat.Count += v.Count
stat.Consume += v.Consume
}
if len(rs.ErrStats) > 0 {
if r.ErrStats == nil {
r.ErrStats = make(map[string]int)
}
for err, cnt := range rs.ErrStats {
r.ErrStats[err] += cnt
}
r.OtherErrCnt += rs.OtherErrCnt
}
}
// ReplicaAccessStats records the replica access info.
type ReplicaAccessStats struct {
// AccessInfos records the access info
AccessInfos []ReplicaAccessInfo
// avoid to consume too much memory, after more than 5 records, count them by peerID in `OverflowAccessStat` map.
OverflowAccessStat map[uint64]*RequestErrorStats
}
// ReplicaAccessInfo indicates the access path detail info of a request.
type ReplicaAccessInfo struct {
Peer uint64
Store uint64
ReqReadTp ReqReadType
Err string
}
type ReqReadType byte
const (
ReqLeader ReqReadType = iota
ReqReplicaRead
ReqStaleRead
)
func (s *ReplicaAccessStats) recordReplicaAccessInfo(staleRead, replicaRead bool, peerID, storeID uint64, err string) {
if len(s.AccessInfos) < 5 {
tp := ReqLeader
if replicaRead {
tp = ReqReplicaRead
} else if staleRead {
tp = ReqStaleRead
}
s.AccessInfos = append(s.AccessInfos, ReplicaAccessInfo{
Peer: peerID,
Store: storeID,
ReqReadTp: tp,
Err: err,
})
return
}
if s.OverflowAccessStat == nil {
s.OverflowAccessStat = make(map[uint64]*RequestErrorStats)
}
stat, ok := s.OverflowAccessStat[peerID]
if !ok {
stat = &RequestErrorStats{}
s.OverflowAccessStat[peerID] = stat
}
stat.RecordRPCErrorStats(err)
}
// String implements fmt.Stringer interface.
func (s *ReplicaAccessStats) String() string {
if s == nil {
return ""
}
var builder strings.Builder
for i, info := range s.AccessInfos {
if i > 0 {
builder.WriteString(", ")
}
switch info.ReqReadTp {
case ReqLeader:
builder.WriteString("{")
case ReqReplicaRead:
builder.WriteString("{replica_read, ")
case ReqStaleRead:
builder.WriteString("{stale_read, ")
}
builder.WriteString("peer:")
builder.WriteString(strconv.FormatUint(info.Peer, 10))
builder.WriteString(", store:")
builder.WriteString(strconv.FormatUint(info.Store, 10))
builder.WriteString(", err:")
builder.WriteString(info.Err)
builder.WriteString("}")
}
if len(s.OverflowAccessStat) > 0 {
builder.WriteString(", overflow_count:{")
cnt := 0
for peerID, stat := range s.OverflowAccessStat {
if stat == nil {
continue
}
if cnt > 0 {
builder.WriteString(", ")
}
builder.WriteString("{peer:")
builder.WriteString(strconv.FormatUint(peerID, 10))
builder.WriteString(", error_stats:")
builder.WriteString(stat.String())
builder.WriteString("}")
cnt++
}
builder.WriteString("}")
}
return builder.String()
}
// NewRegionRequestSender creates a new sender.
func NewRegionRequestSender(regionCache *RegionCache, client client.Client) *RegionRequestSender {
return &RegionRequestSender{
regionCache: regionCache,
apiVersion: regionCache.codec.GetAPIVersion(),
client: client,
}
}
// GetRegionCache returns the region cache.
func (s *RegionRequestSender) GetRegionCache() *RegionCache {
return s.regionCache
}
// GetClient returns the RPC client.
func (s *RegionRequestSender) GetClient() client.Client {
return s.client
}
// getClientExt returns the client with ClientExt interface.
// Return nil if the client does not implement ClientExt.
// Don't use in critical path.
func (s *RegionRequestSender) getClientExt() client.ClientExt {
ext, _ := s.client.(client.ClientExt)
return ext
}
// SetStoreAddr specifies the dest store address.
func (s *RegionRequestSender) SetStoreAddr(addr string) {
s.storeAddr = addr
}
// GetStoreAddr returns the dest store address.
func (s *RegionRequestSender) GetStoreAddr() string {
return s.storeAddr
}
// GetRPCError returns the RPC error.
func (s *RegionRequestSender) GetRPCError() error {
return s.rpcError
}
// SetRPCError rewrite the rpc error.
func (s *RegionRequestSender) SetRPCError(err error) {
s.rpcError = err
}
// SendReq sends a request to tikv server. If fails to send the request to all replicas,
// a fake region error may be returned. Caller which receives the error should retry the request.
// It also returns the times of retries in RPC layer. A positive retryTimes indicates a possible undetermined error.
func (s *RegionRequestSender) SendReq(
bo *retry.Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration,
) (*tikvrpc.Response, int, error) {
resp, _, retryTimes, err := s.SendReqCtx(bo, req, regionID, timeout, tikvrpc.TiKV)
return resp, retryTimes, err
}
func (s *RegionRequestSender) recordRPCAccessInfo(req *tikvrpc.Request, rpcCtx *RPCContext, err string) {
if req == nil || rpcCtx == nil || rpcCtx.Peer == nil || rpcCtx.Store == nil {
return
}
if s.AccessStats == nil {
s.AccessStats = &ReplicaAccessStats{}
}
s.AccessStats.recordReplicaAccessInfo(req.StaleRead, req.ReplicaRead, rpcCtx.Peer.GetId(), rpcCtx.Store.storeID, err)
}
type replica struct {
store *Store
peer *metapb.Peer
epoch uint32
attempts int
attemptedTime time.Duration
flag uint8
}
func (r *replica) getEpoch() uint32 {
return atomic.LoadUint32(&r.epoch)
}
func (r *replica) isEpochStale() bool {
return r.epoch != atomic.LoadUint32(&r.store.epoch)
}
func (r *replica) isExhausted(maxAttempt int, maxAttemptTime time.Duration) bool {
return r.attempts >= maxAttempt || (maxAttemptTime > 0 && r.attemptedTime >= maxAttemptTime)
}
func (r *replica) onUpdateLeader() {
if r.isExhausted(maxReplicaAttempt, maxReplicaAttemptTime) {
// Give the replica one more chance and because each follower is tried only once,
// it won't result in infinite retry.
r.attempts = maxReplicaAttempt - 1
r.attemptedTime = 0
}
r.deleteFlag(notLeaderFlag)
}
const (
deadlineErrUsingConfTimeoutFlag uint8 = 1 << iota // deadlineErrUsingConfTimeoutFlag indicates the replica is already tried, but the received deadline exceeded error.
dataIsNotReadyFlag // dataIsNotReadyFlag indicates the replica is already tried, but the received data is not ready error.
notLeaderFlag // notLeaderFlag indicates the replica is already tried, but the received not leader error.
serverIsBusyFlag // serverIsBusyFlag indicates the replica is already tried, but the received server is busy error.
)
func (r *replica) addFlag(flag uint8) {
r.flag |= flag
}
func (r *replica) deleteFlag(flag uint8) {
r.flag &= ^flag
}
func (r *replica) hasFlag(flag uint8) bool {
return (r.flag & flag) > 0
}
type baseReplicaSelector struct {
regionCache *RegionCache
region *Region
replicas []*replica
// TiKV can reject the request when its estimated wait duration exceeds busyThreshold.
// Then, the client will receive a ServerIsBusy error and choose another replica to retry.
busyThreshold time.Duration
// pendingBackoffs records the pending backoff by store_id for fast retry. Here are some examples to show how it works:
// Example-1, fast retry and success:
// 1. send req to store 1, got ServerIsBusy region error, record `store1 -> BoTiKVServerBusy` backoff in pendingBackoffs and fast retry next replica.
// 2. retry in store2, and success.
// Since the request is success, we can skip the backoff and fast return result to user.
// Example-2: fast retry different replicas but all failed:
// 1. send req to store 1, got ServerIsBusy region error, record `store1 -> BoTiKVServerBusy` backoff in pendingBackoffs and fast retry next replica.
// 2. send req to store 2, got ServerIsBusy region error, record `store2 -> BoTiKVServerBusy` backoff in pendingBackoffs and fast retry next replica.
// 3. send req to store 3, got ServerIsBusy region error, record `store3 -> BoTiKVServerBusy` backoff in pendingBackoffs and fast retry next replica.
// 4. no candidate since all stores are busy. But before return no candidate error to up layer, we need to call backoffOnNoCandidate function
// to apply a max pending backoff, the backoff is to avoid frequent access and increase the pressure on the cluster.
// Example-3: fast retry same replica:
// 1. send req to store 1, got ServerIsBusy region error, record `store1 -> BoTiKVServerBusy` backoff in pendingBackoffs and fast retry next replica.
// 2. assume store 2 and store 3 are unreachable.
// 3. re-send req to store 1 with replica-read. But before re-send to store1, we need to call backoffOnRetry function
// to apply pending BoTiKVServerBusy backoff, the backoff is to avoid frequent access and increase the pressure on the cluster.
pendingBackoffs map[uint64]*backoffArgs
}
func (s *baseReplicaSelector) String() string {
var replicaStatus []string
cacheRegionIsValid := "unknown"
if s != nil {
if s.region != nil {
if s.region.isValid() {
cacheRegionIsValid = "true"
} else {
cacheRegionIsValid = "false"
}
}
for _, replica := range s.replicas {
replicaStatus = append(replicaStatus, fmt.Sprintf("peer: %v, store: %v, isEpochStale: %v, "+
"attempts: %v, attempts_time: %v, replica-epoch: %v, store-epoch: %v, store-state: %v, store-liveness-state: %v",
replica.peer.GetId(),
replica.store.storeID,
replica.isEpochStale(),
replica.attempts,
util.FormatDuration(replica.attemptedTime),
replica.getEpoch(),
atomic.LoadUint32(&replica.store.epoch),
replica.store.getResolveState(),
replica.store.getLivenessState(),
))
}
}
return fmt.Sprintf("cacheRegionIsValid: %v, replicaStatus: %v", cacheRegionIsValid, replicaStatus)
}
const (
maxReplicaAttempt = 10
// The maximum time to allow retrying sending requests after RPC failure. In case an RPC request fails after
// timeout (there might be network issue or the TiKV node stuck), we use this to avoid retrying 10 times which may cost too much time.
// For request using `client.ReadTimeoutShort` which is 30s, it might retry twice which costs 1min.
maxReplicaAttemptTime = time.Second * 50
)
func (s *baseReplicaSelector) buildRPCContext(bo *retry.Backoffer, targetReplica, proxyReplica *replica) (*RPCContext, error) {
// Backoff and retry if no replica is selected or the selected replica is stale
if targetReplica == nil || targetReplica.isEpochStale() ||
(proxyReplica != nil && proxyReplica.isEpochStale()) {
// TODO(youjiali1995): Is it necessary to invalidate the region?
metrics.TiKVReplicaSelectorFailureCounter.WithLabelValues("stale_store").Inc()
s.invalidateRegion()
return nil, nil
}
rpcCtx := &RPCContext{
ClusterID: s.regionCache.clusterID,
Region: s.region.VerID(),
Meta: s.region.meta,
Peer: targetReplica.peer,
Store: targetReplica.store,
AccessMode: tiKVOnly,
TiKVNum: len(s.replicas),
}
// Set leader addr
addr, err := s.regionCache.getStoreAddr(bo, s.region, targetReplica.store)
if err != nil {
return nil, err
}
if len(addr) == 0 {
return nil, nil
}
rpcCtx.Addr = addr
targetReplica.attempts++
// Set proxy addr
if proxyReplica != nil {
addr, err = s.regionCache.getStoreAddr(bo, s.region, proxyReplica.store)
if err != nil {
return nil, err
}
if len(addr) == 0 {
return nil, nil
}
rpcCtx.ProxyStore = proxyReplica.store
rpcCtx.ProxyAddr = addr
proxyReplica.attempts++
}
return rpcCtx, nil
}
func (s *baseReplicaSelector) checkLiveness(bo *retry.Backoffer, accessReplica *replica) livenessState {
return accessReplica.store.requestLivenessAndStartHealthCheckLoopIfNeeded(bo, s.regionCache.bg, s.regionCache.stores)
}
func (s *baseReplicaSelector) invalidateReplicaStore(replica *replica, cause error) {
store := replica.store
if atomic.CompareAndSwapUint32(&store.epoch, replica.epoch, replica.epoch+1) {
logutil.BgLogger().Info(
"mark store's regions need be refill",
zap.Uint64("id", store.storeID),
zap.String("addr", store.addr),
zap.Error(cause),
)
metrics.RegionCacheCounterWithInvalidateStoreRegionsOK.Inc()
// schedule a store addr resolve.
s.regionCache.stores.markStoreNeedCheck(store)
store.healthStatus.markAlreadySlow()
}
}
// updateLeader updates the leader of the cached region.
// If the leader peer isn't found in the region, the region will be invalidated.
// If switch to new leader successfully, returns the AccessIndex of the new leader in the replicas.
func (s *baseReplicaSelector) updateLeader(leader *metapb.Peer) int {
if leader == nil {
return -1
}
for i, replica := range s.replicas {
if isSamePeer(replica.peer, leader) {
// If hibernate region is enabled and the leader is not reachable, the raft group
// will not be wakened up and re-elect the leader until the follower receives
// a request. So, before the new leader is elected, we should not send requests
// to the unreachable old leader to avoid unnecessary timeout.
if replica.store.getLivenessState() != reachable {
return -1
}
replica.onUpdateLeader()
// Update the workTiKVIdx so that following requests can be sent to the leader immediately.
if !s.region.switchWorkLeaderToPeer(leader) {
panic("the store must exist")
}
logutil.BgLogger().Debug(
"switch region leader to specific leader due to kv return NotLeader",
zap.Uint64("regionID", s.region.GetID()),
zap.Uint64("leaderStoreID", leader.GetStoreId()),
)
return i
}
}
// Invalidate the region since the new leader is not in the cached version.
s.region.invalidate(StoreNotFound)
return -1
}
func (s *baseReplicaSelector) invalidateRegion() {
if s.region != nil {
s.region.invalidate(Other)
}
}
func (s *RegionRequestSender) getRPCContext(
bo *retry.Backoffer,
req *tikvrpc.Request,
regionID RegionVerID,
et tikvrpc.EndpointType,
opts ...StoreSelectorOption,
) (*RPCContext, error) {
switch et {
case tikvrpc.TiKV:
if s.replicaSelector == nil {
selector, err := newReplicaSelector(s.regionCache, regionID, req, opts...)
if err != nil || selector == nil {
return nil, err
}
s.replicaSelector = selector
}
return s.replicaSelector.next(bo, req)
case tikvrpc.TiFlash:
// Should ignore WN, because in disaggregated tiflash mode, TiDB will build rpcCtx itself.
return s.regionCache.GetTiFlashRPCContext(bo, regionID, true, LabelFilterNoTiFlashWriteNode)
case tikvrpc.TiDB:
return &RPCContext{Addr: s.storeAddr}, nil
case tikvrpc.TiFlashCompute:
// In disaggregated tiflash mode, TiDB will build rpcCtx itself, so cannot reach here.
return nil, errors.Errorf("should not reach here for disaggregated tiflash mode")
default:
return nil, errors.Errorf("unsupported storage type: %v", et)
}
}
func (s *RegionRequestSender) reset() {
s.replicaSelector = nil
s.failStoreIDs = nil
s.failProxyStoreIDs = nil
}
// IsFakeRegionError returns true if err is fake region error.
func IsFakeRegionError(err *errorpb.Error) bool {
return err != nil && err.GetEpochNotMatch() != nil && len(err.GetEpochNotMatch().CurrentRegions) == 0
}
const slowLogSendReqTime = 100 * time.Millisecond
// SendReqCtx sends a request to tikv server and return response and RPCCtx of this RPC.
func (s *RegionRequestSender) SendReqCtx(
bo *retry.Backoffer,
req *tikvrpc.Request,
regionID RegionVerID,
timeout time.Duration,
et tikvrpc.EndpointType,
opts ...StoreSelectorOption,
) (
resp *tikvrpc.Response,
rpcCtx *RPCContext,
retryTimes int,
err error,
) {
if span := opentracing.SpanFromContext(bo.GetCtx()); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("regionRequest.SendReqCtx", opentracing.ChildOf(span.Context()))
defer span1.Finish()
bo.SetCtx(opentracing.ContextWithSpan(bo.GetCtx(), span1))
}
if val, err := util.EvalFailpoint("tikvStoreSendReqResult"); err == nil {
if s, ok := val.(string); ok {
switch s {
case "timeout":
return nil, nil, 0, errors.New("timeout")
case "GCNotLeader":
if req.Type == tikvrpc.CmdGC {
return &tikvrpc.Response{
Resp: &kvrpcpb.GCResponse{RegionError: &errorpb.Error{NotLeader: &errorpb.NotLeader{}}},
}, nil, 0, nil
}
case "PessimisticLockNotLeader":
if req.Type == tikvrpc.CmdPessimisticLock {
return &tikvrpc.Response{
Resp: &kvrpcpb.PessimisticLockResponse{RegionError: &errorpb.Error{NotLeader: &errorpb.NotLeader{}}},
}, nil, 0, nil
}
case "GCServerIsBusy":
if req.Type == tikvrpc.CmdGC {
return &tikvrpc.Response{
Resp: &kvrpcpb.GCResponse{RegionError: &errorpb.Error{ServerIsBusy: &errorpb.ServerIsBusy{}}},
}, nil, 0, nil
}
case "busy":
return &tikvrpc.Response{
Resp: &kvrpcpb.GCResponse{RegionError: &errorpb.Error{ServerIsBusy: &errorpb.ServerIsBusy{}}},
}, nil, 0, nil
case "requestTiDBStoreError":
if et == tikvrpc.TiDB {
return nil, nil, 0, errors.WithStack(tikverr.ErrTiKVServerTimeout)
}
case "requestTiFlashError":
if et == tikvrpc.TiFlash {
return nil, nil, 0, errors.WithStack(tikverr.ErrTiFlashServerTimeout)
}
}
}
}
// If the MaxExecutionDurationMs is not set yet, we set it to be the RPC timeout duration
// so TiKV can give up the requests whose response TiDB cannot receive due to timeout.
if req.Context.MaxExecutionDurationMs == 0 {
req.Context.MaxExecutionDurationMs = uint64(timeout.Milliseconds())
}
s.reset()
startTime := time.Now()
startBackOff := bo.GetTotalSleep()
retryTimes = 0
defer func() {
if retryTimes > 0 {
metrics.TiKVRequestRetryTimesHistogram.Observe(float64(retryTimes))
}
}()
var staleReadCollector *staleReadMetricsCollector
if req.StaleRead {
staleReadCollector = &staleReadMetricsCollector{}
defer func() {
if retryTimes == 0 {
metrics.StaleReadHitCounter.Add(1)
} else {
metrics.StaleReadMissCounter.Add(1)
}
}()
}
for {
if retryTimes > 0 {
if retryTimes%100 == 0 {
logutil.Logger(bo.GetCtx()).Warn(
"retry",
zap.Uint64("region", regionID.GetID()),
zap.Int("times", retryTimes),
)
}
}
rpcCtx, err = s.getRPCContext(bo, req, regionID, et, opts...)
if err != nil {
return nil, nil, retryTimes, err
}
if _, err := util.EvalFailpoint("invalidCacheAndRetry"); err == nil {
// cooperate with tikvclient/setGcResolveMaxBackoff
if c := bo.GetCtx().Value("injectedBackoff"); c != nil {
resp, err = tikvrpc.GenRegionErrorResp(req, &errorpb.Error{EpochNotMatch: &errorpb.EpochNotMatch{}})
return resp, nil, retryTimes, err
}
}
if rpcCtx == nil {
// TODO(youjiali1995): remove it when using the replica selector for all requests.
// If the region is not found in cache, it must be out
// of date and already be cleaned up. We can skip the
// RPC by returning RegionError directly.
// TODO: Change the returned error to something like "region missing in cache",
// and handle this error like EpochNotMatch, which means to re-split the request and retry.
if s.replicaSelector != nil {
if err := s.replicaSelector.backoffOnNoCandidate(bo); err != nil {
return nil, nil, retryTimes, err
}
if cost := time.Since(startTime); cost > slowLogSendReqTime || cost > timeout {
s.logSendReqError(bo, "throwing pseudo region error due to no replica available", regionID, retryTimes, req, cost, bo.GetTotalSleep()-startBackOff, timeout)
}
}
resp, err = tikvrpc.GenRegionErrorResp(req, &errorpb.Error{EpochNotMatch: &errorpb.EpochNotMatch{}})
return resp, nil, retryTimes, err
}
var isLocalTraffic bool
if staleReadCollector != nil && s.replicaSelector != nil && s.replicaSelector.target != nil {
isLocalTraffic = s.replicaSelector.target.store.IsLabelsMatch(s.replicaSelector.option.labels)
staleReadCollector.onReq(req, isLocalTraffic)
}
logutil.Eventf(bo.GetCtx(), "send %s request to region %d at %s", req.Type, regionID.id, rpcCtx.Addr)
s.storeAddr = rpcCtx.Addr
if _, err := util.EvalFailpoint("beforeSendReqToRegion"); err == nil {
if hook := bo.GetCtx().Value("sendReqToRegionHook"); hook != nil {
h := hook.(func(*tikvrpc.Request))
h(req)
}
}
req.Context.ClusterId = rpcCtx.ClusterID
if req.InputRequestSource != "" && s.replicaSelector != nil {
patchRequestSource(req, s.replicaSelector.replicaType())
}
if e := tikvrpc.SetContext(req, rpcCtx.Meta, rpcCtx.Peer); e != nil {
return nil, nil, retryTimes, err
}
if s.replicaSelector != nil {
if err := s.replicaSelector.backoffOnRetry(rpcCtx.Store, bo); err != nil {
return nil, nil, retryTimes, err
}
}
var retry bool
resp, retry, err = s.sendReqToRegion(bo, rpcCtx, req, timeout)
req.IsRetryRequest = true
if err != nil {
if cost := time.Since(startTime); cost > slowLogSendReqTime || cost > timeout {
msg := fmt.Sprintf("send request failed, err: %v", err.Error())
s.logSendReqError(bo, msg, regionID, retryTimes, req, cost, bo.GetTotalSleep()-startBackOff, timeout)
}
return nil, nil, retryTimes, err
}
if _, err1 := util.EvalFailpoint("afterSendReqToRegion"); err1 == nil {
if hook := bo.GetCtx().Value("sendReqToRegionFinishHook"); hook != nil {
h := hook.(func(*tikvrpc.Request, *tikvrpc.Response, error))
h(req, resp, err)
}
}
// recheck whether the session/query is killed during the Next()
if err2 := bo.CheckKilled(); err2 != nil {
return nil, nil, retryTimes, err2
}
if val, err := util.EvalFailpoint("mockRetrySendReqToRegion"); err == nil {
if val.(bool) {
retry = true
}
}
if retry {
retryTimes++
continue
}
var regionErr *errorpb.Error
regionErr, err = resp.GetRegionError()
if err != nil {
return nil, nil, retryTimes, err
}
if regionErr != nil {
retry, err = s.onRegionError(bo, rpcCtx, req, regionErr)
if err != nil {
if cost := time.Since(startTime); cost > slowLogSendReqTime || cost > timeout {
msg := fmt.Sprintf("send request on region error failed, err: %v", err.Error())
s.logSendReqError(bo, msg, regionID, retryTimes, req, cost, bo.GetTotalSleep()-startBackOff, timeout)
}
return nil, nil, retryTimes, err
}
if retry {
retryTimes++
continue
}
if cost := time.Since(startTime); cost > slowLogSendReqTime || cost > timeout {
s.logSendReqError(bo, "send request meet region error without retry", regionID, retryTimes, req, cost, bo.GetTotalSleep()-startBackOff, timeout)
}
} else {
if s.replicaSelector != nil {
s.replicaSelector.onSendSuccess(req)
}
}
if staleReadCollector != nil {
staleReadCollector.onResp(req.Type, resp, isLocalTraffic)
}
return resp, rpcCtx, retryTimes, nil
}
}
func (s *RegionRequestSender) logSendReqError(bo *retry.Backoffer, msg string, regionID RegionVerID, retryTimes int, req *tikvrpc.Request, cost time.Duration, currentBackoffMs int, timeout time.Duration) {
var builder strings.Builder
// build the total round stats string.
builder.WriteString("{total-backoff: ")
builder.WriteString(util.FormatDuration(time.Duration(bo.GetTotalSleep() * int(time.Millisecond))))
builder.WriteString(", total-backoff-times: ")
builder.WriteString(strconv.Itoa(bo.GetTotalBackoffTimes()))
if s.Stats != nil {
builder.WriteString(", total-rpc: {")
builder.WriteString(s.Stats.String())
builder.WriteString("}")
}
builder.WriteString("}")
totalRoundStats := builder.String()
// build the current round stats string.
builder.Reset()
builder.WriteString("{time: ")
builder.WriteString(util.FormatDuration(cost))
builder.WriteString(", backoff: ")
builder.WriteString(util.FormatDuration(time.Duration(currentBackoffMs * int(time.Millisecond))))
builder.WriteString(", timeout: ")
builder.WriteString(util.FormatDuration(timeout))
builder.WriteString(", req-max-exec-timeout: ")
builder.WriteString(util.FormatDuration(time.Duration(int64(req.Context.MaxExecutionDurationMs) * int64(time.Millisecond))))
builder.WriteString(", retry-times: ")
builder.WriteString(strconv.Itoa(retryTimes))
if s.AccessStats != nil {
builder.WriteString(", replica-access: {")
builder.WriteString(s.AccessStats.String())
builder.WriteString("}")
}
builder.WriteString("}")
currentRoundStats := builder.String()
logutil.Logger(bo.GetCtx()).Info(msg,
zap.Uint64("req-ts", req.GetStartTS()),
zap.String("req-type", req.Type.String()),
zap.String("region", regionID.String()),
zap.String("replica-read-type", req.ReplicaReadType.String()),
zap.Bool("stale-read", req.StaleRead),
zap.Stringer("request-sender", s),
zap.String("total-round-stats", totalRoundStats),
zap.String("current-round-stats", currentRoundStats))
}
// RPCCancellerCtxKey is context key attach rpc send cancelFunc collector to ctx.
type RPCCancellerCtxKey struct{}
// RPCCanceller is rpc send cancelFunc collector.
type RPCCanceller struct {
sync.Mutex
allocID int
cancels map[int]func()
cancelled bool
}
// NewRPCanceller creates RPCCanceller with init state.
func NewRPCanceller() *RPCCanceller {
return &RPCCanceller{cancels: make(map[int]func())}
}
// WithCancel generates new context with cancel func.
func (h *RPCCanceller) WithCancel(ctx context.Context) (context.Context, func()) {
nctx, cancel := context.WithCancel(ctx)
h.Lock()
if h.cancelled {
h.Unlock()
cancel()