-
Notifications
You must be signed in to change notification settings - Fork 717
/
unsafe_recovery_controller.go
1266 lines (1154 loc) · 40.1 KB
/
unsafe_recovery_controller.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 Project 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 unsaferecovery
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/pingcap/errors"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/btree"
"github.com/tikv/pd/pkg/codec"
"github.com/tikv/pd/pkg/core"
"github.com/tikv/pd/pkg/errs"
sc "github.com/tikv/pd/pkg/schedule/config"
"github.com/tikv/pd/pkg/utils/logutil"
"github.com/tikv/pd/pkg/utils/syncutil"
"github.com/tikv/pd/pkg/utils/typeutil"
"go.uber.org/zap"
)
// stage is the stage of unsafe recovery.
type stage int
const (
storeRequestInterval = time.Second * 40
)
// Stage transition graph: for more details, please check `Controller.HandleStoreHeartbeat()`
//
// +-----------+ +-----------+
// +-----------+ | | | |
// | | | Collect | | Tombstone |
// | Idle |------>| Report |-----+---->| Tiflash |-----+
// | | | | | | Learner | |
// +-----------+ +-----------+ | | | |
// | +-----------+ |
// | | |
// | | |
// | v |
// | +-----------+ |
// | | | |
// | | Force | |
// | | LeaderFor |-----+
// | |CommitMerge| |
// | | | |
// | +-----------+ |
// | | |
// | | |
// | v |
// | +-----------+ | +-----------+
// | | | | | | +-----------+
// | | Force | | | exitForce | | |
// | | Leader |-----+---->| Leader |------->| Failed |
// | | | | | | | |
// | +-----------+ | +-----------+ +-----------+
// | | |
// | | |
// | v |
// | +-----------+ |
// | | | |
// | | Demote | |
// +-----| Voter |-----|
// | | |
// +-----------+ |
// | |
// | |
// v |
// +-----------+ +-----------+ |
// +-----------+ | | | | |
// | | | ExitForce | | Create | |
// | Finished |<------| Leader |<----------| Region |-----+
// | | | | | |
// +-----------+ +-----------+ +-----------+
const (
Idle stage = iota
CollectReport
TombstoneTiFlashLearner
ForceLeaderForCommitMerge
ForceLeader
DemoteFailedVoter
CreateEmptyRegion
ExitForceLeader
Finished
Failed
)
type cluster interface {
core.StoreSetInformer
ResetRegionCache()
AllocID() (uint64, error)
BuryStore(storeID uint64, forceBury bool) error
GetSchedulerConfig() sc.SchedulerConfigProvider
}
// Controller is used to control the unsafe recovery process.
type Controller struct {
syncutil.RWMutex
cluster cluster
stage stage
// the round of recovery, which is an increasing number to identify the reports of each round
step uint64
failedStores map[uint64]struct{}
timeout time.Time
autoDetect bool
// collected reports from store, if not reported yet, it would be nil
storeReports map[uint64]*pdpb.StoreReport
numStoresReported int
storePlanExpires map[uint64]time.Time
storeRecoveryPlans map[uint64]*pdpb.RecoveryPlan
// accumulated output for the whole recovery process
output []StageOutput
// exposed to the outside for testing
AffectedTableIDs map[int64]struct{}
affectedMetaRegions map[uint64]struct{}
newlyCreatedRegions map[uint64]struct{}
err error
}
// StageOutput is the information for one stage of the recovery process.
type StageOutput struct {
Info string `json:"info,omitempty"`
Time string `json:"time,omitempty"`
Actions map[string][]string `json:"actions,omitempty"`
Details []string `json:"details,omitempty"`
}
// NewController creates a new Controller.
func NewController(cluster cluster) *Controller {
u := &Controller{
cluster: cluster,
}
u.reset()
return u
}
func (u *Controller) reset() {
u.stage = Idle
u.step = 0
u.failedStores = make(map[uint64]struct{})
u.storeReports = make(map[uint64]*pdpb.StoreReport)
u.numStoresReported = 0
u.storePlanExpires = make(map[uint64]time.Time)
u.storeRecoveryPlans = make(map[uint64]*pdpb.RecoveryPlan)
u.output = make([]StageOutput, 0)
u.AffectedTableIDs = make(map[int64]struct{}, 0)
u.affectedMetaRegions = make(map[uint64]struct{}, 0)
u.newlyCreatedRegions = make(map[uint64]struct{}, 0)
u.err = nil
}
// IsRunning returns whether there is ongoing unsafe recovery process. If yes, further unsafe
// recovery requests, schedulers, checkers, AskSplit and AskBatchSplit requests are blocked.
func (u *Controller) IsRunning() bool {
u.RLock()
defer u.RUnlock()
return isRunning(u.stage)
}
func isRunning(s stage) bool {
return s != Idle && s != Finished && s != Failed
}
// RemoveFailedStores removes Failed stores from the cluster.
func (u *Controller) RemoveFailedStores(failedStores map[uint64]struct{}, timeout uint64, autoDetect bool) error {
u.Lock()
defer u.Unlock()
if isRunning(u.stage) {
return errs.ErrUnsafeRecoveryIsRunning.FastGenByArgs()
}
if !autoDetect {
if len(failedStores) == 0 {
return errs.ErrUnsafeRecoveryInvalidInput.FastGenByArgs("no store specified")
}
// validate the stores and mark the store as tombstone forcibly
for failedStore := range failedStores {
store := u.cluster.GetStore(failedStore)
if store == nil {
return errs.ErrUnsafeRecoveryInvalidInput.FastGenByArgs(fmt.Sprintf("store %v doesn't exist", failedStore))
} else if (store.IsPreparing() || store.IsServing()) && !store.IsDisconnected() {
return errs.ErrUnsafeRecoveryInvalidInput.FastGenByArgs(fmt.Sprintf("store %v is up and connected", failedStore))
}
}
for failedStore := range failedStores {
err := u.cluster.BuryStore(failedStore, true)
if err != nil && !errors.ErrorEqual(err, errs.ErrStoreNotFound.FastGenByArgs(failedStore)) {
return err
}
}
}
u.reset()
for _, s := range u.cluster.GetStores() {
if s.IsRemoved() || s.IsPhysicallyDestroyed() {
continue
}
if _, exists := failedStores[s.GetID()]; exists {
continue
}
u.storeReports[s.GetID()] = nil
}
u.timeout = time.Now().Add(time.Duration(timeout) * time.Second)
u.failedStores = failedStores
u.autoDetect = autoDetect
u.changeStage(CollectReport)
return nil
}
// Show returns the current status of ongoing unsafe recover operation.
func (u *Controller) Show() []StageOutput {
u.Lock()
defer u.Unlock()
if u.stage == Idle {
return []StageOutput{{Info: "No on-going recovery."}}
}
if err := u.checkTimeout(); err != nil {
u.handleErr(err)
}
status := u.output
if u.stage != Finished && u.stage != Failed {
status = append(status, u.getReportStatus())
}
return status
}
func (u *Controller) getReportStatus() StageOutput {
var status StageOutput
status.Time = time.Now().Format("2006-01-02 15:04:05.000")
if u.numStoresReported != len(u.storeReports) {
status.Info = fmt.Sprintf("Collecting reports from alive stores(%d/%d)", u.numStoresReported, len(u.storeReports))
var reported, unreported, undispatched string
for storeID, report := range u.storeReports {
str := strconv.FormatUint(storeID, 10) + ", "
if report == nil {
if _, requested := u.storePlanExpires[storeID]; !requested {
undispatched += str
} else {
unreported += str
}
} else {
reported += str
}
}
status.Details = append(status.Details, "Stores that have not dispatched plan: "+strings.Trim(undispatched, ", "))
status.Details = append(status.Details, "Stores that have reported to PD: "+strings.Trim(reported, ", "))
status.Details = append(status.Details, "Stores that have not reported to PD: "+strings.Trim(unreported, ", "))
} else {
status.Info = fmt.Sprintf("Collected reports from all %d alive stores", len(u.storeReports))
}
return status
}
func (u *Controller) checkTimeout() error {
if u.stage == Finished || u.stage == Failed {
return nil
}
if time.Now().After(u.timeout) {
return errors.Errorf("Exceeds timeout %v", u.timeout)
}
return nil
}
// handleErr handles the error occurred during the unsafe recovery process.
func (u *Controller) handleErr(err error) bool {
// Keep the earliest error.
if u.err == nil {
u.err = err
}
if u.stage == ExitForceLeader {
// We already tried to exit force leader, and it still Failed.
// We turn into Failed stage directly. TiKV will step down force leader
// automatically after being for a long time.
u.changeStage(Failed)
return true
}
// When encountering an error for the first time, we will try to exit force
// leader before turning into Failed stage to avoid the leaking force leaders
// blocks reads and writes.
u.storePlanExpires = make(map[uint64]time.Time)
u.storeRecoveryPlans = make(map[uint64]*pdpb.RecoveryPlan)
u.timeout = time.Now().Add(storeRequestInterval * 2)
// empty recovery plan would trigger exit force leader
u.changeStage(ExitForceLeader)
return false
}
// HandleStoreHeartbeat handles the store heartbeat requests and checks whether the stores need to
// send detailed report back.
func (u *Controller) HandleStoreHeartbeat(heartbeat *pdpb.StoreHeartbeatRequest, resp *pdpb.StoreHeartbeatResponse) {
u.Lock()
defer u.Unlock()
if !isRunning(u.stage) {
// no recovery in progress, do nothing
return
}
done, err := func() (bool, error) {
if err := u.checkTimeout(); err != nil {
return false, err
}
allCollected, err := u.CollectReport(heartbeat)
if err != nil {
return false, err
}
if allCollected {
newestRegionTree, peersMap, err := u.buildUpFromReports()
if err != nil {
return false, err
}
return u.generatePlan(newestRegionTree, peersMap)
}
return false, nil
}()
if done || (err != nil && u.handleErr(err)) {
return
}
u.dispatchPlan(heartbeat, resp)
}
func (u *Controller) generatePlan(newestRegionTree *regionTree, peersMap map[uint64][]*regionItem) (bool, error) {
// clean up previous plan
u.storePlanExpires = make(map[uint64]time.Time)
u.storeRecoveryPlans = make(map[uint64]*pdpb.RecoveryPlan)
stage := u.stage
reCheck := false
hasPlan := false
var err error
for {
switch stage {
case CollectReport:
fallthrough
case TombstoneTiFlashLearner:
if hasPlan, err = u.generateTombstoneTiFlashLearnerPlan(newestRegionTree, peersMap); hasPlan && err == nil {
u.changeStage(TombstoneTiFlashLearner)
break
}
if err != nil {
break
}
fallthrough
case ForceLeaderForCommitMerge:
if hasPlan, err = u.generateForceLeaderPlan(newestRegionTree, peersMap, true); hasPlan && err == nil {
u.changeStage(ForceLeaderForCommitMerge)
break
}
if err != nil {
break
}
fallthrough
case ForceLeader:
if hasPlan, err = u.generateForceLeaderPlan(newestRegionTree, peersMap, false); hasPlan && err == nil {
u.changeStage(ForceLeader)
break
}
if err != nil {
break
}
fallthrough
case DemoteFailedVoter:
if hasPlan = u.generateDemoteFailedVoterPlan(newestRegionTree, peersMap); hasPlan {
u.changeStage(DemoteFailedVoter)
break
} else if !reCheck {
reCheck = true
stage = TombstoneTiFlashLearner
continue
}
fallthrough
case CreateEmptyRegion:
if hasPlan, err = u.generateCreateEmptyRegionPlan(newestRegionTree, peersMap); hasPlan && err == nil {
u.changeStage(CreateEmptyRegion)
break
}
if err != nil {
break
}
fallthrough
case ExitForceLeader:
if hasPlan = u.generateExitForceLeaderPlan(); hasPlan {
u.changeStage(ExitForceLeader)
}
default:
panic("unreachable")
}
break
}
if err == nil && !hasPlan {
if u.err != nil {
u.changeStage(Failed)
} else {
u.changeStage(Finished)
}
return true, nil
}
return false, err
}
// It dispatches recovery plan if any.
func (u *Controller) dispatchPlan(heartbeat *pdpb.StoreHeartbeatRequest, resp *pdpb.StoreHeartbeatResponse) {
storeID := heartbeat.Stats.StoreId
now := time.Now()
if reported, exist := u.storeReports[storeID]; reported != nil || !exist {
// the plan has been executed, no need to dispatch again
// or no need to dispatch plan to this store(e.g. Tiflash)
return
}
if expire, dispatched := u.storePlanExpires[storeID]; !dispatched || expire.Before(now) {
if dispatched {
log.Info("unsafe recovery store recovery plan execution timeout, retry", zap.Uint64("store-id", storeID))
}
// Dispatch the recovery plan to the store, and the plan may be empty.
resp.RecoveryPlan = u.getRecoveryPlan(storeID)
resp.RecoveryPlan.Step = u.step
u.storePlanExpires[storeID] = now.Add(storeRequestInterval)
}
}
// CollectReport collects and checks if store reports have been fully collected.
func (u *Controller) CollectReport(heartbeat *pdpb.StoreHeartbeatRequest) (bool, error) {
storeID := heartbeat.Stats.StoreId
if _, isFailedStore := u.failedStores[storeID]; isFailedStore {
return false, errors.Errorf("Receive heartbeat from Failed store %d", storeID)
}
if heartbeat.StoreReport == nil {
return false, nil
}
if heartbeat.StoreReport.GetStep() != u.step {
log.Info("unsafe recovery receives invalid store report",
zap.Uint64("store-id", storeID), zap.Uint64("expected-step", u.step), zap.Uint64("obtained-step", heartbeat.StoreReport.GetStep()))
// invalid store report, ignore
return false, nil
}
if report, exists := u.storeReports[storeID]; exists {
// if receive duplicated report from the same TiKV, use the latest one
u.storeReports[storeID] = heartbeat.StoreReport
if report == nil {
u.numStoresReported++
if u.numStoresReported == len(u.storeReports) {
return true, nil
}
}
}
return false, nil
}
// GetStage gets the stage of the current unsafe recovery.
func (u *Controller) GetStage() stage {
u.RLock()
defer u.RUnlock()
return u.stage
}
func (u *Controller) changeStage(stage stage) {
// If the running stage changes, update the scheduling allowance status to add or remove "online-unsafe-recovery" halt.
if running := isRunning(stage); running != isRunning(u.stage) {
u.cluster.GetSchedulerConfig().SetSchedulingAllowanceStatus(running, "online-unsafe-recovery")
}
u.stage = stage
var output StageOutput
output.Time = time.Now().Format("2006-01-02 15:04:05.000")
switch u.stage {
case Idle:
case CollectReport:
// TODO: clean up existing operators
output.Info = "Unsafe recovery enters collect report stage"
if u.autoDetect {
output.Details = append(output.Details, "auto detect mode with no specified Failed stores")
} else {
stores := ""
count := 0
for store := range u.failedStores {
count += 1
stores += fmt.Sprintf("%d", store)
if count != len(u.failedStores) {
stores += ", "
}
}
output.Details = append(output.Details, fmt.Sprintf("Failed stores %s", stores))
}
case TombstoneTiFlashLearner:
output.Info = "Unsafe recovery enters tombstone TiFlash learner stage"
output.Actions = u.getTombstoneTiFlashLearnerDigest()
case ForceLeaderForCommitMerge:
output.Info = "Unsafe recovery enters force leader for commit merge stage"
output.Actions = u.getForceLeaderPlanDigest()
case ForceLeader:
output.Info = "Unsafe recovery enters force leader stage"
output.Actions = u.getForceLeaderPlanDigest()
case DemoteFailedVoter:
output.Info = "Unsafe recovery enters demote Failed voter stage"
output.Actions = u.getDemoteFailedVoterPlanDigest()
case CreateEmptyRegion:
output.Info = "Unsafe recovery enters create empty region stage"
output.Actions = u.getCreateEmptyRegionPlanDigest()
case ExitForceLeader:
output.Info = "Unsafe recovery enters exit force leader stage"
if u.err != nil {
output.Details = append(output.Details, fmt.Sprintf("triggered by error: %v", u.err.Error()))
}
case Finished:
if u.step > 1 {
// == 1 means no operation has done, no need to invalid cache
u.cluster.ResetRegionCache()
}
output.Info = "Unsafe recovery Finished"
output.Details = u.getAffectedTableDigest()
u.storePlanExpires = make(map[uint64]time.Time)
u.storeRecoveryPlans = make(map[uint64]*pdpb.RecoveryPlan)
case Failed:
output.Info = fmt.Sprintf("Unsafe recovery Failed: %v", u.err)
output.Details = u.getAffectedTableDigest()
if u.numStoresReported != len(u.storeReports) {
// in collecting reports, print out which stores haven't reported yet
output.Details = append(output.Details, u.getReportStatus().Details...)
}
u.storePlanExpires = make(map[uint64]time.Time)
u.storeRecoveryPlans = make(map[uint64]*pdpb.RecoveryPlan)
}
u.output = append(u.output, output)
data, err := json.Marshal(output)
if err != nil {
log.Error("unsafe recovery fail to marshal json object", zap.Error(err))
} else {
log.Info(string(data))
}
// reset store reports to nil instead of delete, because it relays on the item
// to decide which store it needs to collect the report from.
for k := range u.storeReports {
u.storeReports[k] = nil
}
u.numStoresReported = 0
u.step += 1
}
func (u *Controller) getForceLeaderPlanDigest() map[string][]string {
outputs := make(map[string][]string)
for storeID, plan := range u.storeRecoveryPlans {
forceLeaders := plan.GetForceLeader()
if forceLeaders != nil {
regions := ""
for i, regionID := range forceLeaders.GetEnterForceLeaders() {
regions += fmt.Sprintf("%d", regionID)
if i != len(forceLeaders.GetEnterForceLeaders())-1 {
regions += ", "
}
}
outputs[fmt.Sprintf("store %d", storeID)] = []string{fmt.Sprintf("force leader on regions: %s", regions)}
}
}
return outputs
}
func (u *Controller) getDemoteFailedVoterPlanDigest() map[string][]string {
outputs := make(map[string][]string)
for storeID, plan := range u.storeRecoveryPlans {
if len(plan.GetDemotes()) == 0 && len(plan.GetTombstones()) == 0 {
continue
}
output := []string{}
for _, demote := range plan.GetDemotes() {
peers := ""
for _, peer := range demote.GetFailedVoters() {
peers += fmt.Sprintf("{ %v}, ", peer) // the extra space is intentional
}
output = append(output, fmt.Sprintf("region %d demotes peers %s", demote.GetRegionId(), strings.Trim(peers, ", ")))
}
for _, tombstone := range plan.GetTombstones() {
output = append(output, fmt.Sprintf("tombstone the peer of region %d", tombstone))
}
outputs[fmt.Sprintf("store %d", storeID)] = output
}
return outputs
}
func (u *Controller) getTombstoneTiFlashLearnerDigest() map[string][]string {
outputs := make(map[string][]string)
for storeID, plan := range u.storeRecoveryPlans {
if len(plan.GetTombstones()) == 0 {
continue
}
output := []string{}
for _, tombstone := range plan.GetTombstones() {
output = append(output, fmt.Sprintf("tombstone the peer of region %d", tombstone))
}
outputs[fmt.Sprintf("store %d", storeID)] = output
}
return outputs
}
func (u *Controller) getCreateEmptyRegionPlanDigest() map[string][]string {
outputs := make(map[string][]string)
for storeID, plan := range u.storeRecoveryPlans {
if plan.GetCreates() == nil {
continue
}
output := []string{}
for _, region := range plan.GetCreates() {
info := logutil.RedactStringer(core.RegionToHexMeta(region)).String()
// avoid json escape character to make the output readable
info = strings.ReplaceAll(info, "<", "{ ") // the extra space is intentional
info = strings.ReplaceAll(info, ">", "}")
output = append(output, fmt.Sprintf("create region %d: %v", region.GetId(), info))
}
outputs[fmt.Sprintf("store %d", storeID)] = output
}
return outputs
}
func (u *Controller) getAffectedTableDigest() []string {
var details []string
if len(u.affectedMetaRegions) != 0 {
regions := ""
for r := range u.affectedMetaRegions {
regions += fmt.Sprintf("%d, ", r)
}
details = append(details, "affected meta regions: "+strings.Trim(regions, ", "))
}
if len(u.AffectedTableIDs) != 0 {
tables := ""
for t := range u.AffectedTableIDs {
tables += fmt.Sprintf("%d, ", t)
}
details = append(details, "affected table ids: "+strings.Trim(tables, ", "))
}
if len(u.newlyCreatedRegions) != 0 {
regions := ""
for r := range u.newlyCreatedRegions {
regions += fmt.Sprintf("%d, ", r)
}
details = append(details, "newly created empty regions: "+strings.Trim(regions, ", "))
} else {
details = append(details, "no newly created empty regions")
}
return details
}
func (u *Controller) recordAffectedRegion(region *metapb.Region) {
isMeta, tableID := codec.Key(region.StartKey).MetaOrTable()
if isMeta {
u.affectedMetaRegions[region.GetId()] = struct{}{}
} else if tableID != 0 {
u.AffectedTableIDs[tableID] = struct{}{}
}
}
func (u *Controller) isFailed(peer *metapb.Peer) bool {
_, isFailed := u.failedStores[peer.StoreId]
_, isLive := u.storeReports[peer.StoreId]
if isFailed || (u.autoDetect && !isLive) {
return true
}
return false
}
func (u *Controller) canElectLeader(region *metapb.Region, onlyIncoming bool) bool {
hasQuorum := func(voters []*metapb.Peer) bool {
numFailedVoters := 0
numLiveVoters := 0
for _, voter := range voters {
if u.isFailed(voter) {
numFailedVoters += 1
} else {
numLiveVoters += 1
}
}
return numFailedVoters < numLiveVoters
}
// consider joint consensus
var incomingVoters []*metapb.Peer
var outgoingVoters []*metapb.Peer
for _, peer := range region.Peers {
if peer.Role == metapb.PeerRole_Voter || peer.Role == metapb.PeerRole_IncomingVoter {
incomingVoters = append(incomingVoters, peer)
}
if peer.Role == metapb.PeerRole_Voter || peer.Role == metapb.PeerRole_DemotingVoter {
outgoingVoters = append(outgoingVoters, peer)
}
}
return hasQuorum(incomingVoters) && (onlyIncoming || hasQuorum(outgoingVoters))
}
func (u *Controller) getFailedPeers(region *metapb.Region) []*metapb.Peer {
// if it can form a quorum after exiting the joint state, then no need to demotes any peer
if u.canElectLeader(region, true) {
return nil
}
var failedPeers []*metapb.Peer
for _, peer := range region.Peers {
if u.isFailed(peer) {
failedPeers = append(failedPeers, peer)
}
}
return failedPeers
}
type regionItem struct {
report *pdpb.PeerReport
storeID uint64
}
// Less returns true if the region start key is less than the other.
func (r *regionItem) Less(other *regionItem) bool {
left := r.region().GetStartKey()
right := other.region().GetStartKey()
return bytes.Compare(left, right) < 0
}
func (r *regionItem) contains(key []byte) bool {
start, end := r.region().GetStartKey(), r.region().GetEndKey()
return bytes.Compare(key, start) >= 0 && (len(end) == 0 || bytes.Compare(key, end) < 0)
}
func (r *regionItem) region() *metapb.Region {
return r.report.GetRegionState().GetRegion()
}
func (r *regionItem) isInitialized() bool {
return len(r.region().Peers) != 0
}
func (r *regionItem) isEpochStale(other *regionItem) bool {
re := r.region().GetRegionEpoch()
oe := other.region().GetRegionEpoch()
return re.GetVersion() < oe.GetVersion() || (re.GetVersion() == oe.GetVersion() && re.GetConfVer() < oe.GetConfVer())
}
func (r *regionItem) isRaftStale(origin *regionItem, u *Controller) bool {
cmps := []func(a, b *regionItem) int{
func(a, b *regionItem) int {
return int(a.report.GetRaftState().GetHardState().GetTerm()) - int(b.report.GetRaftState().GetHardState().GetTerm())
},
// choose the peer has maximum applied index or last index.
func(a, b *regionItem) int {
maxIdxA := typeutil.MaxUint64(a.report.GetRaftState().GetLastIndex(), a.report.AppliedIndex)
maxIdxB := typeutil.MaxUint64(b.report.GetRaftState().GetLastIndex(), b.report.AppliedIndex)
return int(maxIdxA - maxIdxB)
},
func(a, b *regionItem) int {
return int(a.report.GetRaftState().GetLastIndex()) - int(b.report.GetRaftState().GetLastIndex())
},
func(a, b *regionItem) int {
return int(a.report.GetRaftState().GetHardState().GetCommit()) - int(b.report.GetRaftState().GetHardState().GetCommit())
},
func(a, b *regionItem) int {
if u.cluster.GetStore(a.storeID).IsTiFlash() {
return -1
}
if u.cluster.GetStore(b.storeID).IsTiFlash() {
return 1
}
// better use voter rather than learner
for _, peer := range a.region().GetPeers() {
if peer.StoreId == a.storeID {
if peer.Role == metapb.PeerRole_DemotingVoter || peer.Role == metapb.PeerRole_Learner {
return -1
}
}
}
return 0
},
}
for _, cmp := range cmps {
if v := cmp(r, origin); v != 0 {
return v < 0
}
}
return false
}
const (
defaultBTreeDegree = 64
)
type regionTree struct {
regions map[uint64]*regionItem
tree *btree.BTreeG[*regionItem]
}
func newRegionTree() *regionTree {
return ®ionTree{
regions: make(map[uint64]*regionItem),
tree: btree.NewG[*regionItem](defaultBTreeDegree),
}
}
func (t *regionTree) size() int {
return t.tree.Len()
}
func (t *regionTree) contains(regionID uint64) bool {
_, ok := t.regions[regionID]
return ok
}
// getOverlaps gets the regions which are overlapped with the specified region range.
func (t *regionTree) getOverlaps(item *regionItem) []*regionItem {
// note that find() gets the last item that is less or equal than the region.
// in the case: |_______a_______|_____b_____|___c___|
// new region is |______d______|
// find() will return regionItem of region_a
// and both startKey of region_a and region_b are less than endKey of region_d,
// thus they are regarded as overlapped regions.
result := t.find(item)
if result == nil {
result = item
}
end := item.region().GetEndKey()
var overlaps []*regionItem
t.tree.AscendGreaterOrEqual(result, func(i *regionItem) bool {
over := i
if len(end) > 0 && bytes.Compare(end, over.region().GetStartKey()) <= 0 {
return false
}
overlaps = append(overlaps, over)
return true
})
return overlaps
}
// find is a helper function to find an item that contains the regions start key.
func (t *regionTree) find(item *regionItem) *regionItem {
var result *regionItem
t.tree.DescendLessOrEqual(item, func(i *regionItem) bool {
result = i
return false
})
if result == nil || !result.contains(item.region().GetStartKey()) {
return nil
}
return result
}
// Insert the peer report of one region int the tree.
// It finds and deletes all the overlapped regions first, and then
// insert the new region.
func (t *regionTree) insert(item *regionItem) (bool, error) {
overlaps := t.getOverlaps(item)
if t.contains(item.region().GetId()) {
// it's ensured by the `buildUpFromReports` that only insert the latest peer of one region.
return false, errors.Errorf("region %v shouldn't be updated twice", item.region().GetId())
}
for _, newer := range overlaps {
log.Info("unsafe recovery found overlap regions", logutil.ZapRedactStringer("newer-region-meta", core.RegionToHexMeta(newer.region())), logutil.ZapRedactStringer("older-region-meta", core.RegionToHexMeta(item.region())))
// it's ensured by the `buildUpFromReports` that peers are inserted in epoch descending order.
if newer.isEpochStale(item) {
return false, errors.Errorf("region %v's epoch shouldn't be staler than old ones %v", item, newer)
}
}
if len(overlaps) != 0 {
return false, nil
}
t.regions[item.region().GetId()] = item
t.tree.ReplaceOrInsert(item)
return true, nil
}
func (u *Controller) getRecoveryPlan(storeID uint64) *pdpb.RecoveryPlan {
if _, exists := u.storeRecoveryPlans[storeID]; !exists {
u.storeRecoveryPlans[storeID] = &pdpb.RecoveryPlan{}
}
return u.storeRecoveryPlans[storeID]
}
func (u *Controller) buildUpFromReports() (*regionTree, map[uint64][]*regionItem, error) {
peersMap := make(map[uint64][]*regionItem)
// Go through all the peer reports to build up the newest region tree
for storeID, storeReport := range u.storeReports {
for _, peerReport := range storeReport.PeerReports {
item := ®ionItem{report: peerReport, storeID: storeID}
peersMap[item.region().GetId()] = append(peersMap[item.region().GetId()], item)
}
}
// find the report of the leader
newestPeerReports := make([]*regionItem, 0, len(peersMap))
for _, peers := range peersMap {
var latest *regionItem
for _, peer := range peers {
if latest == nil || latest.isEpochStale(peer) {
latest = peer
}
}
if !latest.isInitialized() {
// ignore the uninitialized peer
continue
}
newestPeerReports = append(newestPeerReports, latest)
}
// sort in descending order of epoch
sort.SliceStable(newestPeerReports, func(i, j int) bool {
return newestPeerReports[j].isEpochStale(newestPeerReports[i])
})
newestRegionTree := newRegionTree()
for _, peer := range newestPeerReports {
_, err := newestRegionTree.insert(peer)
if err != nil {
return nil, nil, err
}
}
return newestRegionTree, peersMap, nil
}
func (u *Controller) selectLeader(peersMap map[uint64][]*regionItem, region *metapb.Region) *regionItem {
var leader *regionItem
for _, peer := range peersMap[region.GetId()] {
if leader == nil || leader.isRaftStale(peer, u) {
leader = peer
}
}
return leader
}
func (u *Controller) generateTombstoneTiFlashLearnerPlan(newestRegionTree *regionTree, peersMap map[uint64][]*regionItem) (bool, error) {
if u.err != nil {
return false, nil
}
hasPlan := false
var err error
newestRegionTree.tree.Ascend(func(item *regionItem) bool {
region := item.region()
if !u.canElectLeader(region, false) {
leader := u.selectLeader(peersMap, region)
if leader == nil {
err = errors.Errorf("can't select leader for region %d: %v", region.GetId(), logutil.RedactStringer(core.RegionToHexMeta(region)))
return false
}
storeID := leader.storeID
if u.cluster.GetStore(storeID).IsTiFlash() {
// tombstone the tiflash learner, as it can't be leader
storeRecoveryPlan := u.getRecoveryPlan(storeID)
storeRecoveryPlan.Tombstones = append(storeRecoveryPlan.Tombstones, region.GetId())
u.recordAffectedRegion(region)
hasPlan = true
}
}
return true
})
return hasPlan, err
}