forked from tikv/pd
/
store.go
581 lines (510 loc) · 16.8 KB
/
store.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
// 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 core
import (
"fmt"
"math"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/proto"
"github.com/pingcap/kvproto/pkg/metapb"
"github.com/pingcap/kvproto/pkg/pdpb"
log "github.com/pingcap/log"
errcode "github.com/pingcap/pd/pkg/error_code"
"go.uber.org/zap"
)
// StoreInfo contains information about a store.
type StoreInfo struct {
*metapb.Store
Stats *pdpb.StoreStats
// Blocked means that the store is blocked from balance.
blocked bool
LeaderCount int
RegionCount int
LeaderSize int64
RegionSize int64
PendingPeerCount int
LastHeartbeatTS time.Time
LeaderWeight float64
RegionWeight float64
RollingStoreStats *RollingStoreStats
}
// NewStoreInfo creates StoreInfo with meta data.
func NewStoreInfo(store *metapb.Store) *StoreInfo {
return &StoreInfo{
Store: store,
Stats: &pdpb.StoreStats{},
LeaderWeight: 1.0,
RegionWeight: 1.0,
RollingStoreStats: newRollingStoreStats(),
}
}
// Clone creates a copy of current StoreInfo.
func (s *StoreInfo) Clone() *StoreInfo {
return &StoreInfo{
Store: proto.Clone(s.Store).(*metapb.Store),
Stats: proto.Clone(s.Stats).(*pdpb.StoreStats),
blocked: s.blocked,
LeaderCount: s.LeaderCount,
RegionCount: s.RegionCount,
LeaderSize: s.LeaderSize,
RegionSize: s.RegionSize,
PendingPeerCount: s.PendingPeerCount,
LastHeartbeatTS: s.LastHeartbeatTS,
LeaderWeight: s.LeaderWeight,
RegionWeight: s.RegionWeight,
RollingStoreStats: s.RollingStoreStats,
}
}
// Block stops balancer from selecting the store.
func (s *StoreInfo) Block() {
s.blocked = true
}
// Unblock allows balancer to select the store.
func (s *StoreInfo) Unblock() {
s.blocked = false
}
// IsBlocked returns if the store is blocked.
func (s *StoreInfo) IsBlocked() bool {
return s.blocked
}
// IsUp checks if the store's state is Up.
func (s *StoreInfo) IsUp() bool {
return s.GetState() == metapb.StoreState_Up
}
// IsOffline checks if the store's state is Offline.
func (s *StoreInfo) IsOffline() bool {
return s.GetState() == metapb.StoreState_Offline
}
// IsTombstone checks if the store's state is Tombstone.
func (s *StoreInfo) IsTombstone() bool {
return s.GetState() == metapb.StoreState_Tombstone
}
// DownTime returns the time elapsed since last heartbeat.
func (s *StoreInfo) DownTime() time.Duration {
return time.Since(s.LastHeartbeatTS)
}
const minWeight = 1e-6
const maxScore = 1024 * 1024 * 1024
// LeaderScore returns the store's leader score: leaderSize / leaderWeight.
func (s *StoreInfo) LeaderScore(delta int64) float64 {
return float64(s.LeaderSize+delta) / math.Max(s.LeaderWeight, minWeight)
}
// RegionScore returns the store's region score.
func (s *StoreInfo) RegionScore(highSpaceRatio, lowSpaceRatio float64, delta int64) float64 {
var score float64
var amplification float64
available := float64(s.Stats.GetAvailable()) / (1 << 20)
used := float64(s.Stats.GetUsedSize()) / (1 << 20)
capacity := float64(s.Stats.GetCapacity()) / (1 << 20)
if s.RegionSize == 0 {
amplification = 1
} else {
// because of rocksdb compression, region size is larger than actual used size
amplification = float64(s.RegionSize) / used
}
// highSpaceBound is the lower bound of the high space stage.
highSpaceBound := (1 - highSpaceRatio) * capacity
// lowSpaceBound is the upper bound of the low space stage.
lowSpaceBound := (1 - lowSpaceRatio) * capacity
if available-float64(delta)/amplification >= highSpaceBound {
score = float64(s.RegionSize + delta)
} else if available-float64(delta)/amplification <= lowSpaceBound {
score = maxScore - (available - float64(delta)/amplification)
} else {
// to make the score function continuous, we use linear function y = k * x + b as transition period
// from above we know that there are two points must on the function image
// note that it is possible that other irrelative files occupy a lot of storage, so capacity == available + used + irrelative
// and we regarded irrelative as a fixed value.
// Then amp = size / used = size / (capacity - irrelative - available)
//
// When available == highSpaceBound,
// we can conclude that size = (capacity - irrelative - highSpaceBound) * amp = (used + available - highSpaceBound) * amp
// Similarly, when available == lowSpaceBound,
// we can conclude that size = (capacity - irrelative - lowSpaceBound) * amp = (used + available - lowSpaceBound) * amp
// These are the two fixed points' x-coordinates, and y-coordinates which can be easily obtained from the above two functions.
x1, y1 := (used+available-highSpaceBound)*amplification, (used+available-highSpaceBound)*amplification
x2, y2 := (used+available-lowSpaceBound)*amplification, maxScore-lowSpaceBound
k := (y2 - y1) / (x2 - x1)
b := y1 - k*x1
score = k*float64(s.RegionSize+delta) + b
}
return score / math.Max(s.RegionWeight, minWeight)
}
// StorageSize returns store's used storage size reported from tikv.
func (s *StoreInfo) StorageSize() uint64 {
return s.Stats.GetUsedSize()
}
// AvailableRatio is store's freeSpace/capacity.
func (s *StoreInfo) AvailableRatio() float64 {
if s.Stats.GetCapacity() == 0 {
return 0
}
return float64(s.Stats.GetAvailable()) / float64(s.Stats.GetCapacity())
}
// IsLowSpace checks if the store is lack of space.
func (s *StoreInfo) IsLowSpace(lowSpaceRatio float64) bool {
return s.Stats != nil && s.AvailableRatio() < 1-lowSpaceRatio
}
// ResourceCount reutrns count of leader/region in the store.
func (s *StoreInfo) ResourceCount(kind ResourceKind) uint64 {
switch kind {
case LeaderKind:
return uint64(s.LeaderCount)
case RegionKind:
return uint64(s.RegionCount)
default:
return 0
}
}
// ResourceSize returns size of leader/region in the store
func (s *StoreInfo) ResourceSize(kind ResourceKind) int64 {
switch kind {
case LeaderKind:
return s.LeaderSize
case RegionKind:
return s.RegionSize
default:
return 0
}
}
// ResourceScore reutrns score of leader/region in the store.
func (s *StoreInfo) ResourceScore(kind ResourceKind, highSpaceRatio, lowSpaceRatio float64, delta int64) float64 {
switch kind {
case LeaderKind:
return s.LeaderScore(delta)
case RegionKind:
return s.RegionScore(highSpaceRatio, lowSpaceRatio, delta)
default:
return 0
}
}
// ResourceWeight returns weight of leader/region in the score
func (s *StoreInfo) ResourceWeight(kind ResourceKind) float64 {
switch kind {
case LeaderKind:
if s.LeaderWeight <= 0 {
return minWeight
}
return s.LeaderWeight
case RegionKind:
if s.RegionWeight <= 0 {
return minWeight
}
return s.RegionWeight
default:
return 0
}
}
// GetStartTS returns the start timestamp.
func (s *StoreInfo) GetStartTS() time.Time {
return time.Unix(int64(s.Stats.GetStartTime()), 0)
}
// GetUptime returns the uptime.
func (s *StoreInfo) GetUptime() time.Duration {
uptime := s.LastHeartbeatTS.Sub(s.GetStartTS())
if uptime > 0 {
return uptime
}
return 0
}
var (
// If a store's last heartbeat is storeDisconnectDuration ago, the store will
// be marked as disconnected state. The value should be greater than tikv's
// store heartbeat interval (default 10s).
storeDisconnectDuration = 20 * time.Second
storeUnhealthDuration = 10 * time.Minute
)
// IsDisconnected checks if a store is disconnected, which means PD misses
// tikv's store heartbeat for a short time, maybe caused by process restart or
// temporary network failure.
func (s *StoreInfo) IsDisconnected() bool {
return s.DownTime() > storeDisconnectDuration
}
// IsUnhealth checks if a store is unhealth.
func (s *StoreInfo) IsUnhealth() bool {
return s.DownTime() > storeUnhealthDuration
}
// GetLabelValue returns a label's value (if exists).
func (s *StoreInfo) GetLabelValue(key string) string {
for _, label := range s.GetLabels() {
if strings.EqualFold(label.GetKey(), key) {
return label.GetValue()
}
}
return ""
}
// CompareLocation compares 2 stores' labels and returns at which level their
// locations are different. It returns -1 if they are at the same location.
func (s *StoreInfo) CompareLocation(other *StoreInfo, labels []string) int {
for i, key := range labels {
v1, v2 := s.GetLabelValue(key), other.GetLabelValue(key)
// If label is not set, the store is considered at the same location
// with any other store.
if v1 != "" && v2 != "" && !strings.EqualFold(v1, v2) {
return i
}
}
return -1
}
// MergeLabels merges the passed in labels with origins, overriding duplicated
// ones.
func (s *StoreInfo) MergeLabels(labels []*metapb.StoreLabel) {
L:
for _, newLabel := range labels {
for _, label := range s.Labels {
if strings.EqualFold(label.Key, newLabel.Key) {
label.Value = newLabel.Value
continue L
}
}
s.Labels = append(s.Labels, newLabel)
}
}
// StoreHotRegionInfos : used to get human readable description for hot regions.
type StoreHotRegionInfos struct {
AsPeer StoreHotRegionsStat `json:"as_peer"`
AsLeader StoreHotRegionsStat `json:"as_leader"`
}
// StoreHotRegionsStat used to record the hot region statistics group by store
type StoreHotRegionsStat map[uint64]*HotRegionsStat
type storeNotFoundErr struct {
storeID uint64
}
func (e storeNotFoundErr) Error() string {
return fmt.Sprintf("store %v not found", e.storeID)
}
// NewStoreNotFoundErr is for log of store not found
func NewStoreNotFoundErr(storeID uint64) errcode.ErrorCode {
return errcode.NewNotFoundErr(storeNotFoundErr{storeID})
}
// StoresInfo contains information about all stores.
type StoresInfo struct {
stores map[uint64]*StoreInfo
bytesReadRate float64
bytesWriteRate float64
}
// NewStoresInfo create a StoresInfo with map of storeID to StoreInfo
func NewStoresInfo() *StoresInfo {
return &StoresInfo{
stores: make(map[uint64]*StoreInfo),
}
}
// GetStore returns a copy of the StoreInfo with the specified storeID.
func (s *StoresInfo) GetStore(storeID uint64) *StoreInfo {
store, ok := s.stores[storeID]
if !ok {
return nil
}
return store.Clone()
}
// TakeStore returns the point of the origin StoreInfo with the specified storeID.
func (s *StoresInfo) TakeStore(storeID uint64) *StoreInfo {
store, ok := s.stores[storeID]
if !ok {
return nil
}
return store
}
// SetStore sets a StoreInfo with storeID.
func (s *StoresInfo) SetStore(store *StoreInfo) {
s.stores[store.GetId()] = store
store.RollingStoreStats.Observe(store.Stats)
s.updateTotalBytesReadRate()
s.updateTotalBytesWriteRate()
}
// BlockStore block a StoreInfo with storeID
func (s *StoresInfo) BlockStore(storeID uint64) errcode.ErrorCode {
op := errcode.Op("store.block")
store, ok := s.stores[storeID]
if !ok {
return op.AddTo(NewStoreNotFoundErr(storeID))
}
if store.IsBlocked() {
return op.AddTo(StoreBlockedErr{StoreID: storeID})
}
store.Block()
return nil
}
// UnblockStore unblock a StoreInfo with storeID
func (s *StoresInfo) UnblockStore(storeID uint64) {
store, ok := s.stores[storeID]
if !ok {
log.Fatal("store is unblocked, but it is not found",
zap.Uint64("store-id", storeID))
}
store.Unblock()
}
// GetStores get a complete set of StoreInfo
func (s *StoresInfo) GetStores() []*StoreInfo {
stores := make([]*StoreInfo, 0, len(s.stores))
for _, store := range s.stores {
stores = append(stores, store.Clone())
}
return stores
}
// GetMetaStores get a complete set of metapb.Store
func (s *StoresInfo) GetMetaStores() []*metapb.Store {
stores := make([]*metapb.Store, 0, len(s.stores))
for _, store := range s.stores {
stores = append(stores, proto.Clone(store.Store).(*metapb.Store))
}
return stores
}
// GetStoreCount return the total count of storeInfo
func (s *StoresInfo) GetStoreCount() int {
return len(s.stores)
}
// SetLeaderCount set the leader count to a storeInfo
func (s *StoresInfo) SetLeaderCount(storeID uint64, leaderCount int) {
if store, ok := s.stores[storeID]; ok {
store.LeaderCount = leaderCount
}
}
// SetRegionCount set the region count to a storeInfo
func (s *StoresInfo) SetRegionCount(storeID uint64, regionCount int) {
if store, ok := s.stores[storeID]; ok {
store.RegionCount = regionCount
}
}
// SetPendingPeerCount sets the pending count to a storeInfo
func (s *StoresInfo) SetPendingPeerCount(storeID uint64, pendingPeerCount int) {
if store, ok := s.stores[storeID]; ok {
store.PendingPeerCount = pendingPeerCount
}
}
// SetLeaderSize set the leader count to a storeInfo
func (s *StoresInfo) SetLeaderSize(storeID uint64, leaderSize int64) {
if store, ok := s.stores[storeID]; ok {
store.LeaderSize = leaderSize
}
}
// SetRegionSize set the region count to a storeInfo
func (s *StoresInfo) SetRegionSize(storeID uint64, regionSize int64) {
if store, ok := s.stores[storeID]; ok {
store.RegionSize = regionSize
}
}
func (s *StoresInfo) updateTotalBytesWriteRate() {
var totalBytesWirteRate float64
for _, s := range s.stores {
if s.IsUp() {
totalBytesWirteRate += s.RollingStoreStats.GetBytesWriteRate()
}
}
s.bytesWriteRate = totalBytesWirteRate
}
// TotalBytesWriteRate returns the total written bytes rate of all StoreInfo.
func (s *StoresInfo) TotalBytesWriteRate() float64 {
return s.bytesWriteRate
}
func (s *StoresInfo) updateTotalBytesReadRate() {
var totalBytesReadRate float64
for _, s := range s.stores {
if s.IsUp() {
totalBytesReadRate += s.RollingStoreStats.GetBytesReadRate()
}
}
s.bytesReadRate = totalBytesReadRate
}
// TotalBytesReadRate returns the total read bytes rate of all StoreInfo.
func (s *StoresInfo) TotalBytesReadRate() float64 {
return s.bytesReadRate
}
// GetStoresBytesWriteStat returns the bytes write stat of all StoreInfo.
func (s *StoresInfo) GetStoresBytesWriteStat() map[uint64]uint64 {
res := make(map[uint64]uint64, len(s.stores))
for _, s := range s.stores {
res[s.GetId()] = uint64(s.RollingStoreStats.GetBytesWriteRate())
}
return res
}
// GetStoresBytesReadStat returns the bytes read stat of all StoreInfo.
func (s *StoresInfo) GetStoresBytesReadStat() map[uint64]uint64 {
res := make(map[uint64]uint64, len(s.stores))
for _, s := range s.stores {
res[s.GetId()] = uint64(s.RollingStoreStats.GetBytesReadRate())
}
return res
}
// GetStoresKeysWriteStat returns the keys write stat of all StoreInfo.
func (s *StoresInfo) GetStoresKeysWriteStat() map[uint64]uint64 {
res := make(map[uint64]uint64, len(s.stores))
for _, s := range s.stores {
res[s.GetId()] = uint64(s.RollingStoreStats.GetKeysWriteRate())
}
return res
}
// GetStoresKeysReadStat returns the bytes read stat of all StoreInfo.
func (s *StoresInfo) GetStoresKeysReadStat() map[uint64]uint64 {
res := make(map[uint64]uint64, len(s.stores))
for _, s := range s.stores {
res[s.GetId()] = uint64(s.RollingStoreStats.GetKeysReadRate())
}
return res
}
// RollingStoreStats are multiple sets of recent historical records with specified windows size.
type RollingStoreStats struct {
sync.RWMutex
bytesWriteRate *RollingStats
bytesReadRate *RollingStats
keysWriteRate *RollingStats
keysReadRate *RollingStats
}
const storeStatsRollingWindows = 3
func newRollingStoreStats() *RollingStoreStats {
return &RollingStoreStats{
bytesWriteRate: NewRollingStats(storeStatsRollingWindows),
bytesReadRate: NewRollingStats(storeStatsRollingWindows),
keysWriteRate: NewRollingStats(storeStatsRollingWindows),
keysReadRate: NewRollingStats(storeStatsRollingWindows),
}
}
// Observe records current statistics.
func (r *RollingStoreStats) Observe(stats *pdpb.StoreStats) {
interval := stats.GetInterval().GetEndTimestamp() - stats.GetInterval().GetStartTimestamp()
if interval == 0 {
return
}
r.Lock()
defer r.Unlock()
r.bytesWriteRate.Add(float64(stats.BytesWritten / interval))
r.bytesReadRate.Add(float64(stats.BytesRead / interval))
r.keysWriteRate.Add(float64(stats.KeysWritten / interval))
r.keysReadRate.Add(float64(stats.KeysRead / interval))
}
// GetBytesWriteRate returns the bytes write rate.
func (r *RollingStoreStats) GetBytesWriteRate() float64 {
r.RLock()
defer r.RUnlock()
return r.bytesWriteRate.Median()
}
// GetBytesReadRate returns the bytes read rate.
func (r *RollingStoreStats) GetBytesReadRate() float64 {
r.RLock()
defer r.RUnlock()
return r.bytesReadRate.Median()
}
// GetKeysWriteRate returns the keys write rate.
func (r *RollingStoreStats) GetKeysWriteRate() float64 {
r.RLock()
defer r.RUnlock()
return r.keysWriteRate.Median()
}
// GetKeysReadRate returns the keys read rate.
func (r *RollingStoreStats) GetKeysReadRate() float64 {
r.RLock()
defer r.RUnlock()
return r.keysReadRate.Median()
}