forked from cubefs/cubefs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvol.go
1663 lines (1458 loc) · 47.5 KB
/
vol.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 2018 The CubeFS 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 master
import (
"encoding/json"
"fmt"
"math"
"runtime/debug"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/cubefs/cubefs/proto"
"github.com/cubefs/cubefs/util"
"github.com/cubefs/cubefs/util/atomicutil"
"github.com/cubefs/cubefs/util/errors"
"github.com/cubefs/cubefs/util/log"
)
type VolVarargs struct {
zoneName string
description string
capacity uint64 // GB
deleteLockTime int64 // h
followerRead bool
authenticate bool
dpSelectorName string
dpSelectorParm string
coldArgs *coldVolArgs
dpReplicaNum uint8
enablePosixAcl bool
dpReadOnlyWhenVolFull bool
enableQuota bool
enableTransaction proto.TxOpMask
txTimeout int64
txConflictRetryNum int64
txConflictRetryInterval int64
txOpLimit int
trashInterval int64
crossZone bool
enableAutoDpMetaRepair bool
}
// Vol represents a set of meta partitionMap and data partitionMap
type Vol struct {
ID uint64
Name string
Owner string
OSSAccessKey string
OSSSecretKey string
dpReplicaNum uint8
mpReplicaNum uint8
Status uint8
Deleting bool
threshold float32
dataPartitionSize uint64 // byte
Capacity uint64 // GB
VolType int
EbsBlkSize int
CacheCapacity uint64
CacheAction int
CacheThreshold int
CacheTTL int
CacheHighWater int
CacheLowWater int
CacheLRUInterval int
CacheRule string
PreloadCacheOn bool
NeedToLowerReplica bool
FollowerRead bool
authenticate bool
crossZone bool
domainOn bool
defaultPriority bool // old default zone first
enablePosixAcl bool
enableTransaction proto.TxOpMask
txTimeout int64
txConflictRetryNum int64
txConflictRetryInterval int64
txOpLimit int
zoneName string
MetaPartitions map[uint64]*MetaPartition `graphql:"-"`
dataPartitions *DataPartitionMap
mpsCache []byte
viewCache []byte
createDpMutex sync.RWMutex
createMpMutex sync.RWMutex
createTime int64
DeleteLockTime int64
description string
dpSelectorName string
dpSelectorParm string
domainId uint64
qosManager *QosCtrlManager
DpReadOnlyWhenVolFull bool // only if this switch is on, all dp becomes readonly when vol is full
ReadOnlyForVolFull bool // only if the switch DpReadOnlyWhenVolFull is on, mark vol is readonly when is full
aclMgr AclManager
uidSpaceManager *UidSpaceManager
volLock sync.RWMutex
quotaManager *MasterQuotaManager
enableQuota bool
TrashInterval int64
DisableAuditLog bool
VersionMgr *VolVersionManager
Forbidden bool
mpsLock *mpsLockManager
preloadCapacity uint64
authKey string
DeleteExecTime time.Time
user *User
dpRepairBlockSize uint64
EnableAutoMetaRepair atomicutil.Bool
}
func newVol(vv volValue) (vol *Vol) {
vol = &Vol{ID: vv.ID, Name: vv.Name, MetaPartitions: make(map[uint64]*MetaPartition)}
if vol.threshold <= 0 {
vol.threshold = defaultMetaPartitionMemUsageThreshold
}
vol.dataPartitions = newDataPartitionMap(vv.Name)
vol.VersionMgr = newVersionMgr(vol)
vol.dpReplicaNum = vv.DpReplicaNum
vol.mpReplicaNum = vv.ReplicaNum
vol.Owner = vv.Owner
vol.dataPartitionSize = vv.DataPartitionSize
vol.Capacity = vv.Capacity
vol.FollowerRead = vv.FollowerRead
vol.authenticate = vv.Authenticate
vol.crossZone = vv.CrossZone
vol.zoneName = vv.ZoneName
vol.viewCache = make([]byte, 0)
vol.mpsCache = make([]byte, 0)
vol.createTime = vv.CreateTime
vol.DeleteLockTime = vv.DeleteLockTime
vol.description = vv.Description
vol.defaultPriority = vv.DefaultPriority
vol.domainId = vv.DomainId
vol.enablePosixAcl = vv.EnablePosixAcl
vol.enableQuota = vv.EnableQuota
vol.enableTransaction = vv.EnableTransaction
vol.txTimeout = vv.TxTimeout
vol.txConflictRetryNum = vv.TxConflictRetryNum
vol.txConflictRetryInterval = vv.TxConflictRetryInterval
vol.txOpLimit = vv.TxOpLimit
vol.VolType = vv.VolType
vol.EbsBlkSize = vv.EbsBlkSize
vol.CacheCapacity = vv.CacheCapacity
vol.CacheAction = vv.CacheAction
vol.CacheThreshold = vv.CacheThreshold
vol.CacheTTL = vv.CacheTTL
vol.CacheHighWater = vv.CacheHighWater
vol.CacheLowWater = vv.CacheLowWater
vol.CacheLRUInterval = vv.CacheLRUInterval
vol.CacheRule = vv.CacheRule
vol.Status = vv.Status
limitQosVal := &qosArgs{
qosEnable: vv.VolQosEnable,
diskQosEnable: vv.DiskQosEnable,
iopsRVal: vv.IopsRLimit,
iopsWVal: vv.IopsWLimit,
flowRVal: vv.FlowRlimit,
flowWVal: vv.FlowWlimit,
}
vol.initQosManager(limitQosVal)
magnifyQosVal := &qosArgs{
iopsRVal: uint64(vv.IopsRMagnify),
iopsWVal: uint64(vv.IopsWMagnify),
flowRVal: uint64(vv.FlowWMagnify),
flowWVal: uint64(vv.FlowWMagnify),
}
vol.qosManager.volUpdateMagnify(magnifyQosVal)
vol.DpReadOnlyWhenVolFull = vv.DpReadOnlyWhenVolFull
vol.DisableAuditLog = false
vol.mpsLock = newMpsLockManager(vol)
vol.preloadCapacity = math.MaxUint64 // mark as special value to trigger calculate
vol.dpRepairBlockSize = proto.DefaultDpRepairBlockSize
vol.EnableAutoMetaRepair.Store(defaultEnableDpMetaRepair)
return
}
func newVolFromVolValue(vv *volValue) (vol *Vol) {
vol = newVol(*vv)
// overwrite oss secure
vol.OSSAccessKey, vol.OSSSecretKey = vv.OSSAccessKey, vv.OSSSecretKey
vol.Status = vv.Status
vol.dpSelectorName = vv.DpSelectorName
vol.dpSelectorParm = vv.DpSelectorParm
if vol.txTimeout == 0 {
vol.txTimeout = proto.DefaultTransactionTimeout
}
if vol.txConflictRetryNum == 0 {
vol.txConflictRetryNum = proto.DefaultTxConflictRetryNum
}
if vol.txConflictRetryInterval == 0 {
vol.txConflictRetryInterval = proto.DefaultTxConflictRetryInterval
}
vol.TrashInterval = vv.TrashInterval
vol.DisableAuditLog = vv.DisableAuditLog
vol.Forbidden = vv.Forbidden
vol.authKey = vv.AuthKey
vol.DeleteExecTime = vv.DeleteExecTime
vol.user = vv.User
vol.dpRepairBlockSize = vv.DpRepairBlockSize
if vol.dpRepairBlockSize == 0 {
vol.dpRepairBlockSize = proto.DefaultDpRepairBlockSize
}
vol.EnableAutoMetaRepair.Store(vv.EnableAutoMetaRepair)
return vol
}
type mpsLockManager struct {
mpsLock sync.RWMutex
lastEffectStack string
lockTime time.Time
innerLock sync.RWMutex
onLock bool
hang bool
vol *Vol
enable int32 // only config debug log enable lock
}
var (
lockCheckInterval = time.Second
lockExpireInterval = time.Minute
)
func newMpsLockManager(vol *Vol) *mpsLockManager {
lc := &mpsLockManager{vol: vol}
go lc.CheckExceptionLock(lockCheckInterval, lockExpireInterval)
if log.EnableDebug() {
atomic.StoreInt32(&lc.enable, 0)
}
return lc
}
func (mpsLock *mpsLockManager) Lock() {
mpsLock.mpsLock.Lock()
if log.EnableDebug() && atomic.LoadInt32(&mpsLock.enable) == 1 {
mpsLock.innerLock.Lock()
mpsLock.onLock = true
mpsLock.lockTime = time.Now()
mpsLock.lastEffectStack = fmt.Sprintf("Lock stack %v", string(debug.Stack()))
}
}
func (mpsLock *mpsLockManager) UnLock() {
mpsLock.mpsLock.Unlock()
if log.EnableDebug() && atomic.LoadInt32(&mpsLock.enable) == 1 {
mpsLock.onLock = false
mpsLock.lockTime = time.Unix(0, 0)
mpsLock.lastEffectStack = fmt.Sprintf("UnLock stack %v", string(debug.Stack()))
mpsLock.innerLock.Unlock()
}
}
func (mpsLock *mpsLockManager) RLock() {
mpsLock.mpsLock.RLock()
if log.EnableDebug() && atomic.LoadInt32(&mpsLock.enable) == 1 {
mpsLock.innerLock.RLock()
mpsLock.hang = false
mpsLock.onLock = true
mpsLock.lockTime = time.Now()
mpsLock.lastEffectStack = fmt.Sprintf("RLock stack %v", string(debug.Stack()))
}
}
func (mpsLock *mpsLockManager) RUnlock() {
mpsLock.mpsLock.RUnlock()
if log.EnableDebug() && atomic.LoadInt32(&mpsLock.enable) == 1 {
mpsLock.onLock = false
mpsLock.hang = false
mpsLock.lockTime = time.Unix(0, 0)
mpsLock.lastEffectStack = fmt.Sprintf("RUnlock stack %v", string(debug.Stack()))
mpsLock.innerLock.RUnlock()
}
}
func (mpsLock *mpsLockManager) CheckExceptionLock(interval time.Duration, expireTime time.Duration) {
ticker := time.NewTicker(interval)
for range ticker.C {
{
if mpsLock.vol.status() == proto.VolStatusMarkDelete || atomic.LoadInt32(&mpsLock.enable) == 0 {
break
}
if !log.EnableDebug() {
continue
}
if !mpsLock.onLock {
continue
}
tm := time.Now()
if tm.After(mpsLock.lockTime.Add(expireTime)) {
log.LogWarnf("vol %v mpsLock hang more than %v since time %v stack(%v)",
mpsLock.vol.Name, expireTime, mpsLock.lockTime, mpsLock.lastEffectStack)
mpsLock.hang = true
}
}
}
}
func (vol *Vol) CheckStrategy(c *Cluster) {
// make sure resume all the processing ver deleting tasks before checking
if !atomic.CompareAndSwapInt32(&vol.VersionMgr.checkStrategy, 0, 1) {
return
}
go func() {
waitTime := 5 * time.Second * defaultIntervalToCheck
waited := false
for {
time.Sleep(waitTime)
if vol.Status == proto.VolStatusMarkDelete {
break
}
if c != nil && c.IsLeader() {
if !waited {
log.LogInfof("wait for %v seconds once after becoming leader to make sure all the ver deleting tasks are resumed",
waitTime)
time.Sleep(waitTime)
waited = true
}
if !proto.IsHot(vol.VolType) {
return
}
vol.VersionMgr.RLock()
if vol.VersionMgr.strategy.GetPeriodicSecond() == 0 || !vol.VersionMgr.strategy.Enable { // strategy not be set
vol.VersionMgr.RUnlock()
continue
}
vol.VersionMgr.RUnlock()
vol.VersionMgr.checkCreateStrategy(c)
vol.VersionMgr.checkDeleteStrategy(c)
}
}
}()
}
func (vol *Vol) CalculatePreloadCapacity() uint64 {
total := uint64(0)
dps := vol.dataPartitions.partitions
for _, dp := range dps {
if proto.IsPreLoadDp(dp.PartitionType) {
total += dp.total / util.GB
}
}
if overSoldFactor <= 0 {
return total
}
return uint64(float32(total) / overSoldFactor)
}
func (vol *Vol) getPreloadCapacity() uint64 {
if vol.preloadCapacity != math.MaxUint64 {
return vol.preloadCapacity
}
vol.preloadCapacity = vol.CalculatePreloadCapacity()
log.LogDebugf("[getPreloadCapacity] vol(%v) calculated preload capacity: %v", vol.Name, vol.preloadCapacity)
return vol.preloadCapacity
}
func (vol *Vol) initQosManager(limitArgs *qosArgs) {
vol.qosManager = &QosCtrlManager{
cliInfoMgrMap: make(map[uint64]*ClientInfoMgr),
serverFactorLimitMap: make(map[uint32]*ServerFactorLimit),
qosEnable: limitArgs.qosEnable,
vol: vol,
ClientHitTriggerCnt: defaultClientTriggerHitCnt,
ClientReqPeriod: defaultClientReqPeriodSeconds,
}
if limitArgs.iopsRVal == 0 {
limitArgs.iopsRVal = defaultIopsRLimit
}
if limitArgs.iopsWVal == 0 {
limitArgs.iopsWVal = defaultIopsWLimit
}
if limitArgs.flowRVal == 0 {
limitArgs.flowRVal = defaultFlowRLimit
}
if limitArgs.flowWVal == 0 {
limitArgs.flowWVal = defaultFlowWLimit
}
arrLimit := [defaultLimitTypeCnt]uint64{limitArgs.iopsRVal, limitArgs.iopsWVal, limitArgs.flowRVal, limitArgs.flowWVal}
arrType := [defaultLimitTypeCnt]uint32{proto.IopsReadType, proto.IopsWriteType, proto.FlowReadType, proto.FlowWriteType}
for i := 0; i < defaultLimitTypeCnt; i++ {
vol.qosManager.serverFactorLimitMap[arrType[i]] = &ServerFactorLimit{
Name: proto.QosTypeString(arrType[i]),
Type: arrType[i],
Total: arrLimit[i],
Buffer: arrLimit[i],
requestCh: make(chan interface{}, 10240),
qosManager: vol.qosManager,
done: make(chan interface{}, 1),
}
go vol.qosManager.serverFactorLimitMap[arrType[i]].dispatch()
}
}
func (vol *Vol) refreshOSSSecure() (key, secret string) {
vol.OSSAccessKey = util.RandomString(16, util.Numeric|util.LowerLetter|util.UpperLetter)
vol.OSSSecretKey = util.RandomString(32, util.Numeric|util.LowerLetter|util.UpperLetter)
return vol.OSSAccessKey, vol.OSSSecretKey
}
func (vol *Vol) addMetaPartition(mp *MetaPartition) {
vol.mpsLock.Lock()
defer vol.mpsLock.UnLock()
if _, ok := vol.MetaPartitions[mp.PartitionID]; !ok {
vol.MetaPartitions[mp.PartitionID] = mp
return
}
// replace the old partition in the map with mp
vol.MetaPartitions[mp.PartitionID] = mp
}
func (vol *Vol) metaPartition(partitionID uint64) (mp *MetaPartition, err error) {
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
mp, ok := vol.MetaPartitions[partitionID]
if !ok {
err = proto.ErrMetaPartitionNotExists
}
return
}
func (vol *Vol) maxPartitionID() (maxPartitionID uint64) {
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
for id := range vol.MetaPartitions {
if id > maxPartitionID {
maxPartitionID = id
}
}
return
}
func (vol *Vol) getRWMetaPartitionNum() (num uint64, isHeartBeatDone bool) {
if time.Now().Unix()-vol.createTime <= defaultMetaPartitionTimeOutSec {
log.LogInfof("The vol[%v] is being created.", vol.Name)
return num, false
}
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
for _, mp := range vol.MetaPartitions {
if !mp.heartBeatDone {
log.LogInfof("The mp[%v] of vol[%v] is not done", mp.PartitionID, vol.Name)
return num, false
}
if mp.Status == proto.ReadWrite {
num++
} else {
log.LogWarnf("The mp[%v] of vol[%v] is not RW", mp.PartitionID, vol.Name)
}
}
return num, true
}
func (vol *Vol) getDataPartitionsView() (body []byte, err error) {
return vol.dataPartitions.updateResponseCache(false, 0, vol)
}
func (vol *Vol) getDataPartitionViewCompress() (body []byte, err error) {
return vol.dataPartitions.updateCompressCache(false, 0, vol)
}
func (vol *Vol) getDataPartitionByID(partitionID uint64) (dp *DataPartition, err error) {
return vol.dataPartitions.get(partitionID)
}
func (vol *Vol) addMetaPartitions(c *Cluster, count int) (err error) {
// add extra meta partitions at a time
var (
start uint64
end uint64
)
vol.createMpMutex.Lock()
defer vol.createMpMutex.Unlock()
// update End of the maxMetaPartition range
maxPartitionId := vol.maxPartitionID()
rearMetaPartition := vol.MetaPartitions[maxPartitionId]
oldEnd := rearMetaPartition.End
end = rearMetaPartition.MaxInodeID + gConfig.MetaPartitionInodeIdStep
if err = rearMetaPartition.canSplit(end, gConfig.MetaPartitionInodeIdStep, false); err != nil {
return err
}
rearMetaPartition.End = end
if err = c.syncUpdateMetaPartition(rearMetaPartition); err != nil {
rearMetaPartition.End = oldEnd
log.LogErrorf("action[addMetaPartitions] split partition partitionID[%v] err[%v]", rearMetaPartition.PartitionID, err)
return
}
// create new meta partitions
for i := 0; i < count; i++ {
start = end + 1
end = start + gConfig.MetaPartitionInodeIdStep
if end > (defaultMaxMetaPartitionInodeID - gConfig.MetaPartitionInodeIdStep) {
end = defaultMaxMetaPartitionInodeID
log.LogWarnf("action[addMetaPartitions] vol[%v] add too many meta partition ,partition range overflow ! ", vol.Name)
}
if i == count-1 {
end = defaultMaxMetaPartitionInodeID
}
if err = vol.createMetaPartition(c, start, end); err != nil {
log.LogErrorf("action[addMetaPartitions] vol[%v] add meta partition err[%v]", vol.Name, err)
break
}
if end == defaultMaxMetaPartitionInodeID {
break
}
}
return
}
func (vol *Vol) initMetaPartitions(c *Cluster, count int) (err error) {
// initialize k meta partitionMap at a time
var (
start uint64
end uint64
)
if count < defaultInitMetaPartitionCount {
count = defaultInitMetaPartitionCount
}
if count > defaultMaxInitMetaPartitionCount {
count = defaultMaxInitMetaPartitionCount
}
vol.createMpMutex.Lock()
for index := 0; index < count; index++ {
if index != 0 {
start = end + 1
}
end = gConfig.MetaPartitionInodeIdStep * uint64(index+1)
if index == count-1 {
end = defaultMaxMetaPartitionInodeID
}
if err = vol.createMetaPartition(c, start, end); err != nil {
log.LogErrorf("action[initMetaPartitions] vol[%v] init meta partition err[%v]", vol.Name, err)
break
}
}
vol.createMpMutex.Unlock()
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
if len(vol.MetaPartitions) != count {
err = fmt.Errorf("action[initMetaPartitions] vol[%v] init meta partition failed,mpCount[%v],expectCount[%v],err[%v]",
vol.Name, len(vol.MetaPartitions), count, err)
}
return
}
func (vol *Vol) initDataPartitions(c *Cluster, dpCount int) (err error) {
if dpCount == 0 {
dpCount = defaultInitDataPartitionCnt
}
// initialize k data partitionMap at a time
err = c.batchCreateDataPartition(vol, dpCount, true)
return
}
func (vol *Vol) checkDataPartitions(c *Cluster) (cnt int) {
if vol.getDataPartitionsCount() == 0 && vol.Status != proto.VolStatusMarkDelete && proto.IsHot(vol.VolType) {
c.batchCreateDataPartition(vol, 1, false)
}
shouldDpInhibitWriteByVolFull := vol.shouldInhibitWriteBySpaceFull()
vol.SetReadOnlyForVolFull(shouldDpInhibitWriteByVolFull)
totalPreloadCapacity := uint64(0)
partitions := vol.dataPartitions.clonePartitions()
for _, dp := range partitions {
if proto.IsPreLoadDp(dp.PartitionType) {
now := time.Now().Unix()
if now > dp.PartitionTTL {
log.LogWarnf("[checkDataPartitions] dp(%d) is deleted because of ttl expired, now(%d), ttl(%d)",
dp.PartitionID, now, dp.PartitionTTL)
vol.deleteDataPartition(c, dp)
continue
}
startTime := dp.dataNodeStartTime()
if now-dp.createTime > 600 && dp.used == 0 && now-startTime > 600 {
log.LogWarnf("[checkDataPartitions] dp(%d) is deleted because of clear, now(%d), create(%d), start(%d)",
dp.PartitionID, now, dp.createTime, startTime)
vol.deleteDataPartition(c, dp)
continue
}
totalPreloadCapacity += dp.total / util.GB
}
dp.checkReplicaStatus(c.getDataPartitionTimeoutSec())
dp.checkStatus(c.Name, true, c.getDataPartitionTimeoutSec(), c, shouldDpInhibitWriteByVolFull, vol.Forbidden)
dp.checkLeader(c, c.Name, c.getDataPartitionTimeoutSec())
dp.checkMissingReplicas(c.Name, c.leaderInfo.addr, c.cfg.MissingDataPartitionInterval, c.cfg.IntervalToAlarmMissingDataPartition)
dp.checkReplicaNum(c, vol)
// NOTE: cluster or enable meta repair
if c.getEnableAutoDpMetaRepair() || vol.EnableAutoMetaRepair.Load() {
dp.checkReplicaMeta(c)
}
if time.Now().Unix()-vol.createTime < defaultIntervalToCheckHeartbeat*3 && !vol.Forbidden {
dp.setReadWrite()
}
if dp.Status == proto.ReadWrite {
cnt++
}
dp.checkDiskError(c.Name, c.leaderInfo.addr)
dp.checkReplicationTask(c.Name, vol.dataPartitionSize)
}
if overSoldFactor > 0 {
totalPreloadCapacity = uint64(float32(totalPreloadCapacity) / overSoldFactor)
}
vol.preloadCapacity = totalPreloadCapacity
if vol.preloadCapacity != 0 {
log.LogDebugf("[checkDataPartitions] vol(%v) totalPreloadCapacity(%v GB), overSoldFactor(%v)",
vol.Name, totalPreloadCapacity, overSoldFactor)
}
return
}
func (vol *Vol) loadDataPartition(c *Cluster) {
partitions, startIndex := vol.dataPartitions.getDataPartitionsToBeChecked(c.cfg.PeriodToLoadALLDataPartitions)
if len(partitions) == 0 {
return
}
c.waitForResponseToLoadDataPartition(partitions)
msg := fmt.Sprintf("action[loadDataPartition] vol[%v],checkStartIndex:%v checkCount:%v",
vol.Name, startIndex, len(partitions))
log.LogInfo(msg)
}
func (vol *Vol) releaseDataPartitions(releaseCount int, afterLoadSeconds int64) {
partitions, startIndex := vol.dataPartitions.getDataPartitionsToBeReleased(releaseCount, afterLoadSeconds)
if len(partitions) == 0 {
return
}
vol.dataPartitions.freeMemOccupiedByDataPartitions(partitions)
msg := fmt.Sprintf("action[freeMemOccupiedByDataPartitions] vol[%v] release data partition start:%v releaseCount:%v",
vol.Name, startIndex, len(partitions))
log.LogInfo(msg)
}
func (vol *Vol) tryUpdateDpReplicaNum(c *Cluster, partition *DataPartition) (err error) {
partition.RLock()
defer partition.RUnlock()
if partition.isRecover || vol.dpReplicaNum != 2 || partition.ReplicaNum != 3 || len(partition.Hosts) != 2 {
return
}
if partition.isSpecialReplicaCnt() {
return
}
oldReplicaNum := partition.ReplicaNum
partition.ReplicaNum = partition.ReplicaNum - 1
if err = c.syncUpdateDataPartition(partition); err != nil {
partition.ReplicaNum = oldReplicaNum
}
return
}
func (vol *Vol) isOkUpdateRepCnt() (ok bool, rsp []uint64) {
if proto.IsCold(vol.VolType) {
return
}
ok = true
dps := vol.cloneDataPartitionMap()
for _, dp := range dps {
if vol.dpReplicaNum != dp.ReplicaNum {
rsp = append(rsp, dp.PartitionID)
ok = false
// output dps detail info
if len(rsp) > 20 {
return
}
}
}
return ok, rsp
}
func (vol *Vol) checkMetaPartitions(c *Cluster) {
var tasks []*proto.AdminTask
metaPartitionInodeIdStep := gConfig.MetaPartitionInodeIdStep
maxPartitionID := vol.maxPartitionID()
mps := vol.cloneMetaPartitionMap()
var (
doSplit bool
err error
)
for _, mp := range mps {
doSplit = mp.checkStatus(c.Name, true, int(vol.mpReplicaNum), maxPartitionID, metaPartitionInodeIdStep, vol.Forbidden)
if doSplit && !c.cfg.DisableAutoCreate {
nextStart := mp.MaxInodeID + metaPartitionInodeIdStep
log.LogInfof(c.Name, fmt.Sprintf("cluster[%v],vol[%v],meta partition[%v] splits start[%v] maxinodeid:[%v] default step:[%v],nextStart[%v]",
c.Name, vol.Name, mp.PartitionID, mp.Start, mp.MaxInodeID, metaPartitionInodeIdStep, nextStart))
if err = vol.splitMetaPartition(c, mp, nextStart, metaPartitionInodeIdStep, false); err != nil {
Warn(c.Name, fmt.Sprintf("cluster[%v],vol[%v],meta partition[%v] splits failed,err[%v]", c.Name, vol.Name, mp.PartitionID, err))
}
}
mp.checkLeader(c.Name)
mp.checkReplicaNum(c, vol.Name, vol.mpReplicaNum)
mp.checkEnd(c, maxPartitionID)
mp.reportMissingReplicas(c.Name, c.leaderInfo.addr, defaultMetaPartitionTimeOutSec, defaultIntervalToAlarmMissingMetaPartition)
tasks = append(tasks, mp.replicaCreationTasks(c.Name, vol.Name)...)
}
c.addMetaNodeTasks(tasks)
vol.checkSplitMetaPartition(c, metaPartitionInodeIdStep)
}
func (vol *Vol) checkSplitMetaPartition(c *Cluster, metaPartitionInodeStep uint64) {
maxPartitionID := vol.maxPartitionID()
maxMP, err := vol.metaPartition(maxPartitionID)
if err != nil {
return
}
// Any of the following conditions will trigger max mp split
// 1. The memory of the metanode which max mp belongs to reaches the threshold
// 2. The number of inodes managed by max mp reaches the threshold(0.75)
// 3. The number of RW mp is less than 3
maxMPInodeUsedRatio := float64(maxMP.MaxInodeID-maxMP.Start) / float64(metaPartitionInodeStep)
RWMPNum, isHeartBeatDone := vol.getRWMetaPartitionNum()
if !isHeartBeatDone {
log.LogInfof("Not all volume[%s] mp heartbeat is done, skip mp split", vol.Name)
return
}
if maxMP.memUsedReachThreshold(c.Name, vol.Name) || RWMPNum < lowerLimitRWMetaPartition ||
maxMPInodeUsedRatio > metaPartitionInodeUsageThreshold {
end := maxMP.MaxInodeID + metaPartitionInodeStep/4
if RWMPNum < lowerLimitRWMetaPartition {
end = maxMP.MaxInodeID + metaPartitionInodeStep
}
if err := vol.splitMetaPartition(c, maxMP, end, metaPartitionInodeStep, true); err != nil {
msg := fmt.Sprintf("action[checkSplitMetaPartition],split meta maxMP[%v] failed,err[%v]\n",
maxMP.PartitionID, err)
Warn(c.Name, msg)
}
log.LogInfof("volume[%v] split MaxMP[%v], MaxInodeID[%d] Start[%d] RWMPNum[%d] maxMPInodeUsedRatio[%.2f]",
vol.Name, maxPartitionID, maxMP.MaxInodeID, maxMP.Start, RWMPNum, maxMPInodeUsedRatio)
}
}
func (mp *MetaPartition) memUsedReachThreshold(clusterName, volName string) bool {
liveReplicas := mp.getLiveReplicas()
foundReadonlyReplica := false
var readonlyReplica *MetaReplica
for _, replica := range liveReplicas {
if replica.Status == proto.ReadOnly {
foundReadonlyReplica = true
readonlyReplica = replica
break
}
}
if !foundReadonlyReplica || readonlyReplica == nil {
return false
}
if readonlyReplica.metaNode.IsWriteAble() {
msg := fmt.Sprintf("action[checkSplitMetaPartition] vol[%v],max meta parition[%v] status is readonly\n",
volName, mp.PartitionID)
Warn(clusterName, msg)
return false
}
return true
}
func (vol *Vol) cloneMetaPartitionMap() (mps map[uint64]*MetaPartition) {
mps = make(map[uint64]*MetaPartition)
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
for _, mp := range vol.MetaPartitions {
mps[mp.PartitionID] = mp
}
return
}
func (vol *Vol) setMpForbid() {
vol.mpsLock.RLock()
defer vol.mpsLock.RUnlock()
for _, mp := range vol.MetaPartitions {
if mp.Status != proto.Unavailable {
mp.Status = proto.ReadOnly
}
}
}
func (vol *Vol) cloneDataPartitionMap() (dps map[uint64]*DataPartition) {
vol.dataPartitions.RLock()
defer vol.dataPartitions.RUnlock()
dps = make(map[uint64]*DataPartition)
for _, dp := range vol.dataPartitions.partitionMap {
dps[dp.PartitionID] = dp
}
return
}
func (vol *Vol) setDpForbid() {
vol.dataPartitions.RLock()
defer vol.dataPartitions.RUnlock()
for _, dp := range vol.dataPartitions.partitionMap {
if dp.Status != proto.Unavailable {
dp.Status = proto.ReadOnly
}
}
}
func (vol *Vol) setStatus(status uint8) {
vol.volLock.Lock()
defer vol.volLock.Unlock()
vol.Status = status
}
func (vol *Vol) status() uint8 {
vol.volLock.RLock()
defer vol.volLock.RUnlock()
return vol.Status
}
func (vol *Vol) capacity() uint64 {
vol.volLock.RLock()
defer vol.volLock.RUnlock()
return vol.Capacity
}
func (vol *Vol) SetReadOnlyForVolFull(isFull bool) {
vol.volLock.Lock()
defer vol.volLock.Unlock()
if isFull {
if vol.DpReadOnlyWhenVolFull {
vol.ReadOnlyForVolFull = isFull
}
} else {
vol.ReadOnlyForVolFull = isFull
}
}
func (vol *Vol) IsReadOnlyForVolFull() bool {
vol.volLock.RLock()
defer vol.volLock.RUnlock()
return vol.ReadOnlyForVolFull
}
func (vol *Vol) autoDeleteDp(c *Cluster) {
if vol.dataPartitions == nil {
return
}
maxSize := overSoldCap(vol.CacheCapacity * util.GB)
maxCnt := maxSize / vol.dataPartitionSize
if maxSize%vol.dataPartitionSize != 0 {
maxCnt++
}
partitions := vol.dataPartitions.clonePartitions()
for _, dp := range partitions {
if !proto.IsCacheDp(dp.PartitionType) {
continue
}
if maxCnt > 0 {
maxCnt--
continue
}
log.LogInfof("[autoDeleteDp] start delete dp, id[%d]", dp.PartitionID)
vol.deleteDataPartition(c, dp)
}
}
func (vol *Vol) checkAutoDataPartitionCreation(c *Cluster) {
defer func() {
if r := recover(); r != nil {
log.LogWarnf("checkAutoDataPartitionCreation occurred panic,err[%v]", r)
WarnBySpecialKey(fmt.Sprintf("%v_%v_scheduling_job_panic", c.Name, ModuleName),
"checkAutoDataPartitionCreation occurred panic")
}
}()
if ok, _ := vol.needCreateDataPartition(); !ok {
return
}
vol.setStatus(proto.VolStatusNormal)
log.LogInfof("action[autoCreateDataPartitions] vol[%v] before autoCreateDataPartitions", vol.Name)
if !c.DisableAutoAllocate && !vol.Forbidden {
vol.autoCreateDataPartitions(c)
}
}
func (vol *Vol) shouldInhibitWriteBySpaceFull() bool {
if !vol.DpReadOnlyWhenVolFull {
return false
}
if vol.capacity() == 0 {
return false
}
if !proto.IsHot(vol.VolType) {
return false
}
usedSpace := vol.totalUsedSpace() / util.GB
if usedSpace >= vol.capacity() {
return true
}
vol.ReadOnlyForVolFull = false
return false
}
func (vol *Vol) needCreateDataPartition() (ok bool, err error) {
ok = false
if vol.status() == proto.VolStatusMarkDelete {
err = proto.ErrVolNotExists
return
}
if vol.capacity() == 0 {
err = proto.ErrVolNoAvailableSpace
return
}
if proto.IsHot(vol.VolType) {
if vol.IsReadOnlyForVolFull() {
vol.setAllDataPartitionsToReadOnly()
err = proto.ErrVolNoAvailableSpace
return
}
ok = true
return
}
// cold
if vol.CacheAction == proto.NoCache && vol.CacheRule == "" {
err = proto.ErrVolNoCacheAndRule
return
}
ok = true
return
}
func (vol *Vol) autoCreateDataPartitions(c *Cluster) {
if time.Since(vol.dataPartitions.lastAutoCreateTime) < time.Minute {
return
}
if c.cfg.DisableAutoCreate {
// if disable auto create, once alloc size is over capacity, not allow to create new dp
allocSize := uint64(len(vol.dataPartitions.partitions)) * vol.dataPartitionSize
totalSize := vol.capacity() * util.GB
if allocSize > totalSize {