-
Notifications
You must be signed in to change notification settings - Fork 0
/
coordinator.go
676 lines (595 loc) · 17.7 KB
/
coordinator.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
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"container/list"
"context"
"fmt"
"sync"
"time"
"github.com/juju/errors"
"github.com/pingcap/kvproto/pkg/eraftpb"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
"github.com/pingcap/pd/pkg/logutil"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/namespace"
"github.com/pingcap/pd/server/schedule"
log "github.com/sirupsen/logrus"
)
const (
runSchedulerCheckInterval = 3 * time.Second
collectFactor = 0.8
historyKeepTime = 5 * time.Minute
maxScheduleRetries = 10
regionheartbeatSendChanCap = 1024
hotRegionScheduleName = "balance-hot-region-scheduler"
patrolRegionInterval = time.Millisecond * 100
patrolScanRegionLimit = 128 // It takes about 14 minutes to iterate 1 million regions.
)
var (
errSchedulerExisted = errors.New("scheduler existed")
errSchedulerNotFound = errors.New("scheduler not found")
)
type coordinator struct {
sync.RWMutex
wg sync.WaitGroup
ctx context.Context
cancel context.CancelFunc
cluster *clusterInfo
limiter *schedule.Limiter
replicaChecker *schedule.ReplicaChecker
regionScatterer *schedule.RegionScatterer
namespaceChecker *schedule.NamespaceChecker
mergeChecker *schedule.MergeChecker
operators map[uint64]*schedule.Operator
schedulers map[string]*scheduleController
classifier namespace.Classifier
histories *list.List
hbStreams *heartbeatStreams
}
func newCoordinator(cluster *clusterInfo, hbStreams *heartbeatStreams, classifier namespace.Classifier) *coordinator {
ctx, cancel := context.WithCancel(context.Background())
return &coordinator{
ctx: ctx,
cancel: cancel,
cluster: cluster,
limiter: schedule.NewLimiter(),
replicaChecker: schedule.NewReplicaChecker(cluster, classifier),
regionScatterer: schedule.NewRegionScatterer(cluster, classifier),
namespaceChecker: schedule.NewNamespaceChecker(cluster, classifier),
mergeChecker: schedule.NewMergeChecker(cluster, classifier),
operators: make(map[uint64]*schedule.Operator),
schedulers: make(map[string]*scheduleController),
classifier: classifier,
histories: list.New(),
hbStreams: hbStreams,
}
}
func (c *coordinator) dispatch(region *core.RegionInfo) {
// Check existed operator.
if op := c.getOperator(region.GetId()); op != nil {
timeout := op.IsTimeout()
if step := op.Check(region); step != nil && !timeout {
operatorCounter.WithLabelValues(op.Desc(), "check").Inc()
c.sendScheduleCommand(region, step)
return
}
if op.IsFinish() {
log.Infof("[region %v] operator finish: %s", region.GetId(), op)
operatorCounter.WithLabelValues(op.Desc(), "finish").Inc()
operatorDuration.WithLabelValues(op.Desc()).Observe(op.ElapsedTime().Seconds())
c.pushHistory(op)
c.removeOperator(op)
} else if timeout {
log.Infof("[region %v] operator timeout: %s", region.GetId(), op)
operatorCounter.WithLabelValues(op.Desc(), "timeout").Inc()
c.removeOperator(op)
}
}
// If PD has restarted, it need to check learners added before and promote them.
if c.cluster.IsRaftLearnerEnabled() && c.getOperator(region.GetId()) == nil {
for _, p := range region.GetLearners() {
if region.GetPendingLearner(p.GetId()) != nil {
continue
}
step := schedule.PromoteLearner{
ToStore: p.GetStoreId(),
PeerID: p.GetId(),
}
op := schedule.NewOperator("promoteLearner", region.GetId(), schedule.OpRegion, step)
c.addOperator(op)
break
}
}
}
func (c *coordinator) patrolRegions() {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(patrolRegionInterval)
defer ticker.Stop()
log.Info("coordinator: start patrol regions")
var key []byte
for {
select {
case <-ticker.C:
case <-c.ctx.Done():
return
}
regions := c.cluster.ScanRegions(key, patrolScanRegionLimit)
if len(regions) == 0 {
// reset scan key.
key = nil
continue
}
for _, region := range regions {
key = region.GetEndKey()
if op := c.namespaceChecker.Check(region); op != nil {
if c.addOperator(op) {
break
}
}
if c.limiter.OperatorCount(schedule.OpReplica) < c.cluster.GetReplicaScheduleLimit() {
if op := c.replicaChecker.Check(region); op != nil {
if c.addOperator(op) {
break
}
}
}
if c.limiter.OperatorCount(schedule.OpMerge) < c.cluster.GetMergeScheduleLimit() {
if op1, op2 := c.mergeChecker.Check(region); op1 != nil && op2 != nil {
// make sure two operators can add successfully altogether
if c.addOperators(op1, op2) {
break
}
}
}
}
// update label level isolation statistics.
c.cluster.updateRegionsLabelLevelStats(regions)
}
}
func (c *coordinator) run() {
ticker := time.NewTicker(runSchedulerCheckInterval)
defer ticker.Stop()
log.Info("coordinator: Start collect cluster information")
for {
if c.shouldRun() {
log.Info("coordinator: Cluster information is prepared")
break
}
select {
case <-ticker.C:
case <-c.ctx.Done():
log.Info("coordinator: Stopped coordinator")
return
}
}
log.Info("coordinator: Run scheduler")
k := 0
scheduleCfg := c.cluster.opt.load()
for _, schedulerCfg := range scheduleCfg.Schedulers {
if schedulerCfg.Disable {
continue
}
s, err := schedule.CreateScheduler(schedulerCfg.Type, c.limiter, schedulerCfg.Args...)
if err != nil {
log.Errorf("can not create scheduler %s: %v", schedulerCfg.Type, err)
} else {
log.Infof("create scheduler %s", s.GetName())
if err = c.addScheduler(s, schedulerCfg.Args...); err != nil {
log.Errorf("can not add scheduler %s: %v", s.GetName(), err)
}
}
// only record valid scheduler config
if err == nil {
scheduleCfg.Schedulers[k] = schedulerCfg
k++
}
}
// remove invalid scheduler config and persist
scheduleCfg.Schedulers = scheduleCfg.Schedulers[:k]
if err := c.cluster.opt.persist(c.cluster.kv); err != nil {
log.Errorf("can't persist schedule config: %v", err)
}
c.wg.Add(1)
go c.patrolRegions()
}
func (c *coordinator) stop() {
c.cancel()
c.wg.Wait()
}
// Hack to retrive info from scheduler.
// TODO: remove it.
type hasHotStatus interface {
GetHotReadStatus() *core.StoreHotRegionInfos
GetHotWriteStatus() *core.StoreHotRegionInfos
}
func (c *coordinator) getHotWriteRegions() *core.StoreHotRegionInfos {
c.RLock()
defer c.RUnlock()
s, ok := c.schedulers[hotRegionScheduleName]
if !ok {
return nil
}
if h, ok := s.Scheduler.(hasHotStatus); ok {
return h.GetHotWriteStatus()
}
return nil
}
func (c *coordinator) getHotReadRegions() *core.StoreHotRegionInfos {
c.RLock()
defer c.RUnlock()
s, ok := c.schedulers[hotRegionScheduleName]
if !ok {
return nil
}
if h, ok := s.Scheduler.(hasHotStatus); ok {
return h.GetHotReadStatus()
}
return nil
}
func (c *coordinator) getSchedulers() []string {
c.RLock()
defer c.RUnlock()
names := make([]string, 0, len(c.schedulers))
for name := range c.schedulers {
names = append(names, name)
}
return names
}
func (c *coordinator) collectSchedulerMetrics() {
c.RLock()
defer c.RUnlock()
for _, s := range c.schedulers {
var allowScheduler float64
if s.AllowSchedule() {
allowScheduler = 1
}
schedulerStatusGauge.WithLabelValues(s.GetName(), "allow").Set(allowScheduler)
}
}
func (c *coordinator) collectHotSpotMetrics() {
c.RLock()
defer c.RUnlock()
// collect hot write region metrics
s, ok := c.schedulers[hotRegionScheduleName]
if !ok {
return
}
stores := c.cluster.GetStores()
status := s.Scheduler.(hasHotStatus).GetHotWriteStatus()
for _, s := range stores {
store := fmt.Sprintf("store_%d", s.GetId())
stat, ok := status.AsPeer[s.GetId()]
if ok {
totalWriteBytes := float64(stat.TotalFlowBytes)
hotWriteRegionCount := float64(stat.RegionsCount)
hotSpotStatusGauge.WithLabelValues(store, "total_written_bytes_as_peer").Set(totalWriteBytes)
hotSpotStatusGauge.WithLabelValues(store, "hot_write_region_as_peer").Set(hotWriteRegionCount)
} else {
hotSpotStatusGauge.WithLabelValues(store, "total_written_bytes_as_peer").Set(0)
hotSpotStatusGauge.WithLabelValues(store, "hot_write_region_as_peer").Set(0)
}
stat, ok = status.AsLeader[s.GetId()]
if ok {
totalWriteBytes := float64(stat.TotalFlowBytes)
hotWriteRegionCount := float64(stat.RegionsCount)
hotSpotStatusGauge.WithLabelValues(store, "total_written_bytes_as_leader").Set(totalWriteBytes)
hotSpotStatusGauge.WithLabelValues(store, "hot_write_region_as_leader").Set(hotWriteRegionCount)
} else {
hotSpotStatusGauge.WithLabelValues(store, "total_written_bytes_as_leader").Set(0)
hotSpotStatusGauge.WithLabelValues(store, "hot_write_region_as_leader").Set(0)
}
}
// collect hot read region metrics
status = s.Scheduler.(hasHotStatus).GetHotReadStatus()
for _, s := range stores {
store := fmt.Sprintf("store_%d", s.GetId())
stat, ok := status.AsLeader[s.GetId()]
if ok {
totalReadBytes := float64(stat.TotalFlowBytes)
hotReadRegionCount := float64(stat.RegionsCount)
hotSpotStatusGauge.WithLabelValues(store, "total_read_bytes_as_leader").Set(totalReadBytes)
hotSpotStatusGauge.WithLabelValues(store, "hot_read_region_as_leader").Set(hotReadRegionCount)
} else {
hotSpotStatusGauge.WithLabelValues(store, "total_read_bytes_as_leader").Set(0)
hotSpotStatusGauge.WithLabelValues(store, "hot_read_region_as_leader").Set(0)
}
}
}
func (c *coordinator) shouldRun() bool {
return c.cluster.isPrepared()
}
func (c *coordinator) addScheduler(scheduler schedule.Scheduler, args ...string) error {
c.Lock()
defer c.Unlock()
if _, ok := c.schedulers[scheduler.GetName()]; ok {
return errSchedulerExisted
}
s := newScheduleController(c, scheduler)
if err := s.Prepare(c.cluster); err != nil {
return errors.Trace(err)
}
c.wg.Add(1)
go c.runScheduler(s)
c.schedulers[s.GetName()] = s
c.cluster.opt.AddSchedulerCfg(s.GetType(), args)
return nil
}
func (c *coordinator) removeScheduler(name string) error {
c.Lock()
defer c.Unlock()
s, ok := c.schedulers[name]
if !ok {
return errSchedulerNotFound
}
s.Stop()
delete(c.schedulers, name)
if err := c.cluster.opt.RemoveSchedulerCfg(name); err != nil {
return errors.Trace(err)
}
return nil
}
func (c *coordinator) runScheduler(s *scheduleController) {
defer logutil.LogPanic()
defer c.wg.Done()
defer s.Cleanup(c.cluster)
timer := time.NewTimer(s.GetInterval())
defer timer.Stop()
for {
select {
case <-timer.C:
timer.Reset(s.GetInterval())
if !s.AllowSchedule() {
continue
}
opInfluence := schedule.NewOpInfluence(c.getOperators(), c.cluster)
if op := s.Schedule(c.cluster, opInfluence); op != nil {
if len(op) == 1 {
c.addOperator(op[0])
} else {
c.addOperators(op...)
}
}
case <-s.Ctx().Done():
log.Infof("%v stopped: %v", s.GetName(), s.Ctx().Err())
return
}
}
}
func (c *coordinator) addOperatorLocked(op *schedule.Operator) bool {
regionID := op.RegionID()
log.Infof("[region %v] add operator: %s", regionID, op)
// If the new operator passed in has higher priorities than the old one,
// then replace the old operator.
if old, ok := c.operators[regionID]; ok {
if !isHigherPriorityOperator(op, old) {
log.Infof("[region %v] cancel add operator, old: %s", regionID, old)
return false
}
log.Infof("[region %v] replace old operator: %s", regionID, old)
operatorCounter.WithLabelValues(old.Desc(), "replaced").Inc()
c.removeOperatorLocked(old)
}
c.operators[regionID] = op
c.limiter.UpdateCounts(c.operators)
if region := c.cluster.GetRegion(op.RegionID()); region != nil {
if step := op.Check(region); step != nil {
c.sendScheduleCommand(region, step)
}
}
operatorCounter.WithLabelValues(op.Desc(), "create").Inc()
return true
}
func (c *coordinator) addOperator(op *schedule.Operator) bool {
c.Lock()
defer c.Unlock()
return c.addOperatorLocked(op)
}
func (c *coordinator) addOperators(ops ...*schedule.Operator) bool {
c.Lock()
defer c.Unlock()
for _, op := range ops {
if old := c.operators[op.RegionID()]; old != nil && !isHigherPriorityOperator(op, old) {
log.Infof("[region %v] cancel add operators, old: %s", op.RegionID(), old)
return false
}
}
for _, op := range ops {
c.addOperatorLocked(op)
}
return true
}
func isHigherPriorityOperator(new, old *schedule.Operator) bool {
return new.GetPriorityLevel() < old.GetPriorityLevel()
}
func (c *coordinator) pushHistory(op *schedule.Operator) {
c.Lock()
defer c.Unlock()
for _, h := range op.History() {
c.histories.PushFront(h)
}
}
func (c *coordinator) pruneHistory() {
c.Lock()
defer c.Unlock()
p := c.histories.Back()
for p != nil && time.Since(p.Value.(schedule.OperatorHistory).FinishTime) > historyKeepTime {
prev := p.Prev()
c.histories.Remove(p)
p = prev
}
}
func (c *coordinator) removeOperator(op *schedule.Operator) {
c.Lock()
defer c.Unlock()
c.removeOperatorLocked(op)
}
func (c *coordinator) removeOperatorLocked(op *schedule.Operator) {
regionID := op.RegionID()
delete(c.operators, regionID)
c.limiter.UpdateCounts(c.operators)
operatorCounter.WithLabelValues(op.Desc(), "remove").Inc()
}
func (c *coordinator) getOperator(regionID uint64) *schedule.Operator {
c.RLock()
defer c.RUnlock()
return c.operators[regionID]
}
func (c *coordinator) getOperators() []*schedule.Operator {
c.RLock()
defer c.RUnlock()
operators := make([]*schedule.Operator, 0, len(c.operators))
for _, op := range c.operators {
operators = append(operators, op)
}
return operators
}
func (c *coordinator) getHistory(start time.Time) []schedule.OperatorHistory {
c.RLock()
defer c.RUnlock()
histories := make([]schedule.OperatorHistory, 0, c.histories.Len())
for p := c.histories.Front(); p != nil; p = p.Next() {
history := p.Value.(schedule.OperatorHistory)
if history.FinishTime.Before(start) {
break
}
histories = append(histories, history)
}
return histories
}
func (c *coordinator) sendScheduleCommand(region *core.RegionInfo, step schedule.OperatorStep) {
log.Infof("[region %v] send schedule command: %s", region.GetId(), step)
switch s := step.(type) {
case schedule.TransferLeader:
cmd := &pdpb.RegionHeartbeatResponse{
TransferLeader: &pdpb.TransferLeader{
Peer: region.GetStorePeer(s.ToStore),
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.AddPeer:
if region.GetStorePeer(s.ToStore) != nil {
// The newly added peer is pending.
return
}
cmd := &pdpb.RegionHeartbeatResponse{
ChangePeer: &pdpb.ChangePeer{
ChangeType: eraftpb.ConfChangeType_AddNode,
Peer: &metapb.Peer{
Id: s.PeerID,
StoreId: s.ToStore,
},
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.AddLearner:
if region.GetStorePeer(s.ToStore) != nil {
// The newly added peer is pending.
return
}
cmd := &pdpb.RegionHeartbeatResponse{
ChangePeer: &pdpb.ChangePeer{
ChangeType: eraftpb.ConfChangeType_AddLearnerNode,
Peer: &metapb.Peer{
Id: s.PeerID,
StoreId: s.ToStore,
IsLearner: true,
},
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.PromoteLearner:
cmd := &pdpb.RegionHeartbeatResponse{
ChangePeer: &pdpb.ChangePeer{
// reuse AddNode type
ChangeType: eraftpb.ConfChangeType_AddNode,
Peer: &metapb.Peer{
Id: s.PeerID,
StoreId: s.ToStore,
},
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.RemovePeer:
cmd := &pdpb.RegionHeartbeatResponse{
ChangePeer: &pdpb.ChangePeer{
ChangeType: eraftpb.ConfChangeType_RemoveNode,
Peer: region.GetStorePeer(s.FromStore),
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.MergeRegion:
if s.IsPassive {
return
}
cmd := &pdpb.RegionHeartbeatResponse{
Merge: &pdpb.Merge{
Target: s.ToRegion,
},
}
c.hbStreams.sendMsg(region, cmd)
case schedule.SplitRegion:
cmd := &pdpb.RegionHeartbeatResponse{
SplitRegion: &pdpb.SplitRegion{},
}
c.hbStreams.sendMsg(region, cmd)
default:
log.Errorf("unknown operatorStep: %v", step)
}
}
type scheduleController struct {
schedule.Scheduler
cluster *clusterInfo
limiter *schedule.Limiter
classifier namespace.Classifier
nextInterval time.Duration
ctx context.Context
cancel context.CancelFunc
}
func newScheduleController(c *coordinator, s schedule.Scheduler) *scheduleController {
ctx, cancel := context.WithCancel(c.ctx)
return &scheduleController{
Scheduler: s,
cluster: c.cluster,
limiter: c.limiter,
nextInterval: s.GetMinInterval(),
classifier: c.classifier,
ctx: ctx,
cancel: cancel,
}
}
func (s *scheduleController) Ctx() context.Context {
return s.ctx
}
func (s *scheduleController) Stop() {
s.cancel()
}
func (s *scheduleController) Schedule(cluster schedule.Cluster, opInfluence schedule.OpInfluence) []*schedule.Operator {
for i := 0; i < maxScheduleRetries; i++ {
// If we have schedule, reset interval to the minimal interval.
if op := scheduleByNamespace(cluster, s.classifier, s.Scheduler, opInfluence); op != nil {
s.nextInterval = s.Scheduler.GetMinInterval()
return op
}
}
s.nextInterval = s.Scheduler.GetNextInterval(s.nextInterval)
return nil
}
func (s *scheduleController) GetInterval() time.Duration {
return s.nextInterval
}
func (s *scheduleController) AllowSchedule() bool {
return s.Scheduler.IsScheduleAllowed(s.cluster)
}