-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
636 lines (553 loc) · 18 KB
/
handler.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
// 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 (
"bytes"
"strconv"
"strings"
"time"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
log "github.com/pingcap/log"
"github.com/pingcap/pd/server/core"
"github.com/pingcap/pd/server/schedule"
"github.com/pkg/errors"
"go.uber.org/zap"
)
var (
// ErrNotBootstrapped is error info for cluster not bootstrapped
ErrNotBootstrapped = errors.New("TiKV cluster not bootstrapped, please start TiKV first")
// ErrOperatorNotFound is error info for operator not found
ErrOperatorNotFound = errors.New("operator not found")
// ErrAddOperator is error info for already have an operator when adding operator
ErrAddOperator = errors.New("failed to add operator, maybe already have one")
// ErrRegionNotAdjacent is error info for region not adjacent
ErrRegionNotAdjacent = errors.New("two regions are not adjacent")
// ErrRegionNotFound is error info for region not found
ErrRegionNotFound = func(regionID uint64) error {
return errors.Errorf("region %v not found", regionID)
}
// ErrRegionAbnormalPeer is error info for region has abonormal peer
ErrRegionAbnormalPeer = func(regionID uint64) error {
return errors.Errorf("region %v has abnormal peer", regionID)
}
// ErrRegionIsStale is error info for region is stale
ErrRegionIsStale = func(region *metapb.Region, origin *metapb.Region) error {
return errors.Errorf("region is stale: region %v origin %v", region, origin)
}
)
// Handler is a helper to export methods to handle API/RPC requests.
type Handler struct {
s *Server
opt *scheduleOption
}
func newHandler(s *Server) *Handler {
return &Handler{s: s, opt: s.scheduleOpt}
}
func (h *Handler) getCoordinator() (*coordinator, error) {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil, errors.WithStack(ErrNotBootstrapped)
}
return cluster.coordinator, nil
}
// GetSchedulers returns all names of schedulers.
func (h *Handler) GetSchedulers() ([]string, error) {
c, err := h.getCoordinator()
if err != nil {
return nil, err
}
return c.getSchedulers(), nil
}
// GetStores returns all stores in the cluster.
func (h *Handler) GetStores() ([]*core.StoreInfo, error) {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil, errors.WithStack(ErrNotBootstrapped)
}
storeMetas := cluster.GetStores()
stores := make([]*core.StoreInfo, 0, len(storeMetas))
for _, s := range storeMetas {
store, err := cluster.GetStore(s.GetId())
if err != nil {
return nil, err
}
stores = append(stores, store)
}
return stores, nil
}
// GetHotWriteRegions gets all hot write regions stats.
func (h *Handler) GetHotWriteRegions() *core.StoreHotRegionInfos {
c, err := h.getCoordinator()
if err != nil {
return nil
}
return c.getHotWriteRegions()
}
// GetHotReadRegions gets all hot read regions stats.
func (h *Handler) GetHotReadRegions() *core.StoreHotRegionInfos {
c, err := h.getCoordinator()
if err != nil {
return nil
}
return c.getHotReadRegions()
}
// GetHotBytesWriteStores gets all hot write stores stats.
func (h *Handler) GetHotBytesWriteStores() map[uint64]uint64 {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil
}
return cluster.cachedCluster.getStoresBytesWriteStat()
}
// GetHotBytesReadStores gets all hot write stores stats.
func (h *Handler) GetHotBytesReadStores() map[uint64]uint64 {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil
}
return cluster.cachedCluster.getStoresBytesReadStat()
}
// GetHotKeysWriteStores gets all hot write stores stats.
func (h *Handler) GetHotKeysWriteStores() map[uint64]uint64 {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil
}
return cluster.cachedCluster.getStoresKeysWriteStat()
}
// GetHotKeysReadStores gets all hot write stores stats.
func (h *Handler) GetHotKeysReadStores() map[uint64]uint64 {
cluster := h.s.GetRaftCluster()
if cluster == nil {
return nil
}
return cluster.cachedCluster.getStoresKeysReadStat()
}
// AddScheduler adds a scheduler.
func (h *Handler) AddScheduler(name string, args ...string) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
s, err := schedule.CreateScheduler(name, c.limiter, args...)
if err != nil {
return err
}
log.Info("create scheduler", zap.String("scheduler-name", s.GetName()))
if err = c.addScheduler(s, args...); err != nil {
log.Error("can not add scheduler", zap.String("scheduler-name", s.GetName()), zap.Error(err))
} else if err = h.opt.persist(c.cluster.kv); err != nil {
log.Error("can not persist scheduler config", zap.Error(err))
}
return err
}
// RemoveScheduler removes a scheduler by name.
func (h *Handler) RemoveScheduler(name string) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
if err = c.removeScheduler(name); err != nil {
log.Error("can not remove scheduler", zap.String("scheduler-name", name), zap.Error(err))
} else if err = h.opt.persist(c.cluster.kv); err != nil {
log.Error("can not persist scheduler config", zap.Error(err))
}
return err
}
// AddBalanceLeaderScheduler adds a balance-leader-scheduler.
func (h *Handler) AddBalanceLeaderScheduler() error {
return h.AddScheduler("balance-leader")
}
// AddBalanceRegionScheduler adds a balance-region-scheduler.
func (h *Handler) AddBalanceRegionScheduler() error {
return h.AddScheduler("balance-region")
}
// AddBalanceHotRegionScheduler adds a balance-hot-region-scheduler.
func (h *Handler) AddBalanceHotRegionScheduler() error {
return h.AddScheduler("hot-region")
}
// AddLabelScheduler adds a label-scheduler.
func (h *Handler) AddLabelScheduler() error {
return h.AddScheduler("label")
}
// AddScatterRangeScheduler adds a balance-range-leader-scheduler
func (h *Handler) AddScatterRangeScheduler(args ...string) error {
return h.AddScheduler("scatter-range", args...)
}
// AddAdjacentRegionScheduler adds a balance-adjacent-region-scheduler.
func (h *Handler) AddAdjacentRegionScheduler(args ...string) error {
return h.AddScheduler("adjacent-region", args...)
}
// AddGrantLeaderScheduler adds a grant-leader-scheduler.
func (h *Handler) AddGrantLeaderScheduler(storeID uint64) error {
return h.AddScheduler("grant-leader", strconv.FormatUint(storeID, 10))
}
// AddEvictLeaderScheduler adds an evict-leader-scheduler.
func (h *Handler) AddEvictLeaderScheduler(storeID uint64) error {
return h.AddScheduler("evict-leader", strconv.FormatUint(storeID, 10))
}
// AddShuffleLeaderScheduler adds a shuffle-leader-scheduler.
func (h *Handler) AddShuffleLeaderScheduler() error {
return h.AddScheduler("shuffle-leader")
}
// AddShuffleRegionScheduler adds a shuffle-region-scheduler.
func (h *Handler) AddShuffleRegionScheduler() error {
return h.AddScheduler("shuffle-region")
}
// AddRandomMergeScheduler adds a random-merge-scheduler.
func (h *Handler) AddRandomMergeScheduler() error {
return h.AddScheduler("random-merge")
}
// GetOperator returns the region operator.
func (h *Handler) GetOperator(regionID uint64) (*schedule.Operator, error) {
c, err := h.getCoordinator()
if err != nil {
return nil, err
}
op := c.getOperator(regionID)
if op == nil {
return nil, ErrOperatorNotFound
}
return op, nil
}
// RemoveOperator removes the region operator.
func (h *Handler) RemoveOperator(regionID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
op := c.getOperator(regionID)
if op == nil {
return ErrOperatorNotFound
}
c.removeOperator(op)
return nil
}
// GetOperators returns the running operators.
func (h *Handler) GetOperators() ([]*schedule.Operator, error) {
c, err := h.getCoordinator()
if err != nil {
return nil, err
}
return c.getOperators(), nil
}
// GetAdminOperators returns the running admin operators.
func (h *Handler) GetAdminOperators() ([]*schedule.Operator, error) {
return h.GetOperatorsOfKind(schedule.OpAdmin)
}
// GetLeaderOperators returns the running leader operators.
func (h *Handler) GetLeaderOperators() ([]*schedule.Operator, error) {
return h.GetOperatorsOfKind(schedule.OpLeader)
}
// GetRegionOperators returns the running region operators.
func (h *Handler) GetRegionOperators() ([]*schedule.Operator, error) {
return h.GetOperatorsOfKind(schedule.OpRegion)
}
// GetOperatorsOfKind returns the running operators of the kind.
func (h *Handler) GetOperatorsOfKind(mask schedule.OperatorKind) ([]*schedule.Operator, error) {
ops, err := h.GetOperators()
if err != nil {
return nil, err
}
var results []*schedule.Operator
for _, op := range ops {
if op.Kind()&mask != 0 {
results = append(results, op)
}
}
return results, nil
}
// GetHistory returns finished operators' history since start.
func (h *Handler) GetHistory(start time.Time) ([]schedule.OperatorHistory, error) {
c, err := h.getCoordinator()
if err != nil {
return nil, err
}
return c.getHistory(start), nil
}
var errAddOperator = errors.New("failed to add operator, maybe already have one")
// AddTransferLeaderOperator adds an operator to transfer leader to the store.
func (h *Handler) AddTransferLeaderOperator(regionID uint64, storeID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
newLeader := region.GetStoreVoter(storeID)
if newLeader == nil {
return errors.Errorf("region has no voter in store %v", storeID)
}
step := schedule.TransferLeader{FromStore: region.GetLeader().GetStoreId(), ToStore: newLeader.GetStoreId()}
op := schedule.NewOperator("adminTransferLeader", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpLeader, step)
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddTransferRegionOperator adds an operator to transfer region to the stores.
func (h *Handler) AddTransferRegionOperator(regionID uint64, storeIDs map[uint64]struct{}) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
var steps []schedule.OperatorStep
// Add missing peers.
for id := range storeIDs {
if c.cluster.GetStore(id) == nil {
return core.NewStoreNotFoundErr(id)
}
if region.GetStorePeer(id) != nil {
continue
}
peer, err := c.cluster.AllocPeer(id)
if err != nil {
return err
}
if c.cluster.IsRaftLearnerEnabled() {
steps = append(steps,
schedule.AddLearner{ToStore: id, PeerID: peer.Id},
schedule.PromoteLearner{ToStore: id, PeerID: peer.Id},
)
} else {
steps = append(steps, schedule.AddPeer{ToStore: id, PeerID: peer.Id})
}
}
// Remove redundant peers.
for _, peer := range region.GetPeers() {
if _, ok := storeIDs[peer.GetStoreId()]; ok {
continue
}
steps = append(steps, schedule.RemovePeer{FromStore: peer.GetStoreId()})
}
op := schedule.NewOperator("adminMoveRegion", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpRegion, steps...)
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddTransferPeerOperator adds an operator to transfer peer.
func (h *Handler) AddTransferPeerOperator(regionID uint64, fromStoreID, toStoreID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
oldPeer := region.GetStorePeer(fromStoreID)
if oldPeer == nil {
return errors.Errorf("region has no peer in store %v", fromStoreID)
}
if c.cluster.GetStore(toStoreID) == nil {
return core.NewStoreNotFoundErr(toStoreID)
}
newPeer, err := c.cluster.AllocPeer(toStoreID)
if err != nil {
return err
}
op, err := schedule.CreateMovePeerOperator("adminMovePeer", c.cluster, region, schedule.OpAdmin, fromStoreID, toStoreID, newPeer.GetId())
if err != nil {
return err
}
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddAddPeerOperator adds an operator to add peer.
func (h *Handler) AddAddPeerOperator(regionID uint64, toStoreID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
if region.GetStorePeer(toStoreID) != nil {
return errors.Errorf("region already has peer in store %v", toStoreID)
}
if c.cluster.GetStore(toStoreID) == nil {
return core.NewStoreNotFoundErr(toStoreID)
}
newPeer, err := c.cluster.AllocPeer(toStoreID)
if err != nil {
return err
}
var steps []schedule.OperatorStep
if c.cluster.IsRaftLearnerEnabled() {
steps = []schedule.OperatorStep{
schedule.AddLearner{ToStore: toStoreID, PeerID: newPeer.GetId()},
schedule.PromoteLearner{ToStore: toStoreID, PeerID: newPeer.GetId()},
}
} else {
steps = []schedule.OperatorStep{
schedule.AddPeer{ToStore: toStoreID, PeerID: newPeer.GetId()},
}
}
op := schedule.NewOperator("adminAddPeer", regionID, region.GetRegionEpoch(), schedule.OpAdmin|schedule.OpRegion, steps...)
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddRemovePeerOperator adds an operator to remove peer.
func (h *Handler) AddRemovePeerOperator(regionID uint64, fromStoreID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
if region.GetStorePeer(fromStoreID) == nil {
return errors.Errorf("region has no peer in store %v", fromStoreID)
}
op, err := schedule.CreateRemovePeerOperator("adminRemovePeer", c.cluster, schedule.OpAdmin, region, fromStoreID)
if err != nil {
return err
}
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddMergeRegionOperator adds an operator to merge region.
func (h *Handler) AddMergeRegionOperator(regionID uint64, targetID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
target := c.cluster.GetRegion(targetID)
if target == nil {
return ErrRegionNotFound(targetID)
}
if len(region.GetDownPeers()) > 0 || len(region.GetPendingPeers()) > 0 || len(region.GetLearners()) > 0 ||
len(region.GetPeers()) != c.cluster.GetMaxReplicas() {
return ErrRegionAbnormalPeer(regionID)
}
if len(target.GetDownPeers()) > 0 || len(target.GetPendingPeers()) > 0 || len(target.GetLearners()) > 0 ||
len(target.GetMeta().GetPeers()) != c.cluster.GetMaxReplicas() {
return ErrRegionAbnormalPeer(targetID)
}
// for the case first region (start key is nil) with the last region (end key is nil) but not adjacent
if (bytes.Equal(region.GetStartKey(), target.GetEndKey()) || len(region.GetStartKey()) == 0) &&
(bytes.Equal(region.GetEndKey(), target.GetStartKey()) || len(region.GetEndKey()) == 0) {
return ErrRegionNotAdjacent
}
op1, op2, err := schedule.CreateMergeRegionOperator("adminMergeRegion", c.cluster, region, target, schedule.OpAdmin)
if err != nil {
return err
}
if ok := c.addOperator(op1, op2); !ok {
return errors.WithStack(ErrAddOperator)
}
return nil
}
// AddSplitRegionOperator adds an operator to split a region.
func (h *Handler) AddSplitRegionOperator(regionID uint64, policy string) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
step := schedule.SplitRegion{
StartKey: region.GetStartKey(),
EndKey: region.GetEndKey(),
Policy: pdpb.CheckPolicy(pdpb.CheckPolicy_value[strings.ToUpper(policy)]),
}
op := schedule.NewOperator("adminSplitRegion", regionID, region.GetRegionEpoch(), schedule.OpAdmin, step)
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// AddScatterRegionOperator adds an operator to scatter a region.
func (h *Handler) AddScatterRegionOperator(regionID uint64) error {
c, err := h.getCoordinator()
if err != nil {
return err
}
region := c.cluster.GetRegion(regionID)
if region == nil {
return ErrRegionNotFound(regionID)
}
op, err := c.regionScatterer.Scatter(region)
if err != nil {
return err
}
if op == nil {
return nil
}
if ok := c.addOperator(op); !ok {
return errors.WithStack(errAddOperator)
}
return nil
}
// GetDownPeerRegions gets the region with down peer.
func (h *Handler) GetDownPeerRegions() ([]*core.RegionInfo, error) {
c := h.s.GetRaftCluster()
if c == nil {
return nil, ErrNotBootstrapped
}
return c.cachedCluster.GetRegionStatsByType(downPeer), nil
}
// GetExtraPeerRegions gets the region exceeds the specified number of peers.
func (h *Handler) GetExtraPeerRegions() ([]*core.RegionInfo, error) {
c := h.s.GetRaftCluster()
if c == nil {
return nil, ErrNotBootstrapped
}
return c.cachedCluster.GetRegionStatsByType(extraPeer), nil
}
// GetMissPeerRegions gets the region less than the specified number of peers.
func (h *Handler) GetMissPeerRegions() ([]*core.RegionInfo, error) {
c := h.s.GetRaftCluster()
if c == nil {
return nil, ErrNotBootstrapped
}
return c.cachedCluster.GetRegionStatsByType(missPeer), nil
}
// GetPendingPeerRegions gets the region with pending peer.
func (h *Handler) GetPendingPeerRegions() ([]*core.RegionInfo, error) {
c := h.s.GetRaftCluster()
if c == nil {
return nil, ErrNotBootstrapped
}
return c.cachedCluster.GetRegionStatsByType(pendingPeer), nil
}
// GetIncorrectNamespaceRegions gets the region with incorrect namespace peer.
func (h *Handler) GetIncorrectNamespaceRegions() ([]*core.RegionInfo, error) {
c := h.s.GetRaftCluster()
if c == nil {
return nil, ErrNotBootstrapped
}
return c.cachedCluster.GetRegionStatsByType(incorrectNamespace), nil
}