You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

634 lines
20 KiB

6 years ago
6 years ago
6 years ago
12 years ago
12 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
10 months ago
4 years ago
4 years ago
4 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
  1. package storage
  2. import (
  3. "fmt"
  4. "io"
  5. "path/filepath"
  6. "strings"
  7. "sync"
  8. "sync/atomic"
  9. "github.com/seaweedfs/seaweedfs/weed/pb"
  10. "github.com/seaweedfs/seaweedfs/weed/storage/volume_info"
  11. "github.com/seaweedfs/seaweedfs/weed/util"
  12. "google.golang.org/grpc"
  13. "github.com/seaweedfs/seaweedfs/weed/glog"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/stats"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  19. . "github.com/seaweedfs/seaweedfs/weed/storage/types"
  20. )
  21. const (
  22. MAX_TTL_VOLUME_REMOVAL_DELAY = 10 // 10 minutes
  23. )
  24. type ReadOption struct {
  25. // request
  26. ReadDeleted bool
  27. AttemptMetaOnly bool
  28. MustMetaOnly bool
  29. // response
  30. IsMetaOnly bool // read status
  31. VolumeRevision uint16
  32. IsOutOfRange bool // whether read over MaxPossibleVolumeSize
  33. // If HasSlowRead is set to true:
  34. // * read requests and write requests compete for the lock.
  35. // * large file read P99 latency on busy sites will go up, due to the need to get locks multiple times.
  36. // * write requests will see lower latency.
  37. // If HasSlowRead is set to false:
  38. // * read requests should complete asap, not blocking other requests.
  39. // * write requests may see high latency when downloading large files.
  40. HasSlowRead bool
  41. // increasing ReadBufferSize can reduce the number of get locks times and shorten read P99 latency.
  42. // but will increase memory usage a bit. Use with hasSlowRead normally.
  43. ReadBufferSize int
  44. }
  45. /*
  46. * A VolumeServer contains one Store
  47. */
  48. type Store struct {
  49. MasterAddress pb.ServerAddress
  50. grpcDialOption grpc.DialOption
  51. volumeSizeLimit uint64 // read from the master
  52. Ip string
  53. Port int
  54. GrpcPort int
  55. PublicUrl string
  56. Locations []*DiskLocation
  57. dataCenter string // optional information, overwriting master setting if exists
  58. rack string // optional information, overwriting master setting if exists
  59. connected bool
  60. NeedleMapKind NeedleMapKind
  61. NewVolumesChan chan master_pb.VolumeShortInformationMessage
  62. DeletedVolumesChan chan master_pb.VolumeShortInformationMessage
  63. NewEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  64. DeletedEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  65. isStopping bool
  66. }
  67. func (s *Store) String() (str string) {
  68. str = fmt.Sprintf("Ip:%s, Port:%d, GrpcPort:%d PublicUrl:%s, dataCenter:%s, rack:%s, connected:%v, volumeSizeLimit:%d", s.Ip, s.Port, s.GrpcPort, s.PublicUrl, s.dataCenter, s.rack, s.connected, s.GetVolumeSizeLimit())
  69. return
  70. }
  71. func NewStore(grpcDialOption grpc.DialOption, ip string, port int, grpcPort int, publicUrl string, dirnames []string, maxVolumeCounts []int32,
  72. minFreeSpaces []util.MinFreeSpace, idxFolder string, needleMapKind NeedleMapKind, diskTypes []DiskType, ldbTimeout int64) (s *Store) {
  73. s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, GrpcPort: grpcPort, PublicUrl: publicUrl, NeedleMapKind: needleMapKind}
  74. s.Locations = make([]*DiskLocation, 0)
  75. var wg sync.WaitGroup
  76. for i := 0; i < len(dirnames); i++ {
  77. location := NewDiskLocation(dirnames[i], int32(maxVolumeCounts[i]), minFreeSpaces[i], idxFolder, diskTypes[i])
  78. s.Locations = append(s.Locations, location)
  79. stats.VolumeServerMaxVolumeCounter.Add(float64(maxVolumeCounts[i]))
  80. wg.Add(1)
  81. go func() {
  82. defer wg.Done()
  83. location.loadExistingVolumes(needleMapKind, ldbTimeout)
  84. }()
  85. }
  86. wg.Wait()
  87. s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  88. s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  89. s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  90. s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  91. return
  92. }
  93. func (s *Store) AddVolume(volumeId needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement string, ttlString string, preallocate int64, MemoryMapMaxSizeMb uint32, diskType DiskType, ldbTimeout int64) error {
  94. rt, e := super_block.NewReplicaPlacementFromString(replicaPlacement)
  95. if e != nil {
  96. return e
  97. }
  98. ttl, e := needle.ReadTTL(ttlString)
  99. if e != nil {
  100. return e
  101. }
  102. e = s.addVolume(volumeId, collection, needleMapKind, rt, ttl, preallocate, MemoryMapMaxSizeMb, diskType, ldbTimeout)
  103. return e
  104. }
  105. func (s *Store) DeleteCollection(collection string) (e error) {
  106. for _, location := range s.Locations {
  107. e = location.DeleteCollectionFromDiskLocation(collection)
  108. if e != nil {
  109. return
  110. }
  111. stats.DeleteCollectionMetrics(collection)
  112. // let the heartbeat send the list of volumes, instead of sending the deleted volume ids to DeletedVolumesChan
  113. }
  114. return
  115. }
  116. func (s *Store) findVolume(vid needle.VolumeId) *Volume {
  117. for _, location := range s.Locations {
  118. if v, found := location.FindVolume(vid); found {
  119. return v
  120. }
  121. }
  122. return nil
  123. }
  124. func (s *Store) FindFreeLocation(diskType DiskType) (ret *DiskLocation) {
  125. max := int32(0)
  126. for _, location := range s.Locations {
  127. if diskType != location.DiskType {
  128. continue
  129. }
  130. if location.isDiskSpaceLow {
  131. continue
  132. }
  133. currentFreeCount := location.MaxVolumeCount - int32(location.VolumesLen())
  134. currentFreeCount *= erasure_coding.DataShardsCount
  135. currentFreeCount -= int32(location.EcShardCount())
  136. currentFreeCount /= erasure_coding.DataShardsCount
  137. if currentFreeCount > max {
  138. max = currentFreeCount
  139. ret = location
  140. }
  141. }
  142. return ret
  143. }
  144. func (s *Store) addVolume(vid needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement *super_block.ReplicaPlacement, ttl *needle.TTL, preallocate int64, memoryMapMaxSizeMb uint32, diskType DiskType, ldbTimeout int64) error {
  145. if s.findVolume(vid) != nil {
  146. return fmt.Errorf("Volume Id %d already exists!", vid)
  147. }
  148. if location := s.FindFreeLocation(diskType); location != nil {
  149. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  150. location.Directory, vid, collection, replicaPlacement, ttl)
  151. if volume, err := NewVolume(location.Directory, location.IdxDirectory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate, memoryMapMaxSizeMb, ldbTimeout); err == nil {
  152. location.SetVolume(vid, volume)
  153. glog.V(0).Infof("add volume %d", vid)
  154. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  155. Id: uint32(vid),
  156. Collection: collection,
  157. ReplicaPlacement: uint32(replicaPlacement.Byte()),
  158. Version: uint32(volume.Version()),
  159. Ttl: ttl.ToUint32(),
  160. DiskType: string(diskType),
  161. }
  162. return nil
  163. } else {
  164. return err
  165. }
  166. }
  167. return fmt.Errorf("No more free space left")
  168. }
  169. func (s *Store) VolumeInfos() (allStats []*VolumeInfo) {
  170. for _, location := range s.Locations {
  171. stats := collectStatsForOneLocation(location)
  172. allStats = append(allStats, stats...)
  173. }
  174. sortVolumeInfos(allStats)
  175. return allStats
  176. }
  177. func collectStatsForOneLocation(location *DiskLocation) (stats []*VolumeInfo) {
  178. location.volumesLock.RLock()
  179. defer location.volumesLock.RUnlock()
  180. for k, v := range location.volumes {
  181. s := collectStatForOneVolume(k, v)
  182. stats = append(stats, s)
  183. }
  184. return stats
  185. }
  186. func collectStatForOneVolume(vid needle.VolumeId, v *Volume) (s *VolumeInfo) {
  187. s = &VolumeInfo{
  188. Id: vid,
  189. Collection: v.Collection,
  190. ReplicaPlacement: v.ReplicaPlacement,
  191. Version: v.Version(),
  192. ReadOnly: v.IsReadOnly(),
  193. Ttl: v.Ttl,
  194. CompactRevision: uint32(v.CompactionRevision),
  195. DiskType: v.DiskType().String(),
  196. }
  197. s.RemoteStorageName, s.RemoteStorageKey = v.RemoteStorageNameKey()
  198. v.dataFileAccessLock.RLock()
  199. defer v.dataFileAccessLock.RUnlock()
  200. if v.nm == nil {
  201. return
  202. }
  203. s.FileCount = v.nm.FileCount()
  204. s.DeleteCount = v.nm.DeletedCount()
  205. s.DeletedByteCount = v.nm.DeletedSize()
  206. s.Size = v.nm.ContentSize()
  207. return
  208. }
  209. func (s *Store) SetDataCenter(dataCenter string) {
  210. s.dataCenter = dataCenter
  211. }
  212. func (s *Store) SetRack(rack string) {
  213. s.rack = rack
  214. }
  215. func (s *Store) GetDataCenter() string {
  216. return s.dataCenter
  217. }
  218. func (s *Store) GetRack() string {
  219. return s.rack
  220. }
  221. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  222. var volumeMessages []*master_pb.VolumeInformationMessage
  223. maxVolumeCounts := make(map[string]uint32)
  224. var maxFileKey NeedleId
  225. collectionVolumeSize := make(map[string]int64)
  226. collectionVolumeDeletedBytes := make(map[string]int64)
  227. collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
  228. for _, location := range s.Locations {
  229. var deleteVids []needle.VolumeId
  230. maxVolumeCounts[string(location.DiskType)] += uint32(location.MaxVolumeCount)
  231. location.volumesLock.RLock()
  232. for _, v := range location.volumes {
  233. curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage()
  234. if volumeMessage == nil {
  235. continue
  236. }
  237. if maxFileKey < curMaxFileKey {
  238. maxFileKey = curMaxFileKey
  239. }
  240. shouldDeleteVolume := false
  241. if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
  242. volumeMessages = append(volumeMessages, volumeMessage)
  243. } else {
  244. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  245. deleteVids = append(deleteVids, v.Id)
  246. shouldDeleteVolume = true
  247. } else {
  248. glog.V(0).Infof("volume %d is expired", v.Id)
  249. }
  250. if v.lastIoError != nil {
  251. deleteVids = append(deleteVids, v.Id)
  252. shouldDeleteVolume = true
  253. glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
  254. }
  255. }
  256. if _, exist := collectionVolumeSize[v.Collection]; !exist {
  257. collectionVolumeSize[v.Collection] = 0
  258. collectionVolumeDeletedBytes[v.Collection] = 0
  259. }
  260. if !shouldDeleteVolume {
  261. collectionVolumeSize[v.Collection] += int64(volumeMessage.Size)
  262. collectionVolumeDeletedBytes[v.Collection] += int64(volumeMessage.DeletedByteCount)
  263. } else {
  264. collectionVolumeSize[v.Collection] -= int64(volumeMessage.Size)
  265. if collectionVolumeSize[v.Collection] <= 0 {
  266. delete(collectionVolumeSize, v.Collection)
  267. }
  268. }
  269. if _, exist := collectionVolumeReadOnlyCount[v.Collection]; !exist {
  270. collectionVolumeReadOnlyCount[v.Collection] = map[string]uint8{
  271. stats.IsReadOnly: 0,
  272. stats.NoWriteOrDelete: 0,
  273. stats.NoWriteCanDelete: 0,
  274. stats.IsDiskSpaceLow: 0,
  275. }
  276. }
  277. if !shouldDeleteVolume && v.IsReadOnly() {
  278. collectionVolumeReadOnlyCount[v.Collection][stats.IsReadOnly] += 1
  279. if v.noWriteOrDelete {
  280. collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteOrDelete] += 1
  281. }
  282. if v.noWriteCanDelete {
  283. collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteCanDelete] += 1
  284. }
  285. if v.location.isDiskSpaceLow {
  286. collectionVolumeReadOnlyCount[v.Collection][stats.IsDiskSpaceLow] += 1
  287. }
  288. }
  289. }
  290. location.volumesLock.RUnlock()
  291. if len(deleteVids) > 0 {
  292. // delete expired volumes.
  293. location.volumesLock.Lock()
  294. for _, vid := range deleteVids {
  295. found, err := location.deleteVolumeById(vid, false)
  296. if err == nil {
  297. if found {
  298. glog.V(0).Infof("volume %d is deleted", vid)
  299. }
  300. } else {
  301. glog.Warningf("delete volume %d: %v", vid, err)
  302. }
  303. }
  304. location.volumesLock.Unlock()
  305. }
  306. }
  307. // delete expired ec volumes
  308. ecVolumeMessages, deletedEcVolumes := s.deleteExpiredEcVolumes()
  309. var uuidList []string
  310. for _, loc := range s.Locations {
  311. uuidList = append(uuidList, loc.DirectoryUuid)
  312. }
  313. for col, size := range collectionVolumeSize {
  314. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  315. }
  316. for col, deletedBytes := range collectionVolumeDeletedBytes {
  317. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "deleted_bytes").Set(float64(deletedBytes))
  318. }
  319. for col, types := range collectionVolumeReadOnlyCount {
  320. for t, count := range types {
  321. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, t).Set(float64(count))
  322. }
  323. }
  324. return &master_pb.Heartbeat{
  325. Ip: s.Ip,
  326. Port: uint32(s.Port),
  327. GrpcPort: uint32(s.GrpcPort),
  328. PublicUrl: s.PublicUrl,
  329. MaxVolumeCounts: maxVolumeCounts,
  330. MaxFileKey: NeedleIdToUint64(maxFileKey),
  331. DataCenter: s.dataCenter,
  332. Rack: s.rack,
  333. Volumes: volumeMessages,
  334. DeletedEcShards: deletedEcVolumes,
  335. HasNoVolumes: len(volumeMessages) == 0,
  336. HasNoEcShards: len(ecVolumeMessages) == 0,
  337. LocationUuids: uuidList,
  338. }
  339. }
  340. func (s *Store) deleteExpiredEcVolumes() (ecShards, deleted []*master_pb.VolumeEcShardInformationMessage) {
  341. for _, location := range s.Locations {
  342. for _, ev := range location.ecVolumes {
  343. messages := ev.ToVolumeEcShardInformationMessage()
  344. if ev.IsTimeToDestroy() {
  345. err := location.deleteEcVolumeById(ev.VolumeId)
  346. if err != nil {
  347. ecShards = append(ecShards, messages...)
  348. glog.Errorf("delete EcVolume err %d: %v", ev.VolumeId, err)
  349. continue
  350. }
  351. deleted = append(deleted, messages...)
  352. } else {
  353. ecShards = append(ecShards, messages...)
  354. }
  355. }
  356. }
  357. return
  358. }
  359. func (s *Store) SetStopping() {
  360. s.isStopping = true
  361. for _, location := range s.Locations {
  362. location.SetStopping()
  363. }
  364. }
  365. func (s *Store) LoadNewVolumes() {
  366. for _, location := range s.Locations {
  367. location.loadExistingVolumes(s.NeedleMapKind, 0)
  368. }
  369. }
  370. func (s *Store) Close() {
  371. for _, location := range s.Locations {
  372. location.Close()
  373. }
  374. }
  375. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, checkCookie bool, fsync bool) (isUnchanged bool, err error) {
  376. if v := s.findVolume(i); v != nil {
  377. if v.IsReadOnly() {
  378. err = fmt.Errorf("volume %d is read only", i)
  379. return
  380. }
  381. _, _, isUnchanged, err = v.writeNeedle2(n, checkCookie, fsync && s.isStopping)
  382. return
  383. }
  384. glog.V(0).Infoln("volume", i, "not found!")
  385. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  386. return
  387. }
  388. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  389. if v := s.findVolume(i); v != nil {
  390. if v.noWriteOrDelete {
  391. return 0, fmt.Errorf("volume %d is read only", i)
  392. }
  393. return v.deleteNeedle2(n)
  394. }
  395. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  396. }
  397. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption, onReadSizeFn func(size Size)) (int, error) {
  398. if v := s.findVolume(i); v != nil {
  399. return v.readNeedle(n, readOption, onReadSizeFn)
  400. }
  401. return 0, fmt.Errorf("volume %d not found", i)
  402. }
  403. func (s *Store) ReadVolumeNeedleMetaAt(i needle.VolumeId, n *needle.Needle, offset int64, size int32) error {
  404. if v := s.findVolume(i); v != nil {
  405. return v.readNeedleMetaAt(n, offset, size)
  406. }
  407. return fmt.Errorf("volume %d not found", i)
  408. }
  409. func (s *Store) ReadVolumeNeedleDataInto(i needle.VolumeId, n *needle.Needle, readOption *ReadOption, writer io.Writer, offset int64, size int64) error {
  410. if v := s.findVolume(i); v != nil {
  411. return v.readNeedleDataInto(n, readOption, writer, offset, size)
  412. }
  413. return fmt.Errorf("volume %d not found", i)
  414. }
  415. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  416. return s.findVolume(i)
  417. }
  418. func (s *Store) HasVolume(i needle.VolumeId) bool {
  419. v := s.findVolume(i)
  420. return v != nil
  421. }
  422. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  423. v := s.findVolume(i)
  424. if v == nil {
  425. return fmt.Errorf("volume %d not found", i)
  426. }
  427. v.noWriteLock.Lock()
  428. v.noWriteOrDelete = true
  429. v.noWriteLock.Unlock()
  430. return nil
  431. }
  432. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  433. v := s.findVolume(i)
  434. if v == nil {
  435. return fmt.Errorf("volume %d not found", i)
  436. }
  437. v.noWriteLock.Lock()
  438. v.noWriteOrDelete = false
  439. v.noWriteLock.Unlock()
  440. return nil
  441. }
  442. func (s *Store) MountVolume(i needle.VolumeId) error {
  443. for _, location := range s.Locations {
  444. if found := location.LoadVolume(i, s.NeedleMapKind); found == true {
  445. glog.V(0).Infof("mount volume %d", i)
  446. v := s.findVolume(i)
  447. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  448. Id: uint32(v.Id),
  449. Collection: v.Collection,
  450. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  451. Version: uint32(v.Version()),
  452. Ttl: v.Ttl.ToUint32(),
  453. DiskType: string(v.location.DiskType),
  454. }
  455. return nil
  456. }
  457. }
  458. return fmt.Errorf("volume %d not found on disk", i)
  459. }
  460. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  461. v := s.findVolume(i)
  462. if v == nil {
  463. return nil
  464. }
  465. message := master_pb.VolumeShortInformationMessage{
  466. Id: uint32(v.Id),
  467. Collection: v.Collection,
  468. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  469. Version: uint32(v.Version()),
  470. Ttl: v.Ttl.ToUint32(),
  471. DiskType: string(v.location.DiskType),
  472. }
  473. for _, location := range s.Locations {
  474. err := location.UnloadVolume(i)
  475. if err == nil {
  476. glog.V(0).Infof("UnmountVolume %d", i)
  477. stats.DeleteCollectionMetrics(v.Collection)
  478. s.DeletedVolumesChan <- message
  479. return nil
  480. } else if err == ErrVolumeNotFound {
  481. continue
  482. }
  483. }
  484. return fmt.Errorf("volume %d not found on disk", i)
  485. }
  486. func (s *Store) DeleteVolume(i needle.VolumeId, onlyEmpty bool) error {
  487. v := s.findVolume(i)
  488. if v == nil {
  489. return fmt.Errorf("delete volume %d not found on disk", i)
  490. }
  491. message := master_pb.VolumeShortInformationMessage{
  492. Id: uint32(v.Id),
  493. Collection: v.Collection,
  494. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  495. Version: uint32(v.Version()),
  496. Ttl: v.Ttl.ToUint32(),
  497. DiskType: string(v.location.DiskType),
  498. }
  499. for _, location := range s.Locations {
  500. err := location.DeleteVolume(i, onlyEmpty)
  501. if err == nil {
  502. glog.V(0).Infof("DeleteVolume %d", i)
  503. s.DeletedVolumesChan <- message
  504. return nil
  505. } else if err == ErrVolumeNotFound {
  506. continue
  507. } else if err == ErrVolumeNotEmpty {
  508. return fmt.Errorf("DeleteVolume %d: %v", i, err)
  509. } else {
  510. glog.Errorf("DeleteVolume %d: %v", i, err)
  511. }
  512. }
  513. return fmt.Errorf("volume %d not found on disk", i)
  514. }
  515. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  516. for _, location := range s.Locations {
  517. fileInfo, found := location.LocateVolume(i)
  518. if !found {
  519. continue
  520. }
  521. // load, modify, save
  522. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  523. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  524. volumeInfo, _, _, err := volume_info.MaybeLoadVolumeInfo(vifFile)
  525. if err != nil {
  526. return fmt.Errorf("volume %d failed to load vif: %v", i, err)
  527. }
  528. volumeInfo.Replication = replication
  529. err = volume_info.SaveVolumeInfo(vifFile, volumeInfo)
  530. if err != nil {
  531. return fmt.Errorf("volume %d failed to save vif: %v", i, err)
  532. }
  533. return nil
  534. }
  535. return fmt.Errorf("volume %d not found on disk", i)
  536. }
  537. func (s *Store) SetVolumeSizeLimit(x uint64) {
  538. atomic.StoreUint64(&s.volumeSizeLimit, x)
  539. }
  540. func (s *Store) GetVolumeSizeLimit() uint64 {
  541. return atomic.LoadUint64(&s.volumeSizeLimit)
  542. }
  543. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  544. volumeSizeLimit := s.GetVolumeSizeLimit()
  545. if volumeSizeLimit == 0 {
  546. return
  547. }
  548. var newMaxVolumeCount int32
  549. for _, diskLocation := range s.Locations {
  550. if diskLocation.OriginalMaxVolumeCount == 0 {
  551. currentMaxVolumeCount := atomic.LoadInt32(&diskLocation.MaxVolumeCount)
  552. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  553. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  554. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  555. volCount := diskLocation.VolumesLen()
  556. maxVolumeCount := int32(volCount)
  557. if unclaimedSpaces > int64(volumeSizeLimit) {
  558. maxVolumeCount += int32(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  559. }
  560. newMaxVolumeCount = newMaxVolumeCount + maxVolumeCount
  561. atomic.StoreInt32(&diskLocation.MaxVolumeCount, maxVolumeCount)
  562. glog.V(4).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  563. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  564. hasChanges = hasChanges || currentMaxVolumeCount != atomic.LoadInt32(&diskLocation.MaxVolumeCount)
  565. } else {
  566. newMaxVolumeCount = newMaxVolumeCount + diskLocation.OriginalMaxVolumeCount
  567. }
  568. }
  569. stats.VolumeServerMaxVolumeCounter.Set(float64(newMaxVolumeCount))
  570. return
  571. }