forked from tikv/pd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cluster.go
540 lines (449 loc) · 14 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
// 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 (
"fmt"
"path"
"sync"
"time"
"github.com/juju/errors"
"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"
log "github.com/sirupsen/logrus"
)
const (
backgroundJobInterval = time.Minute
)
// 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 {
sync.RWMutex
s *Server
running bool
clusterID uint64
clusterRoot string
// cached cluster info
cachedCluster *clusterInfo
coordinator *coordinator
wg sync.WaitGroup
quit chan struct{}
}
// ClusterStatus saves some state information
type ClusterStatus struct {
RaftBootstrapTime time.Time `json:"raft_bootstrap_time,omitempty"`
}
func newRaftCluster(s *Server, clusterID uint64) *RaftCluster {
return &RaftCluster{
s: s,
running: false,
clusterID: clusterID,
clusterRoot: s.getClusterRootPath(),
}
}
func (c *RaftCluster) loadClusterStatus() (*ClusterStatus, error) {
data, err := c.s.kv.Load((c.s.kv.ClusterStatePath("raft_bootstrap_time")))
if err != nil {
return nil, errors.Trace(err)
}
if len(data) == 0 {
return &ClusterStatus{}, nil
}
t, err := parseTimestamp([]byte(data))
if err != nil {
return nil, errors.Trace(err)
}
return &ClusterStatus{RaftBootstrapTime: t}, nil
}
func (c *RaftCluster) start() error {
c.Lock()
defer c.Unlock()
if c.running {
log.Warn("raft cluster has already been started")
return nil
}
cluster, err := loadClusterInfo(c.s.idAlloc, c.s.kv, c.s.scheduleOpt)
if err != nil {
return errors.Trace(err)
}
if cluster == nil {
return nil
}
c.cachedCluster = cluster
c.coordinator = newCoordinator(c.cachedCluster, c.s.hbStreams, c.s.classifier)
c.cachedCluster.regionStats = newRegionStatistics(c.s.scheduleOpt, c.s.classifier)
c.quit = make(chan struct{})
c.wg.Add(2)
go c.runCoordinator()
go c.runBackgroundJobs(backgroundJobInterval)
c.running = true
return nil
}
func (c *RaftCluster) runCoordinator() {
defer logutil.LogPanic()
c.coordinator.run()
c.wg.Done()
}
func (c *RaftCluster) stop() {
c.Lock()
defer c.Unlock()
if !c.running {
return
}
c.running = false
close(c.quit)
c.coordinator.stop()
c.wg.Wait()
}
func (c *RaftCluster) isRunning() bool {
c.RLock()
defer c.RUnlock()
return c.running
}
func makeStoreKey(clusterRootPath string, storeID uint64) string {
return path.Join(clusterRootPath, "s", fmt.Sprintf("%020d", storeID))
}
func makeRegionKey(clusterRootPath string, regionID uint64) string {
return path.Join(clusterRootPath, "r", fmt.Sprintf("%020d", regionID))
}
func makeRaftClusterStatusPrefix(clusterRootPath string) string {
return path.Join(clusterRootPath, "status")
}
func makeBootstrapTimeKey(clusterRootPath string) string {
return path.Join(makeRaftClusterStatusPrefix(clusterRootPath), "raft_bootstrap_time")
}
func checkBootstrapRequest(clusterID uint64, req *pdpb.BootstrapRequest) error {
// TODO: do more check for request fields validation.
storeMeta := req.GetStore()
if storeMeta == nil {
return errors.Errorf("missing store meta for bootstrap %d", clusterID)
} else if storeMeta.GetId() == 0 {
return errors.New("invalid zero store id")
}
regionMeta := req.GetRegion()
if regionMeta == nil {
return errors.Errorf("missing region meta for bootstrap %d", clusterID)
} else if len(regionMeta.GetStartKey()) > 0 || len(regionMeta.GetEndKey()) > 0 {
// first region start/end key must be empty
return errors.Errorf("invalid first region key range, must all be empty for bootstrap %d", clusterID)
} else if regionMeta.GetId() == 0 {
return errors.New("invalid zero region id")
}
peers := regionMeta.GetPeers()
if len(peers) != 1 {
return errors.Errorf("invalid first region peer count %d, must be 1 for bootstrap %d", len(peers), clusterID)
}
peer := peers[0]
if peer.GetStoreId() != storeMeta.GetId() {
return errors.Errorf("invalid peer store id %d != %d for bootstrap %d", peer.GetStoreId(), storeMeta.GetId(), clusterID)
}
if peer.GetId() == 0 {
return errors.New("invalid zero peer id")
}
return nil
}
// GetRegionByKey gets region and leader peer by region key from cluster.
func (c *RaftCluster) GetRegionByKey(regionKey []byte) (*metapb.Region, *metapb.Peer) {
region := c.cachedCluster.searchRegion(regionKey)
if region == nil {
return nil, nil
}
return region.Region, region.Leader
}
// GetRegionInfoByKey gets regionInfo by region key from cluster.
func (c *RaftCluster) GetRegionInfoByKey(regionKey []byte) *core.RegionInfo {
return c.cachedCluster.searchRegion(regionKey)
}
// GetRegionByID gets region and leader peer by regionID from cluster.
func (c *RaftCluster) GetRegionByID(regionID uint64) (*metapb.Region, *metapb.Peer) {
region := c.cachedCluster.GetRegion(regionID)
if region == nil {
return nil, nil
}
return region.Region, region.Leader
}
// GetRegionInfoByID gets regionInfo by regionID from cluster.
func (c *RaftCluster) GetRegionInfoByID(regionID uint64) *core.RegionInfo {
return c.cachedCluster.GetRegion(regionID)
}
// GetMetaRegions gets regions from cluster.
func (c *RaftCluster) GetMetaRegions() []*metapb.Region {
return c.cachedCluster.getMetaRegions()
}
// GetRegions returns all regions info in detail.
func (c *RaftCluster) GetRegions() []*core.RegionInfo {
return c.cachedCluster.getRegions()
}
// GetRegionStats returns region statistics from cluster.
func (c *RaftCluster) GetRegionStats(startKey, endKey []byte) *core.RegionStats {
return c.cachedCluster.getRegionStats(startKey, endKey)
}
// DropCacheRegion removes a region from the cache.
func (c *RaftCluster) DropCacheRegion(id uint64) {
c.cachedCluster.dropRegion(id)
}
// GetStores gets stores from cluster.
func (c *RaftCluster) GetStores() []*metapb.Store {
return c.cachedCluster.getMetaStores()
}
// GetStore gets store from cluster.
func (c *RaftCluster) GetStore(storeID uint64) (*core.StoreInfo, error) {
if storeID == 0 {
return nil, errors.New("invalid zero store id")
}
store := c.cachedCluster.GetStore(storeID)
if store == nil {
return nil, errors.Errorf("invalid store ID %d, not found", storeID)
}
return store, nil
}
// GetAdjacentRegions returns region's info that is adjacent with specific region id.
func (c *RaftCluster) GetAdjacentRegions(region *core.RegionInfo) (*core.RegionInfo, *core.RegionInfo) {
return c.cachedCluster.GetAdjacentRegions(region)
}
// UpdateStoreLabels updates a store's location labels.
func (c *RaftCluster) UpdateStoreLabels(storeID uint64, labels []*metapb.StoreLabel) error {
store := c.cachedCluster.GetStore(storeID)
if store == nil {
return errors.Errorf("invalid store ID %d, not found", storeID)
}
storeMeta := store.Store
storeMeta.Labels = labels
// putStore will perform label merge.
err := c.putStore(storeMeta)
return errors.Trace(err)
}
func (c *RaftCluster) putStore(store *metapb.Store) error {
c.Lock()
defer c.Unlock()
if store.GetId() == 0 {
return errors.Errorf("invalid put store %v", store)
}
cluster := c.cachedCluster
// Store address can not be the same as other stores.
for _, s := range cluster.GetStores() {
// It's OK to start a new store on the same address if the old store has been removed.
if s.IsTombstone() {
continue
}
if s.GetId() != store.GetId() && s.GetAddress() == store.GetAddress() {
return errors.Errorf("duplicated store address: %v, already registered by %v", store, s.Store)
}
}
s := cluster.GetStore(store.GetId())
if s == nil {
// Add a new store.
s = core.NewStoreInfo(store)
} else {
// Update an existed store.
s.Address = store.Address
s.MergeLabels(store.Labels)
}
// Check location labels.
for _, k := range c.cachedCluster.GetLocationLabels() {
if v := s.GetLabelValue(k); len(v) == 0 {
log.Warnf("missing location label %q in store %v", k, s)
}
}
return cluster.putStore(s)
}
// RemoveStore marks a store as offline in cluster.
// State transition: Up -> Offline.
func (c *RaftCluster) RemoveStore(storeID uint64) error {
c.Lock()
defer c.Unlock()
cluster := c.cachedCluster
store := cluster.GetStore(storeID)
if store == nil {
return errors.Trace(core.ErrStoreNotFound(storeID))
}
// Remove an offline store should be OK, nothing to do.
if store.IsOffline() {
return nil
}
if store.IsTombstone() {
return errors.New("store has been removed")
}
store.State = metapb.StoreState_Offline
log.Warnf("[store %d] store %s has been Offline", store.GetId(), store.GetAddress())
return cluster.putStore(store)
}
// BuryStore marks a store as tombstone in cluster.
// State transition:
// Case 1: Up -> Tombstone (if force is true);
// Case 2: Offline -> Tombstone.
func (c *RaftCluster) BuryStore(storeID uint64, force bool) error {
c.Lock()
defer c.Unlock()
cluster := c.cachedCluster
store := cluster.GetStore(storeID)
if store == nil {
return errors.Trace(core.ErrStoreNotFound(storeID))
}
// Bury a tombstone store should be OK, nothing to do.
if store.IsTombstone() {
return nil
}
if store.IsUp() {
if !force {
return errors.New("store is still up, please remove store gracefully")
}
log.Warnf("forcedly bury store %v", store)
}
store.State = metapb.StoreState_Tombstone
log.Warnf("[store %d] store %s has been Tombstone", store.GetId(), store.GetAddress())
return cluster.putStore(store)
}
// SetStoreState sets up a store's state.
func (c *RaftCluster) SetStoreState(storeID uint64, state metapb.StoreState) error {
c.Lock()
defer c.Unlock()
cluster := c.cachedCluster
store := cluster.GetStore(storeID)
if store == nil {
return errors.Trace(core.ErrStoreNotFound(storeID))
}
store.State = state
log.Warnf("[store %d] set state to %v", storeID, state.String())
return cluster.putStore(store)
}
// SetStoreWeight sets up a store's leader/region balance weight.
func (c *RaftCluster) SetStoreWeight(storeID uint64, leader, region float64) error {
c.Lock()
defer c.Unlock()
store := c.cachedCluster.GetStore(storeID)
if store == nil {
return errors.Trace(core.ErrStoreNotFound(storeID))
}
if err := c.s.kv.SaveStoreWeight(storeID, leader, region); err != nil {
return errors.Trace(err)
}
store.LeaderWeight, store.RegionWeight = leader, region
return c.cachedCluster.putStore(store)
}
func (c *RaftCluster) checkStores() {
cluster := c.cachedCluster
for _, store := range cluster.getMetaStores() {
if store.GetState() != metapb.StoreState_Offline {
continue
}
if c.storeIsEmpty(store.GetId()) {
err := c.BuryStore(store.GetId(), false)
if err != nil {
log.Errorf("bury store %v failed: %v", store, err)
} else {
log.Infof("buried store %v", store)
}
}
}
}
func (c *RaftCluster) checkOperators() {
co := c.coordinator
for _, op := range co.getOperators() {
// after region is merged, it will not heartbeat anymore
// the operator of merged region will not timeout actively
if c.cachedCluster.GetRegion(op.RegionID()) == nil {
log.Debugf("remove operator %v cause region %d is merged", op, op.RegionID)
co.removeOperator(op)
continue
}
if op.IsTimeout() {
log.Infof("[region %v] operator timeout: %s", op.RegionID, op)
operatorCounter.WithLabelValues(op.Desc(), "timeout").Inc()
co.removeOperator(op)
}
}
}
func (c *RaftCluster) storeIsEmpty(storeID uint64) bool {
cluster := c.cachedCluster
if cluster.getStoreRegionCount(storeID) > 0 {
return false
}
// If pd-server is started recently, or becomes leader recently, the check may
// happen before any heartbeat from tikv. So we need to check region metas to
// verify no region's peer is on the store.
regions := cluster.getMetaRegions()
for _, region := range regions {
for _, p := range region.GetPeers() {
if p.GetStoreId() == storeID {
return false
}
}
}
return true
}
func (c *RaftCluster) collectMetrics() {
cluster := c.cachedCluster
statsMap := newStoreStatisticsMap(c.cachedCluster.opt, c.GetNamespaceClassifier())
for _, s := range cluster.GetStores() {
statsMap.Observe(s)
}
statsMap.Collect()
c.coordinator.collectSchedulerMetrics()
c.coordinator.collectHotSpotMetrics()
cluster.collectMetrics()
c.collectHealthStatus()
}
func (c *RaftCluster) collectHealthStatus() {
client := c.s.GetClient()
members, err := GetMembers(client)
if err != nil {
log.Info("get members error:", err)
}
unhealth := c.s.CheckHealth(members)
for _, member := range members {
if _, ok := unhealth[member.GetMemberId()]; ok {
healthStatusGauge.WithLabelValues(member.GetName()).Set(0)
continue
}
healthStatusGauge.WithLabelValues(member.GetName()).Set(1)
}
}
func (c *RaftCluster) runBackgroundJobs(interval time.Duration) {
defer logutil.LogPanic()
defer c.wg.Done()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-c.quit:
return
case <-ticker.C:
c.checkOperators()
c.checkStores()
c.collectMetrics()
c.coordinator.pruneHistory()
}
}
}
// GetConfig gets config from cluster.
func (c *RaftCluster) GetConfig() *metapb.Cluster {
return c.cachedCluster.getMeta()
}
func (c *RaftCluster) putConfig(meta *metapb.Cluster) error {
if meta.GetId() != c.clusterID {
return errors.Errorf("invalid cluster %v, mismatch cluster id %d", meta, c.clusterID)
}
return c.cachedCluster.putMeta(meta)
}
// GetNamespaceClassifier returns current namespace classifier.
func (c *RaftCluster) GetNamespaceClassifier() namespace.Classifier {
return c.s.classifier
}