-
Notifications
You must be signed in to change notification settings - Fork 728
/
Copy pathcluster.go
2330 lines (2051 loc) · 71.2 KB
/
cluster.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 2016 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 cluster
import (
"context"
"fmt"
"math"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/coreos/go-semver/semver"
"github.com/gogo/protobuf/proto"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/log"
"github.com/tikv/pd/pkg/errs"
"github.com/tikv/pd/pkg/etcdutil"
"github.com/tikv/pd/pkg/logutil"
"github.com/tikv/pd/pkg/netutil"
"github.com/tikv/pd/pkg/progress"
"github.com/tikv/pd/pkg/syncutil"
"github.com/tikv/pd/pkg/typeutil"
"github.com/tikv/pd/server/config"
"github.com/tikv/pd/server/core"
"github.com/tikv/pd/server/core/storelimit"
"github.com/tikv/pd/server/id"
syncer "github.com/tikv/pd/server/region_syncer"
"github.com/tikv/pd/server/replication"
"github.com/tikv/pd/server/schedule"
"github.com/tikv/pd/server/schedule/checker"
"github.com/tikv/pd/server/schedule/hbstream"
"github.com/tikv/pd/server/schedule/labeler"
"github.com/tikv/pd/server/schedule/placement"
"github.com/tikv/pd/server/schedulers"
"github.com/tikv/pd/server/statistics"
"github.com/tikv/pd/server/statistics/buckets"
"github.com/tikv/pd/server/storage"
"github.com/tikv/pd/server/storage/endpoint"
"github.com/tikv/pd/server/versioninfo"
"go.etcd.io/etcd/clientv3"
"go.uber.org/zap"
)
var (
// DefaultMinResolvedTSPersistenceInterval is the default value of min resolved ts persistence interval.
DefaultMinResolvedTSPersistenceInterval = 10 * time.Second
)
// regionLabelGCInterval is the interval to run region-label's GC work.
const regionLabelGCInterval = time.Hour
const (
// nodeStateCheckJobInterval is the interval to run node state check job.
nodeStateCheckJobInterval = 10 * time.Second
// metricsCollectionJobInterval is the interval to run metrics collection job.
metricsCollectionJobInterval = 10 * time.Second
clientTimeout = 3 * time.Second
defaultChangedRegionsLimit = 10000
// persistLimitRetryTimes is used to reduce the probability of the persistent error
// since the once the store is add or remove, we shouldn't return an error even if the store limit is failed to persist.
persistLimitRetryTimes = 5
persistLimitWaitTime = 100 * time.Millisecond
removingAction = "removing"
preparingAction = "preparing"
)
// Server is the interface for cluster.
type Server interface {
GetAllocator() id.Allocator
GetConfig() *config.Config
GetPersistOptions() *config.PersistOptions
GetStorage() storage.Storage
GetHBStreams() *hbstream.HeartbeatStreams
GetRaftCluster() *RaftCluster
GetBasicCluster() *core.BasicCluster
GetMembers() ([]*pdpb.Member, error)
ReplicateFileToMember(ctx context.Context, member *pdpb.Member, name string, data []byte) error
}
// RaftCluster is used for cluster config management.
// Raft cluster key format:
// cluster 1 -> /1/raft, value is metapb.Cluster
// cluster 2 -> /2/raft
// For cluster 1
// store 1 -> /1/raft/s/1, value is metapb.Store
// region 1 -> /1/raft/r/1, value is metapb.Region
type RaftCluster struct {
syncutil.RWMutex
wg sync.WaitGroup
serverCtx context.Context
ctx context.Context
cancel context.CancelFunc
etcdClient *clientv3.Client
httpClient *http.Client
running bool
meta *metapb.Cluster
storeConfigManager *config.StoreConfigManager
storage storage.Storage
minResolvedTS uint64
// Keep the previous store limit settings when removing a store.
prevStoreLimit map[uint64]map[storelimit.Type]float64
// This below fields are all read-only, we cannot update itself after the raft cluster starts.
clusterID uint64
id id.Allocator
core *core.BasicCluster // cached cluster info
opt *config.PersistOptions
limiter *StoreLimiter
coordinator *coordinator
labelLevelStats *statistics.LabelStatistics
regionStats *statistics.RegionStatistics
hotStat *statistics.HotStat
hotBuckets *buckets.HotBucketCache
ruleManager *placement.RuleManager
regionLabeler *labeler.RegionLabeler
replicationMode *replication.ModeManager
unsafeRecoveryController *unsafeRecoveryController
progressManager *progress.Manager
regionSyncer *syncer.RegionSyncer
changedRegions chan *core.RegionInfo
}
// Status saves some state information.
// NOTE: This type is exported by HTTP API. Please pay more attention when modifying it.
type Status struct {
RaftBootstrapTime time.Time `json:"raft_bootstrap_time,omitempty"`
IsInitialized bool `json:"is_initialized"`
ReplicationStatus string `json:"replication_status"`
}
// NewRaftCluster create a new cluster.
func NewRaftCluster(ctx context.Context, clusterID uint64, regionSyncer *syncer.RegionSyncer, etcdClient *clientv3.Client,
httpClient *http.Client) *RaftCluster {
return &RaftCluster{
serverCtx: ctx,
running: false,
clusterID: clusterID,
regionSyncer: regionSyncer,
httpClient: httpClient,
etcdClient: etcdClient,
}
}
// GetStoreConfig returns the store config.
func (c *RaftCluster) GetStoreConfig() *config.StoreConfig {
return c.storeConfigManager.GetStoreConfig()
}
// LoadClusterStatus loads the cluster status.
func (c *RaftCluster) LoadClusterStatus() (*Status, error) {
bootstrapTime, err := c.loadBootstrapTime()
if err != nil {
return nil, err
}
var isInitialized bool
if bootstrapTime != typeutil.ZeroTime {
isInitialized = c.isInitialized()
}
var replicationStatus string
if c.replicationMode != nil {
replicationStatus = c.replicationMode.GetReplicationStatus().String()
}
return &Status{
RaftBootstrapTime: bootstrapTime,
IsInitialized: isInitialized,
ReplicationStatus: replicationStatus,
}, nil
}
func (c *RaftCluster) isInitialized() bool {
if c.core.GetRegionCount() > 1 {
return true
}
region := c.core.GetRegionByKey(nil)
return region != nil &&
len(region.GetVoters()) >= int(c.opt.GetReplicationConfig().MaxReplicas) &&
len(region.GetPendingPeers()) == 0
}
// loadBootstrapTime loads the saved bootstrap time from etcd. It returns zero
// value of time.Time when there is error or the cluster is not bootstrapped yet.
func (c *RaftCluster) loadBootstrapTime() (time.Time, error) {
var t time.Time
data, err := c.storage.Load(endpoint.ClusterBootstrapTimeKey())
if err != nil {
return t, err
}
if data == "" {
return t, nil
}
return typeutil.ParseTimestamp([]byte(data))
}
// InitCluster initializes the raft cluster.
func (c *RaftCluster) InitCluster(
id id.Allocator,
opt *config.PersistOptions,
storage storage.Storage,
basicCluster *core.BasicCluster) {
c.core, c.opt, c.storage, c.id = basicCluster, opt, storage, id
c.ctx, c.cancel = context.WithCancel(c.serverCtx)
c.labelLevelStats = statistics.NewLabelStatistics()
c.hotStat = statistics.NewHotStat(c.ctx)
c.hotBuckets = buckets.NewBucketsCache(c.ctx)
c.progressManager = progress.NewManager()
c.changedRegions = make(chan *core.RegionInfo, defaultChangedRegionsLimit)
c.prevStoreLimit = make(map[uint64]map[storelimit.Type]float64)
c.unsafeRecoveryController = newUnsafeRecoveryController(c)
}
// Start starts a cluster.
func (c *RaftCluster) Start(s Server) error {
c.Lock()
defer c.Unlock()
if c.running {
log.Warn("raft cluster has already been started")
return nil
}
c.InitCluster(s.GetAllocator(), s.GetPersistOptions(), s.GetStorage(), s.GetBasicCluster())
cluster, err := c.LoadClusterInfo()
if err != nil {
return err
}
if cluster == nil {
return nil
}
c.ruleManager = placement.NewRuleManager(c.storage, c, c.GetOpts())
if c.opt.IsPlacementRulesEnabled() {
err = c.ruleManager.Initialize(c.opt.GetMaxReplicas(), c.opt.GetLocationLabels())
if err != nil {
return err
}
}
c.regionLabeler, err = labeler.NewRegionLabeler(c.ctx, c.storage, regionLabelGCInterval)
if err != nil {
return err
}
c.replicationMode, err = replication.NewReplicationModeManager(s.GetConfig().ReplicationMode, c.storage, cluster, s)
if err != nil {
return err
}
c.storeConfigManager = config.NewStoreConfigManager(c.httpClient)
c.coordinator = newCoordinator(c.ctx, cluster, s.GetHBStreams())
c.regionStats = statistics.NewRegionStatistics(c.opt, c.ruleManager, c.storeConfigManager)
c.limiter = NewStoreLimiter(s.GetPersistOptions())
c.wg.Add(8)
go c.runCoordinator()
go c.runMetricsCollectionJob()
go c.runNodeStateCheckJob()
go c.runStatsBackgroundJobs()
go c.syncRegions()
go c.runReplicationMode()
go c.runMinResolvedTSJob()
go c.runSyncConfig()
c.running = true
return nil
}
// runSyncConfig runs the job to sync tikv config.
func (c *RaftCluster) runSyncConfig() {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
stores := c.GetStores()
syncConfig(c.storeConfigManager, stores)
for {
select {
case <-c.ctx.Done():
log.Info("sync store config job is stopped")
return
case <-ticker.C:
if !syncConfig(c.storeConfigManager, stores) {
stores = c.GetStores()
}
}
}
}
func syncConfig(manager *config.StoreConfigManager, stores []*core.StoreInfo) bool {
for index := 0; index < len(stores); index++ {
// filter out the stores that are tiflash
store := stores[index]
if core.IsStoreContainLabel(store.GetMeta(), core.EngineKey, core.EngineTiFlash) {
continue
}
// filter out the stores that are not up.
if !(store.IsPreparing() || store.IsServing()) {
continue
}
// it will try next store if the current store is failed.
address := netutil.ResolveLoopBackAddr(stores[index].GetStatusAddress(), stores[index].GetAddress())
if err := manager.ObserveConfig(address); err != nil {
storeSyncConfigEvent.WithLabelValues(address, "fail").Inc()
log.Debug("sync store config failed, it will try next store", zap.Error(err))
continue
}
storeSyncConfigEvent.WithLabelValues(address, "succ").Inc()
// it will only try one store.
return true
}
return false
}
// LoadClusterInfo loads cluster related info.
func (c *RaftCluster) LoadClusterInfo() (*RaftCluster, error) {
c.meta = &metapb.Cluster{}
ok, err := c.storage.LoadMeta(c.meta)
if err != nil {
return nil, err
}
if !ok {
return nil, nil
}
c.core.ResetStores()
start := time.Now()
if err := c.storage.LoadStores(c.core.PutStore); err != nil {
return nil, err
}
log.Info("load stores",
zap.Int("count", c.GetStoreCount()),
zap.Duration("cost", time.Since(start)),
)
start = time.Now()
// used to load region from kv storage to cache storage.
if err := c.storage.LoadRegionsOnce(c.ctx, c.core.CheckAndPutRegion); err != nil {
return nil, err
}
log.Info("load regions",
zap.Int("count", c.core.GetRegionCount()),
zap.Duration("cost", time.Since(start)),
)
for _, store := range c.GetStores() {
storeID := store.GetID()
c.hotStat.GetOrCreateRollingStoreStats(storeID)
}
return c, nil
}
func (c *RaftCluster) runMetricsCollectionJob() {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(metricsCollectionJobInterval)
failpoint.Inject("highFrequencyClusterJobs", func() {
ticker = time.NewTicker(time.Microsecond)
})
defer ticker.Stop()
for {
select {
case <-c.ctx.Done():
log.Info("metrics are reset")
c.resetMetrics()
log.Info("metrics collection job has been stopped")
return
case <-ticker.C:
c.collectMetrics()
}
}
}
func (c *RaftCluster) runNodeStateCheckJob() {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(nodeStateCheckJobInterval)
failpoint.Inject("highFrequencyClusterJobs", func() {
ticker = time.NewTicker(2 * time.Second)
})
defer ticker.Stop()
for {
select {
case <-c.ctx.Done():
log.Info("node state check job has been stopped")
return
case <-ticker.C:
c.checkStores()
}
}
}
func (c *RaftCluster) runStatsBackgroundJobs() {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(statistics.RegionsStatsObserveInterval)
defer ticker.Stop()
for {
select {
case <-c.ctx.Done():
log.Info("statistics background jobs has been stopped")
return
case <-ticker.C:
c.hotStat.ObserveRegionsStats(c.core.GetStoresWriteRate())
}
}
}
func (c *RaftCluster) runCoordinator() {
defer logutil.LogPanic()
defer c.wg.Done()
c.coordinator.runUntilStop()
}
func (c *RaftCluster) syncRegions() {
defer logutil.LogPanic()
defer c.wg.Done()
c.regionSyncer.RunServer(c.ctx, c.changedRegionNotifier())
}
func (c *RaftCluster) runReplicationMode() {
defer logutil.LogPanic()
defer c.wg.Done()
c.replicationMode.Run(c.ctx)
}
// Stop stops the cluster.
func (c *RaftCluster) Stop() {
c.Lock()
if !c.running {
c.Unlock()
return
}
c.running = false
c.coordinator.stop()
c.cancel()
c.Unlock()
c.wg.Wait()
log.Info("raftcluster is stopped")
}
// IsRunning return if the cluster is running.
func (c *RaftCluster) IsRunning() bool {
c.RLock()
defer c.RUnlock()
return c.running
}
// Context returns the context of RaftCluster.
func (c *RaftCluster) Context() context.Context {
c.RLock()
defer c.RUnlock()
if c.running {
return c.ctx
}
return nil
}
// GetCoordinator returns the coordinator.
func (c *RaftCluster) GetCoordinator() *coordinator {
return c.coordinator
}
// GetOperatorController returns the operator controller.
func (c *RaftCluster) GetOperatorController() *schedule.OperatorController {
return c.coordinator.opController
}
// GetRegionScatter returns the region scatter.
func (c *RaftCluster) GetRegionScatter() *schedule.RegionScatterer {
return c.coordinator.regionScatterer
}
// GetRegionSplitter returns the region splitter
func (c *RaftCluster) GetRegionSplitter() *schedule.RegionSplitter {
return c.coordinator.regionSplitter
}
// GetMergeChecker returns merge checker.
func (c *RaftCluster) GetMergeChecker() *checker.MergeChecker {
return c.coordinator.checkers.GetMergeChecker()
}
// GetSchedulers gets all schedulers.
func (c *RaftCluster) GetSchedulers() []string {
return c.coordinator.getSchedulers()
}
// GetSchedulerHandlers gets all scheduler handlers.
func (c *RaftCluster) GetSchedulerHandlers() map[string]http.Handler {
return c.coordinator.getSchedulerHandlers()
}
// AddScheduler adds a scheduler.
func (c *RaftCluster) AddScheduler(scheduler schedule.Scheduler, args ...string) error {
return c.coordinator.addScheduler(scheduler, args...)
}
// RemoveScheduler removes a scheduler.
func (c *RaftCluster) RemoveScheduler(name string) error {
return c.coordinator.removeScheduler(name)
}
// PauseOrResumeScheduler pauses or resumes a scheduler.
func (c *RaftCluster) PauseOrResumeScheduler(name string, t int64) error {
return c.coordinator.pauseOrResumeScheduler(name, t)
}
// IsSchedulerPaused checks if a scheduler is paused.
func (c *RaftCluster) IsSchedulerPaused(name string) (bool, error) {
return c.coordinator.isSchedulerPaused(name)
}
// IsSchedulerDisabled checks if a scheduler is disabled.
func (c *RaftCluster) IsSchedulerDisabled(name string) (bool, error) {
return c.coordinator.isSchedulerDisabled(name)
}
// IsSchedulerAllowed checks if a scheduler is allowed.
func (c *RaftCluster) IsSchedulerAllowed(name string) (bool, error) {
return c.coordinator.isSchedulerAllowed(name)
}
// IsSchedulerExisted checks if a scheduler is existed.
func (c *RaftCluster) IsSchedulerExisted(name string) (bool, error) {
return c.coordinator.isSchedulerExisted(name)
}
// PauseOrResumeChecker pauses or resumes checker.
func (c *RaftCluster) PauseOrResumeChecker(name string, t int64) error {
return c.coordinator.pauseOrResumeChecker(name, t)
}
// IsCheckerPaused returns if checker is paused
func (c *RaftCluster) IsCheckerPaused(name string) (bool, error) {
return c.coordinator.isCheckerPaused(name)
}
// GetAllocator returns cluster's id allocator.
func (c *RaftCluster) GetAllocator() id.Allocator {
return c.id
}
// GetRegionSyncer returns the region syncer.
func (c *RaftCluster) GetRegionSyncer() *syncer.RegionSyncer {
return c.regionSyncer
}
// GetReplicationMode returns the ReplicationMode.
func (c *RaftCluster) GetReplicationMode() *replication.ModeManager {
return c.replicationMode
}
// GetRuleManager returns the rule manager reference.
func (c *RaftCluster) GetRuleManager() *placement.RuleManager {
return c.ruleManager
}
// GetRegionLabeler returns the region labeler.
func (c *RaftCluster) GetRegionLabeler() *labeler.RegionLabeler {
return c.regionLabeler
}
// GetStorage returns the storage.
func (c *RaftCluster) GetStorage() storage.Storage {
c.RLock()
defer c.RUnlock()
return c.storage
}
// SetStorage set the storage for test purpose.
func (c *RaftCluster) SetStorage(s storage.Storage) {
c.Lock()
defer c.Unlock()
c.storage = s
}
// GetOpts returns cluster's configuration.
// There is no need a lock since it won't changed.
func (c *RaftCluster) GetOpts() *config.PersistOptions {
return c.opt
}
// AddSuspectRegions adds regions to suspect list.
func (c *RaftCluster) AddSuspectRegions(regionIDs ...uint64) {
c.coordinator.checkers.AddSuspectRegions(regionIDs...)
}
// GetSuspectRegions gets all suspect regions.
func (c *RaftCluster) GetSuspectRegions() []uint64 {
return c.coordinator.checkers.GetSuspectRegions()
}
// GetHotStat gets hot stat for test.
func (c *RaftCluster) GetHotStat() *statistics.HotStat {
return c.hotStat
}
// RemoveSuspectRegion removes region from suspect list.
func (c *RaftCluster) RemoveSuspectRegion(id uint64) {
c.coordinator.checkers.RemoveSuspectRegion(id)
}
// GetUnsafeRecoveryController returns the unsafe recovery controller.
func (c *RaftCluster) GetUnsafeRecoveryController() *unsafeRecoveryController {
return c.unsafeRecoveryController
}
// AddSuspectKeyRange adds the key range with the its ruleID as the key
// The instance of each keyRange is like following format:
// [2][]byte: start key/end key
func (c *RaftCluster) AddSuspectKeyRange(start, end []byte) {
c.coordinator.checkers.AddSuspectKeyRange(start, end)
}
// PopOneSuspectKeyRange gets one suspect keyRange group.
// it would return value and true if pop success, or return empty [][2][]byte and false
// if suspectKeyRanges couldn't pop keyRange group.
func (c *RaftCluster) PopOneSuspectKeyRange() ([2][]byte, bool) {
return c.coordinator.checkers.PopOneSuspectKeyRange()
}
// ClearSuspectKeyRanges clears the suspect keyRanges, only for unit test
func (c *RaftCluster) ClearSuspectKeyRanges() {
c.coordinator.checkers.ClearSuspectKeyRanges()
}
// HandleStoreHeartbeat updates the store status.
func (c *RaftCluster) HandleStoreHeartbeat(stats *pdpb.StoreStats) error {
storeID := stats.GetStoreId()
c.Lock()
defer c.Unlock()
store := c.GetStore(storeID)
if store == nil {
return errors.Errorf("store %v not found", storeID)
}
newStore := store.Clone(core.SetStoreStats(stats), core.SetLastHeartbeatTS(time.Now()))
if newStore.IsLowSpace(c.opt.GetLowSpaceRatio()) {
log.Warn("store does not have enough disk space",
zap.Uint64("store-id", storeID),
zap.Uint64("capacity", newStore.GetCapacity()),
zap.Uint64("available", newStore.GetAvailable()))
}
if newStore.NeedPersist() && c.storage != nil {
if err := c.storage.SaveStore(newStore.GetMeta()); err != nil {
log.Error("failed to persist store", zap.Uint64("store-id", storeID), errs.ZapError(err))
} else {
newStore = newStore.Clone(core.SetLastPersistTime(time.Now()))
}
}
if store := c.core.GetStore(storeID); store != nil {
statistics.UpdateStoreHeartbeatMetrics(store)
}
c.core.PutStore(newStore)
c.hotStat.Observe(storeID, newStore.GetStoreStats())
c.hotStat.FilterUnhealthyStore(c)
reportInterval := stats.GetInterval()
interval := reportInterval.GetEndTimestamp() - reportInterval.GetStartTimestamp()
// c.limiter is nil before "start" is called
if c.limiter != nil && c.opt.GetStoreLimitMode() == "auto" {
c.limiter.Collect(newStore.GetStoreStats())
}
regions := make(map[uint64]*core.RegionInfo, len(stats.GetPeerStats()))
for _, peerStat := range stats.GetPeerStats() {
regionID := peerStat.GetRegionId()
region := c.GetRegion(regionID)
regions[regionID] = region
if region == nil {
log.Warn("discard hot peer stat for unknown region",
zap.Uint64("region-id", regionID),
zap.Uint64("store-id", storeID))
continue
}
peer := region.GetStorePeer(storeID)
if peer == nil {
log.Warn("discard hot peer stat for unknown region peer",
zap.Uint64("region-id", regionID),
zap.Uint64("store-id", storeID))
continue
}
readQueryNum := core.GetReadQueryNum(peerStat.GetQueryStats())
loads := []float64{
statistics.RegionReadBytes: float64(peerStat.GetReadBytes()),
statistics.RegionReadKeys: float64(peerStat.GetReadKeys()),
statistics.RegionReadQuery: float64(readQueryNum),
statistics.RegionWriteBytes: 0,
statistics.RegionWriteKeys: 0,
statistics.RegionWriteQuery: 0,
}
peerInfo := core.NewPeerInfo(peer, loads, interval)
c.hotStat.CheckReadAsync(statistics.NewCheckPeerTask(peerInfo, region))
}
// Here we will compare the reported regions with the previous hot peers to decide if it is still hot.
c.hotStat.CheckReadAsync(statistics.NewCollectUnReportedPeerTask(storeID, regions, interval))
return nil
}
// processReportBuckets update the bucket information.
func (c *RaftCluster) processReportBuckets(buckets *metapb.Buckets) error {
region := c.core.GetRegion(buckets.GetRegionId())
if region == nil {
bucketEventCounter.WithLabelValues("region_cache_miss").Inc()
return errors.Errorf("region %v not found", buckets.GetRegionId())
}
// use CAS to update the bucket information.
// the two request(A:3,B:2) get the same region and need to update the buckets.
// the A will pass the check and set the version to 3, the B will fail because the region.bucket has changed.
// the retry should keep the old version and the new version will be set to the region.bucket, like two requests (A:2,B:3).
for retry := 0; retry < 3; retry++ {
old := region.GetBuckets()
// region should not update if the version of the buckets is less than the old one.
if old != nil && buckets.GetVersion() <= old.GetVersion() {
bucketEventCounter.WithLabelValues("version_not_match").Inc()
return nil
}
failpoint.Inject("concurrentBucketHeartbeat", func() {
time.Sleep(500 * time.Millisecond)
})
if ok := region.UpdateBuckets(buckets, old); ok {
return nil
}
}
bucketEventCounter.WithLabelValues("update_failed").Inc()
return nil
}
// IsPrepared return true if the prepare checker is ready.
func (c *RaftCluster) IsPrepared() bool {
return c.coordinator.prepareChecker.isPrepared()
}
var regionGuide = core.GenerateRegionGuideFunc(true)
// processRegionHeartbeat updates the region information.
func (c *RaftCluster) processRegionHeartbeat(region *core.RegionInfo) error {
origin, err := c.core.PreCheckPutRegion(region)
if err != nil {
return err
}
region.Inherit(origin)
c.hotStat.CheckWriteAsync(statistics.NewCheckExpiredItemTask(region))
c.hotStat.CheckReadAsync(statistics.NewCheckExpiredItemTask(region))
reportInterval := region.GetInterval()
interval := reportInterval.GetEndTimestamp() - reportInterval.GetStartTimestamp()
for _, peer := range region.GetPeers() {
peerInfo := core.NewPeerInfo(peer, region.GetWriteLoads(), interval)
c.hotStat.CheckWriteAsync(statistics.NewCheckPeerTask(peerInfo, region))
}
// Save to storage if meta is updated.
// Save to cache if meta or leader is updated, or contains any down/pending peer.
// Mark isNew if the region in cache does not have leader.
isNew, saveKV, saveCache, needSync := regionGuide(region, origin)
if !saveKV && !saveCache && !isNew {
return nil
}
failpoint.Inject("concurrentRegionHeartbeat", func() {
time.Sleep(500 * time.Millisecond)
})
var overlaps []*core.RegionInfo
c.Lock()
if saveCache {
// To prevent a concurrent heartbeat of another region from overriding the up-to-date region info by a stale one,
// check its validation again here.
//
// However it can't solve the race condition of concurrent heartbeats from the same region.
if _, err := c.core.PreCheckPutRegion(region); err != nil {
c.Unlock()
return err
}
overlaps = c.core.PutRegion(region)
for _, item := range overlaps {
if c.regionStats != nil {
c.regionStats.ClearDefunctRegion(item.GetID())
}
c.labelLevelStats.ClearDefunctRegion(item.GetID())
}
// Update related stores.
storeMap := make(map[uint64]struct{})
for _, p := range region.GetPeers() {
storeMap[p.GetStoreId()] = struct{}{}
}
if origin != nil {
for _, p := range origin.GetPeers() {
storeMap[p.GetStoreId()] = struct{}{}
}
}
for key := range storeMap {
c.updateStoreStatusLocked(key)
}
regionEventCounter.WithLabelValues("update_cache").Inc()
}
if !c.IsPrepared() && isNew {
c.coordinator.prepareChecker.collect(region)
}
if c.regionStats != nil {
c.regionStats.Observe(region, c.getRegionStoresLocked(region))
}
changedRegions := c.changedRegions
c.Unlock()
if c.storage != nil {
// If there are concurrent heartbeats from the same region, the last write will win even if
// writes to storage in the critical area. So don't use mutex to protect it.
// Not successfully saved to storage is not fatal, it only leads to longer warm-up
// after restart. Here we only log the error then go on updating cache.
for _, item := range overlaps {
if err := c.storage.DeleteRegion(item.GetMeta()); err != nil {
log.Error("failed to delete region from storage",
zap.Uint64("region-id", item.GetID()),
logutil.ZapRedactStringer("region-meta", core.RegionToHexMeta(item.GetMeta())),
errs.ZapError(err))
}
}
if saveKV {
if err := c.storage.SaveRegion(region.GetMeta()); err != nil {
log.Error("failed to save region to storage",
zap.Uint64("region-id", region.GetID()),
logutil.ZapRedactStringer("region-meta", core.RegionToHexMeta(region.GetMeta())),
errs.ZapError(err))
}
regionEventCounter.WithLabelValues("update_kv").Inc()
}
}
if saveKV || needSync {
select {
case changedRegions <- region:
default:
}
}
return nil
}
func (c *RaftCluster) updateStoreStatusLocked(id uint64) {
leaderCount := c.core.GetStoreLeaderCount(id)
regionCount := c.core.GetStoreRegionCount(id)
pendingPeerCount := c.core.GetStorePendingPeerCount(id)
leaderRegionSize := c.core.GetStoreLeaderRegionSize(id)
regionSize := c.core.GetStoreRegionSize(id)
c.core.UpdateStoreStatus(id, leaderCount, regionCount, pendingPeerCount, leaderRegionSize, regionSize)
}
func (c *RaftCluster) putMetaLocked(meta *metapb.Cluster) error {
if c.storage != nil {
if err := c.storage.SaveMeta(meta); err != nil {
return err
}
}
c.meta = meta
return nil
}
// GetBasicCluster returns the basic cluster.
func (c *RaftCluster) GetBasicCluster() *core.BasicCluster {
return c.core
}
// GetRegionByKey gets regionInfo by region key from cluster.
func (c *RaftCluster) GetRegionByKey(regionKey []byte) *core.RegionInfo {
return c.core.GetRegionByKey(regionKey)
}
// GetPrevRegionByKey gets previous region and leader peer by the region key from cluster.
func (c *RaftCluster) GetPrevRegionByKey(regionKey []byte) *core.RegionInfo {
return c.core.GetPrevRegionByKey(regionKey)
}
// ScanRegions scans region with start key, until the region contains endKey, or
// total number greater than limit.
func (c *RaftCluster) ScanRegions(startKey, endKey []byte, limit int) []*core.RegionInfo {
return c.core.ScanRange(startKey, endKey, limit)
}
// GetRegion searches for a region by ID.
func (c *RaftCluster) GetRegion(regionID uint64) *core.RegionInfo {
return c.core.GetRegion(regionID)
}
// GetMetaRegions gets regions from cluster.
func (c *RaftCluster) GetMetaRegions() []*metapb.Region {
return c.core.GetMetaRegions()
}
// GetRegions returns all regions' information in detail.
func (c *RaftCluster) GetRegions() []*core.RegionInfo {
return c.core.GetRegions()
}
// GetRegionCount returns total count of regions
func (c *RaftCluster) GetRegionCount() int {
return c.core.GetRegionCount()
}
// GetStoreRegions returns all regions' information with a given storeID.
func (c *RaftCluster) GetStoreRegions(storeID uint64) []*core.RegionInfo {
return c.core.GetStoreRegions(storeID)
}
// RandLeaderRegion returns a random region that has leader on the store.
func (c *RaftCluster) RandLeaderRegion(storeID uint64, ranges []core.KeyRange, opts ...core.RegionOption) *core.RegionInfo {
return c.core.RandLeaderRegion(storeID, ranges, opts...)
}
// RandFollowerRegion returns a random region that has a follower on the store.
func (c *RaftCluster) RandFollowerRegion(storeID uint64, ranges []core.KeyRange, opts ...core.RegionOption) *core.RegionInfo {
return c.core.RandFollowerRegion(storeID, ranges, opts...)
}
// RandPendingRegion returns a random region that has a pending peer on the store.
func (c *RaftCluster) RandPendingRegion(storeID uint64, ranges []core.KeyRange, opts ...core.RegionOption) *core.RegionInfo {
return c.core.RandPendingRegion(storeID, ranges, opts...)
}
// RandLearnerRegion returns a random region that has a learner peer on the store.
func (c *RaftCluster) RandLearnerRegion(storeID uint64, ranges []core.KeyRange, opts ...core.RegionOption) *core.RegionInfo {
return c.core.RandLearnerRegion(storeID, ranges, opts...)
}
// GetLeaderStore returns all stores that contains the region's leader peer.
func (c *RaftCluster) GetLeaderStore(region *core.RegionInfo) *core.StoreInfo {
return c.core.GetLeaderStore(region)
}
// GetFollowerStores returns all stores that contains the region's follower peer.
func (c *RaftCluster) GetFollowerStores(region *core.RegionInfo) []*core.StoreInfo {
return c.core.GetFollowerStores(region)
}
// GetRegionStores returns all stores that contains the region's peer.
func (c *RaftCluster) GetRegionStores(region *core.RegionInfo) []*core.StoreInfo {
return c.core.GetRegionStores(region)
}
// GetStoreCount returns the count of stores.
func (c *RaftCluster) GetStoreCount() int {
return c.core.GetStoreCount()
}
// GetStoreRegionCount returns the number of regions for a given store.
func (c *RaftCluster) GetStoreRegionCount(storeID uint64) int {
return c.core.GetStoreRegionCount(storeID)
}
// GetAverageRegionSize returns the average region approximate size.
func (c *RaftCluster) GetAverageRegionSize() int64 {
return c.core.GetAverageRegionSize()
}
// DropCacheRegion removes a region from the cache.
func (c *RaftCluster) DropCacheRegion(id uint64) {
c.core.RemoveRegionIfExist(id)
}
// DropCacheAllRegion removes all regions from the cache.
func (c *RaftCluster) DropCacheAllRegion() {
c.core.ResetRegionCache()
}
// GetMetaStores gets stores from cluster.