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.

636 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(filterFn func(location *DiskLocation) bool) (ret *DiskLocation) {
  125. max := int32(0)
  126. for _, location := range s.Locations {
  127. if filterFn != nil && !filterFn(location) {
  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(func(location *DiskLocation) bool {
  149. return location.DiskType == diskType
  150. }); location != nil {
  151. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  152. location.Directory, vid, collection, replicaPlacement, ttl)
  153. if volume, err := NewVolume(location.Directory, location.IdxDirectory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate, memoryMapMaxSizeMb, ldbTimeout); err == nil {
  154. location.SetVolume(vid, volume)
  155. glog.V(0).Infof("add volume %d", vid)
  156. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  157. Id: uint32(vid),
  158. Collection: collection,
  159. ReplicaPlacement: uint32(replicaPlacement.Byte()),
  160. Version: uint32(volume.Version()),
  161. Ttl: ttl.ToUint32(),
  162. DiskType: string(diskType),
  163. }
  164. return nil
  165. } else {
  166. return err
  167. }
  168. }
  169. return fmt.Errorf("No more free space left")
  170. }
  171. func (s *Store) VolumeInfos() (allStats []*VolumeInfo) {
  172. for _, location := range s.Locations {
  173. stats := collectStatsForOneLocation(location)
  174. allStats = append(allStats, stats...)
  175. }
  176. sortVolumeInfos(allStats)
  177. return allStats
  178. }
  179. func collectStatsForOneLocation(location *DiskLocation) (stats []*VolumeInfo) {
  180. location.volumesLock.RLock()
  181. defer location.volumesLock.RUnlock()
  182. for k, v := range location.volumes {
  183. s := collectStatForOneVolume(k, v)
  184. stats = append(stats, s)
  185. }
  186. return stats
  187. }
  188. func collectStatForOneVolume(vid needle.VolumeId, v *Volume) (s *VolumeInfo) {
  189. s = &VolumeInfo{
  190. Id: vid,
  191. Collection: v.Collection,
  192. ReplicaPlacement: v.ReplicaPlacement,
  193. Version: v.Version(),
  194. ReadOnly: v.IsReadOnly(),
  195. Ttl: v.Ttl,
  196. CompactRevision: uint32(v.CompactionRevision),
  197. DiskType: v.DiskType().String(),
  198. }
  199. s.RemoteStorageName, s.RemoteStorageKey = v.RemoteStorageNameKey()
  200. v.dataFileAccessLock.RLock()
  201. defer v.dataFileAccessLock.RUnlock()
  202. if v.nm == nil {
  203. return
  204. }
  205. s.FileCount = v.nm.FileCount()
  206. s.DeleteCount = v.nm.DeletedCount()
  207. s.DeletedByteCount = v.nm.DeletedSize()
  208. s.Size = v.nm.ContentSize()
  209. return
  210. }
  211. func (s *Store) SetDataCenter(dataCenter string) {
  212. s.dataCenter = dataCenter
  213. }
  214. func (s *Store) SetRack(rack string) {
  215. s.rack = rack
  216. }
  217. func (s *Store) GetDataCenter() string {
  218. return s.dataCenter
  219. }
  220. func (s *Store) GetRack() string {
  221. return s.rack
  222. }
  223. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  224. var volumeMessages []*master_pb.VolumeInformationMessage
  225. maxVolumeCounts := make(map[string]uint32)
  226. var maxFileKey NeedleId
  227. collectionVolumeSize := make(map[string]int64)
  228. collectionVolumeDeletedBytes := make(map[string]int64)
  229. collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
  230. for _, location := range s.Locations {
  231. var deleteVids []needle.VolumeId
  232. maxVolumeCounts[string(location.DiskType)] += uint32(location.MaxVolumeCount)
  233. location.volumesLock.RLock()
  234. for _, v := range location.volumes {
  235. curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage()
  236. if volumeMessage == nil {
  237. continue
  238. }
  239. if maxFileKey < curMaxFileKey {
  240. maxFileKey = curMaxFileKey
  241. }
  242. shouldDeleteVolume := false
  243. if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
  244. volumeMessages = append(volumeMessages, volumeMessage)
  245. } else {
  246. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  247. deleteVids = append(deleteVids, v.Id)
  248. shouldDeleteVolume = true
  249. } else {
  250. glog.V(0).Infof("volume %d is expired", v.Id)
  251. }
  252. if v.lastIoError != nil {
  253. deleteVids = append(deleteVids, v.Id)
  254. shouldDeleteVolume = true
  255. glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
  256. }
  257. }
  258. if _, exist := collectionVolumeSize[v.Collection]; !exist {
  259. collectionVolumeSize[v.Collection] = 0
  260. collectionVolumeDeletedBytes[v.Collection] = 0
  261. }
  262. if !shouldDeleteVolume {
  263. collectionVolumeSize[v.Collection] += int64(volumeMessage.Size)
  264. collectionVolumeDeletedBytes[v.Collection] += int64(volumeMessage.DeletedByteCount)
  265. } else {
  266. collectionVolumeSize[v.Collection] -= int64(volumeMessage.Size)
  267. if collectionVolumeSize[v.Collection] <= 0 {
  268. delete(collectionVolumeSize, v.Collection)
  269. }
  270. }
  271. if _, exist := collectionVolumeReadOnlyCount[v.Collection]; !exist {
  272. collectionVolumeReadOnlyCount[v.Collection] = map[string]uint8{
  273. stats.IsReadOnly: 0,
  274. stats.NoWriteOrDelete: 0,
  275. stats.NoWriteCanDelete: 0,
  276. stats.IsDiskSpaceLow: 0,
  277. }
  278. }
  279. if !shouldDeleteVolume && v.IsReadOnly() {
  280. collectionVolumeReadOnlyCount[v.Collection][stats.IsReadOnly] += 1
  281. if v.noWriteOrDelete {
  282. collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteOrDelete] += 1
  283. }
  284. if v.noWriteCanDelete {
  285. collectionVolumeReadOnlyCount[v.Collection][stats.NoWriteCanDelete] += 1
  286. }
  287. if v.location.isDiskSpaceLow {
  288. collectionVolumeReadOnlyCount[v.Collection][stats.IsDiskSpaceLow] += 1
  289. }
  290. }
  291. }
  292. location.volumesLock.RUnlock()
  293. if len(deleteVids) > 0 {
  294. // delete expired volumes.
  295. location.volumesLock.Lock()
  296. for _, vid := range deleteVids {
  297. found, err := location.deleteVolumeById(vid, false)
  298. if err == nil {
  299. if found {
  300. glog.V(0).Infof("volume %d is deleted", vid)
  301. }
  302. } else {
  303. glog.Warningf("delete volume %d: %v", vid, err)
  304. }
  305. }
  306. location.volumesLock.Unlock()
  307. }
  308. }
  309. // delete expired ec volumes
  310. ecVolumeMessages, deletedEcVolumes := s.deleteExpiredEcVolumes()
  311. var uuidList []string
  312. for _, loc := range s.Locations {
  313. uuidList = append(uuidList, loc.DirectoryUuid)
  314. }
  315. for col, size := range collectionVolumeSize {
  316. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  317. }
  318. for col, deletedBytes := range collectionVolumeDeletedBytes {
  319. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "deleted_bytes").Set(float64(deletedBytes))
  320. }
  321. for col, types := range collectionVolumeReadOnlyCount {
  322. for t, count := range types {
  323. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, t).Set(float64(count))
  324. }
  325. }
  326. return &master_pb.Heartbeat{
  327. Ip: s.Ip,
  328. Port: uint32(s.Port),
  329. GrpcPort: uint32(s.GrpcPort),
  330. PublicUrl: s.PublicUrl,
  331. MaxVolumeCounts: maxVolumeCounts,
  332. MaxFileKey: NeedleIdToUint64(maxFileKey),
  333. DataCenter: s.dataCenter,
  334. Rack: s.rack,
  335. Volumes: volumeMessages,
  336. DeletedEcShards: deletedEcVolumes,
  337. HasNoVolumes: len(volumeMessages) == 0,
  338. HasNoEcShards: len(ecVolumeMessages) == 0,
  339. LocationUuids: uuidList,
  340. }
  341. }
  342. func (s *Store) deleteExpiredEcVolumes() (ecShards, deleted []*master_pb.VolumeEcShardInformationMessage) {
  343. for _, location := range s.Locations {
  344. for _, ev := range location.ecVolumes {
  345. messages := ev.ToVolumeEcShardInformationMessage()
  346. if ev.IsTimeToDestroy() {
  347. err := location.deleteEcVolumeById(ev.VolumeId)
  348. if err != nil {
  349. ecShards = append(ecShards, messages...)
  350. glog.Errorf("delete EcVolume err %d: %v", ev.VolumeId, err)
  351. continue
  352. }
  353. deleted = append(deleted, messages...)
  354. } else {
  355. ecShards = append(ecShards, messages...)
  356. }
  357. }
  358. }
  359. return
  360. }
  361. func (s *Store) SetStopping() {
  362. s.isStopping = true
  363. for _, location := range s.Locations {
  364. location.SetStopping()
  365. }
  366. }
  367. func (s *Store) LoadNewVolumes() {
  368. for _, location := range s.Locations {
  369. location.loadExistingVolumes(s.NeedleMapKind, 0)
  370. }
  371. }
  372. func (s *Store) Close() {
  373. for _, location := range s.Locations {
  374. location.Close()
  375. }
  376. }
  377. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, checkCookie bool, fsync bool) (isUnchanged bool, err error) {
  378. if v := s.findVolume(i); v != nil {
  379. if v.IsReadOnly() {
  380. err = fmt.Errorf("volume %d is read only", i)
  381. return
  382. }
  383. _, _, isUnchanged, err = v.writeNeedle2(n, checkCookie, fsync && s.isStopping)
  384. return
  385. }
  386. glog.V(0).Infoln("volume", i, "not found!")
  387. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  388. return
  389. }
  390. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  391. if v := s.findVolume(i); v != nil {
  392. if v.noWriteOrDelete {
  393. return 0, fmt.Errorf("volume %d is read only", i)
  394. }
  395. return v.deleteNeedle2(n)
  396. }
  397. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  398. }
  399. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption, onReadSizeFn func(size Size)) (int, error) {
  400. if v := s.findVolume(i); v != nil {
  401. return v.readNeedle(n, readOption, onReadSizeFn)
  402. }
  403. return 0, fmt.Errorf("volume %d not found", i)
  404. }
  405. func (s *Store) ReadVolumeNeedleMetaAt(i needle.VolumeId, n *needle.Needle, offset int64, size int32) error {
  406. if v := s.findVolume(i); v != nil {
  407. return v.readNeedleMetaAt(n, offset, size)
  408. }
  409. return fmt.Errorf("volume %d not found", i)
  410. }
  411. func (s *Store) ReadVolumeNeedleDataInto(i needle.VolumeId, n *needle.Needle, readOption *ReadOption, writer io.Writer, offset int64, size int64) error {
  412. if v := s.findVolume(i); v != nil {
  413. return v.readNeedleDataInto(n, readOption, writer, offset, size)
  414. }
  415. return fmt.Errorf("volume %d not found", i)
  416. }
  417. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  418. return s.findVolume(i)
  419. }
  420. func (s *Store) HasVolume(i needle.VolumeId) bool {
  421. v := s.findVolume(i)
  422. return v != nil
  423. }
  424. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  425. v := s.findVolume(i)
  426. if v == nil {
  427. return fmt.Errorf("volume %d not found", i)
  428. }
  429. v.noWriteLock.Lock()
  430. v.noWriteOrDelete = true
  431. v.noWriteLock.Unlock()
  432. return nil
  433. }
  434. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  435. v := s.findVolume(i)
  436. if v == nil {
  437. return fmt.Errorf("volume %d not found", i)
  438. }
  439. v.noWriteLock.Lock()
  440. v.noWriteOrDelete = false
  441. v.noWriteLock.Unlock()
  442. return nil
  443. }
  444. func (s *Store) MountVolume(i needle.VolumeId) error {
  445. for _, location := range s.Locations {
  446. if found := location.LoadVolume(i, s.NeedleMapKind); found == true {
  447. glog.V(0).Infof("mount volume %d", i)
  448. v := s.findVolume(i)
  449. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  450. Id: uint32(v.Id),
  451. Collection: v.Collection,
  452. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  453. Version: uint32(v.Version()),
  454. Ttl: v.Ttl.ToUint32(),
  455. DiskType: string(v.location.DiskType),
  456. }
  457. return nil
  458. }
  459. }
  460. return fmt.Errorf("volume %d not found on disk", i)
  461. }
  462. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  463. v := s.findVolume(i)
  464. if v == nil {
  465. return nil
  466. }
  467. message := master_pb.VolumeShortInformationMessage{
  468. Id: uint32(v.Id),
  469. Collection: v.Collection,
  470. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  471. Version: uint32(v.Version()),
  472. Ttl: v.Ttl.ToUint32(),
  473. DiskType: string(v.location.DiskType),
  474. }
  475. for _, location := range s.Locations {
  476. err := location.UnloadVolume(i)
  477. if err == nil {
  478. glog.V(0).Infof("UnmountVolume %d", i)
  479. stats.DeleteCollectionMetrics(v.Collection)
  480. s.DeletedVolumesChan <- message
  481. return nil
  482. } else if err == ErrVolumeNotFound {
  483. continue
  484. }
  485. }
  486. return fmt.Errorf("volume %d not found on disk", i)
  487. }
  488. func (s *Store) DeleteVolume(i needle.VolumeId, onlyEmpty bool) error {
  489. v := s.findVolume(i)
  490. if v == nil {
  491. return fmt.Errorf("delete volume %d not found on disk", i)
  492. }
  493. message := master_pb.VolumeShortInformationMessage{
  494. Id: uint32(v.Id),
  495. Collection: v.Collection,
  496. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  497. Version: uint32(v.Version()),
  498. Ttl: v.Ttl.ToUint32(),
  499. DiskType: string(v.location.DiskType),
  500. }
  501. for _, location := range s.Locations {
  502. err := location.DeleteVolume(i, onlyEmpty)
  503. if err == nil {
  504. glog.V(0).Infof("DeleteVolume %d", i)
  505. s.DeletedVolumesChan <- message
  506. return nil
  507. } else if err == ErrVolumeNotFound {
  508. continue
  509. } else if err == ErrVolumeNotEmpty {
  510. return fmt.Errorf("DeleteVolume %d: %v", i, err)
  511. } else {
  512. glog.Errorf("DeleteVolume %d: %v", i, err)
  513. }
  514. }
  515. return fmt.Errorf("volume %d not found on disk", i)
  516. }
  517. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  518. for _, location := range s.Locations {
  519. fileInfo, found := location.LocateVolume(i)
  520. if !found {
  521. continue
  522. }
  523. // load, modify, save
  524. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  525. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  526. volumeInfo, _, _, err := volume_info.MaybeLoadVolumeInfo(vifFile)
  527. if err != nil {
  528. return fmt.Errorf("volume %d failed to load vif: %v", i, err)
  529. }
  530. volumeInfo.Replication = replication
  531. err = volume_info.SaveVolumeInfo(vifFile, volumeInfo)
  532. if err != nil {
  533. return fmt.Errorf("volume %d failed to save vif: %v", i, err)
  534. }
  535. return nil
  536. }
  537. return fmt.Errorf("volume %d not found on disk", i)
  538. }
  539. func (s *Store) SetVolumeSizeLimit(x uint64) {
  540. atomic.StoreUint64(&s.volumeSizeLimit, x)
  541. }
  542. func (s *Store) GetVolumeSizeLimit() uint64 {
  543. return atomic.LoadUint64(&s.volumeSizeLimit)
  544. }
  545. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  546. volumeSizeLimit := s.GetVolumeSizeLimit()
  547. if volumeSizeLimit == 0 {
  548. return
  549. }
  550. var newMaxVolumeCount int32
  551. for _, diskLocation := range s.Locations {
  552. if diskLocation.OriginalMaxVolumeCount == 0 {
  553. currentMaxVolumeCount := atomic.LoadInt32(&diskLocation.MaxVolumeCount)
  554. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  555. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  556. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  557. volCount := diskLocation.VolumesLen()
  558. maxVolumeCount := int32(volCount)
  559. if unclaimedSpaces > int64(volumeSizeLimit) {
  560. maxVolumeCount += int32(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  561. }
  562. newMaxVolumeCount = newMaxVolumeCount + maxVolumeCount
  563. atomic.StoreInt32(&diskLocation.MaxVolumeCount, maxVolumeCount)
  564. glog.V(4).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  565. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  566. hasChanges = hasChanges || currentMaxVolumeCount != atomic.LoadInt32(&diskLocation.MaxVolumeCount)
  567. } else {
  568. newMaxVolumeCount = newMaxVolumeCount + diskLocation.OriginalMaxVolumeCount
  569. }
  570. }
  571. stats.VolumeServerMaxVolumeCounter.Set(float64(newMaxVolumeCount))
  572. return
  573. }