store.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. package storage
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strings"
  6. "sync/atomic"
  7. "google.golang.org/grpc"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/pb"
  10. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  11. "github.com/chrislusf/seaweedfs/weed/stats"
  12. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  13. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  14. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  15. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  16. )
  17. const (
  18. MAX_TTL_VOLUME_REMOVAL_DELAY = 10 // 10 minutes
  19. )
  20. type ReadOption struct {
  21. ReadDeleted bool
  22. }
  23. /*
  24. * A VolumeServer contains one Store
  25. */
  26. type Store struct {
  27. MasterAddress string
  28. grpcDialOption grpc.DialOption
  29. volumeSizeLimit uint64 // read from the master
  30. Ip string
  31. Port int
  32. PublicUrl string
  33. Locations []*DiskLocation
  34. dataCenter string // optional informaton, overwriting master setting if exists
  35. rack string // optional information, overwriting master setting if exists
  36. connected bool
  37. NeedleMapKind NeedleMapKind
  38. NewVolumesChan chan master_pb.VolumeShortInformationMessage
  39. DeletedVolumesChan chan master_pb.VolumeShortInformationMessage
  40. NewEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  41. DeletedEcShardsChan chan master_pb.VolumeEcShardInformationMessage
  42. }
  43. func (s *Store) String() (str string) {
  44. str = fmt.Sprintf("Ip:%s, Port:%d, PublicUrl:%s, dataCenter:%s, rack:%s, connected:%v, volumeSizeLimit:%d", s.Ip, s.Port, s.PublicUrl, s.dataCenter, s.rack, s.connected, s.GetVolumeSizeLimit())
  45. return
  46. }
  47. func NewStore(grpcDialOption grpc.DialOption, port int, ip, publicUrl string, dirnames []string, maxVolumeCounts []int, minFreeSpacePercents []float32, idxFolder string, needleMapKind NeedleMapKind, diskTypes []DiskType) (s *Store) {
  48. s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, PublicUrl: publicUrl, NeedleMapKind: needleMapKind}
  49. s.Locations = make([]*DiskLocation, 0)
  50. for i := 0; i < len(dirnames); i++ {
  51. location := NewDiskLocation(dirnames[i], maxVolumeCounts[i], minFreeSpacePercents[i], idxFolder, diskTypes[i])
  52. location.loadExistingVolumes(needleMapKind)
  53. s.Locations = append(s.Locations, location)
  54. stats.VolumeServerMaxVolumeCounter.Add(float64(maxVolumeCounts[i]))
  55. }
  56. s.NewVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  57. s.DeletedVolumesChan = make(chan master_pb.VolumeShortInformationMessage, 3)
  58. s.NewEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  59. s.DeletedEcShardsChan = make(chan master_pb.VolumeEcShardInformationMessage, 3)
  60. return
  61. }
  62. func (s *Store) AddVolume(volumeId needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement string, ttlString string, preallocate int64, MemoryMapMaxSizeMb uint32, diskType DiskType) error {
  63. rt, e := super_block.NewReplicaPlacementFromString(replicaPlacement)
  64. if e != nil {
  65. return e
  66. }
  67. ttl, e := needle.ReadTTL(ttlString)
  68. if e != nil {
  69. return e
  70. }
  71. e = s.addVolume(volumeId, collection, needleMapKind, rt, ttl, preallocate, MemoryMapMaxSizeMb, diskType)
  72. return e
  73. }
  74. func (s *Store) DeleteCollection(collection string) (e error) {
  75. for _, location := range s.Locations {
  76. e = location.DeleteCollectionFromDiskLocation(collection)
  77. if e != nil {
  78. return
  79. }
  80. // let the heartbeat send the list of volumes, instead of sending the deleted volume ids to DeletedVolumesChan
  81. }
  82. return
  83. }
  84. func (s *Store) findVolume(vid needle.VolumeId) *Volume {
  85. for _, location := range s.Locations {
  86. if v, found := location.FindVolume(vid); found {
  87. return v
  88. }
  89. }
  90. return nil
  91. }
  92. func (s *Store) FindFreeLocation(diskType DiskType) (ret *DiskLocation) {
  93. max := 0
  94. for _, location := range s.Locations {
  95. if diskType != location.DiskType {
  96. continue
  97. }
  98. currentFreeCount := location.MaxVolumeCount - location.VolumesLen()
  99. currentFreeCount *= erasure_coding.DataShardsCount
  100. currentFreeCount -= location.EcVolumesLen()
  101. currentFreeCount /= erasure_coding.DataShardsCount
  102. if currentFreeCount > max {
  103. max = currentFreeCount
  104. ret = location
  105. }
  106. }
  107. return ret
  108. }
  109. func (s *Store) addVolume(vid needle.VolumeId, collection string, needleMapKind NeedleMapKind, replicaPlacement *super_block.ReplicaPlacement, ttl *needle.TTL, preallocate int64, memoryMapMaxSizeMb uint32, diskType DiskType) error {
  110. if s.findVolume(vid) != nil {
  111. return fmt.Errorf("Volume Id %d already exists!", vid)
  112. }
  113. if location := s.FindFreeLocation(diskType); location != nil {
  114. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  115. location.Directory, vid, collection, replicaPlacement, ttl)
  116. if volume, err := NewVolume(location.Directory, location.IdxDirectory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate, memoryMapMaxSizeMb); err == nil {
  117. location.SetVolume(vid, volume)
  118. glog.V(0).Infof("add volume %d", vid)
  119. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  120. Id: uint32(vid),
  121. Collection: collection,
  122. ReplicaPlacement: uint32(replicaPlacement.Byte()),
  123. Version: uint32(volume.Version()),
  124. Ttl: ttl.ToUint32(),
  125. DiskType: string(diskType),
  126. }
  127. return nil
  128. } else {
  129. return err
  130. }
  131. }
  132. return fmt.Errorf("No more free space left")
  133. }
  134. func (s *Store) VolumeInfos() (allStats []*VolumeInfo) {
  135. for _, location := range s.Locations {
  136. stats := collectStatsForOneLocation(location)
  137. allStats = append(allStats, stats...)
  138. }
  139. sortVolumeInfos(allStats)
  140. return allStats
  141. }
  142. func collectStatsForOneLocation(location *DiskLocation) (stats []*VolumeInfo) {
  143. location.volumesLock.RLock()
  144. defer location.volumesLock.RUnlock()
  145. for k, v := range location.volumes {
  146. s := collectStatForOneVolume(k, v)
  147. stats = append(stats, s)
  148. }
  149. return stats
  150. }
  151. func collectStatForOneVolume(vid needle.VolumeId, v *Volume) (s *VolumeInfo) {
  152. s = &VolumeInfo{
  153. Id: vid,
  154. Collection: v.Collection,
  155. ReplicaPlacement: v.ReplicaPlacement,
  156. Version: v.Version(),
  157. ReadOnly: v.IsReadOnly(),
  158. Ttl: v.Ttl,
  159. CompactRevision: uint32(v.CompactionRevision),
  160. DiskType: v.DiskType().String(),
  161. }
  162. s.RemoteStorageName, s.RemoteStorageKey = v.RemoteStorageNameKey()
  163. v.dataFileAccessLock.RLock()
  164. defer v.dataFileAccessLock.RUnlock()
  165. if v.nm == nil {
  166. return
  167. }
  168. s.FileCount = v.nm.FileCount()
  169. s.DeleteCount = v.nm.DeletedCount()
  170. s.DeletedByteCount = v.nm.DeletedSize()
  171. s.Size = v.nm.ContentSize()
  172. return
  173. }
  174. func (s *Store) SetDataCenter(dataCenter string) {
  175. s.dataCenter = dataCenter
  176. }
  177. func (s *Store) SetRack(rack string) {
  178. s.rack = rack
  179. }
  180. func (s *Store) GetDataCenter() string {
  181. return s.dataCenter
  182. }
  183. func (s *Store) GetRack() string {
  184. return s.rack
  185. }
  186. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  187. var volumeMessages []*master_pb.VolumeInformationMessage
  188. maxVolumeCounts := make(map[string]uint32)
  189. var maxFileKey NeedleId
  190. collectionVolumeSize := make(map[string]uint64)
  191. collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
  192. for _, location := range s.Locations {
  193. var deleteVids []needle.VolumeId
  194. maxVolumeCounts[string(location.DiskType)] += uint32(location.MaxVolumeCount)
  195. location.volumesLock.RLock()
  196. for _, v := range location.volumes {
  197. curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage()
  198. if maxFileKey < curMaxFileKey {
  199. maxFileKey = curMaxFileKey
  200. }
  201. deleteVolume := false
  202. if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
  203. volumeMessages = append(volumeMessages, volumeMessage)
  204. } else {
  205. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  206. deleteVids = append(deleteVids, v.Id)
  207. deleteVolume = true
  208. } else {
  209. glog.V(0).Infof("volume %d is expired", v.Id)
  210. }
  211. if v.lastIoError != nil {
  212. deleteVids = append(deleteVids, v.Id)
  213. deleteVolume = true
  214. glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
  215. }
  216. }
  217. if _, exist := collectionVolumeSize[v.Collection]; !exist {
  218. collectionVolumeSize[v.Collection] = 0
  219. }
  220. if !deleteVolume {
  221. collectionVolumeSize[v.Collection] += volumeMessage.Size
  222. }
  223. if _, exist := collectionVolumeReadOnlyCount[v.Collection]; !exist {
  224. collectionVolumeReadOnlyCount[v.Collection] = map[string]uint8{
  225. "IsReadOnly": 0,
  226. "noWriteOrDelete": 0,
  227. "noWriteCanDelete": 0,
  228. "isDiskSpaceLow": 0,
  229. }
  230. }
  231. if !deleteVolume && v.IsReadOnly() {
  232. collectionVolumeReadOnlyCount[v.Collection]["IsReadOnly"] += 1
  233. if v.noWriteOrDelete {
  234. collectionVolumeReadOnlyCount[v.Collection]["noWriteOrDelete"] += 1
  235. }
  236. if v.noWriteCanDelete {
  237. collectionVolumeReadOnlyCount[v.Collection]["noWriteCanDelete"] += 1
  238. }
  239. if v.location.isDiskSpaceLow {
  240. collectionVolumeReadOnlyCount[v.Collection]["isDiskSpaceLow"] += 1
  241. }
  242. }
  243. }
  244. location.volumesLock.RUnlock()
  245. if len(deleteVids) > 0 {
  246. // delete expired volumes.
  247. location.volumesLock.Lock()
  248. for _, vid := range deleteVids {
  249. found, err := location.deleteVolumeById(vid)
  250. if err == nil {
  251. if found {
  252. glog.V(0).Infof("volume %d is deleted", vid)
  253. }
  254. } else {
  255. glog.Warningf("delete volume %d: %v", vid, err)
  256. }
  257. }
  258. location.volumesLock.Unlock()
  259. }
  260. }
  261. for col, size := range collectionVolumeSize {
  262. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  263. }
  264. for col, types := range collectionVolumeReadOnlyCount {
  265. for t, count := range types {
  266. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, t).Set(float64(count))
  267. }
  268. }
  269. return &master_pb.Heartbeat{
  270. Ip: s.Ip,
  271. Port: uint32(s.Port),
  272. PublicUrl: s.PublicUrl,
  273. MaxVolumeCounts: maxVolumeCounts,
  274. MaxFileKey: NeedleIdToUint64(maxFileKey),
  275. DataCenter: s.dataCenter,
  276. Rack: s.rack,
  277. Volumes: volumeMessages,
  278. HasNoVolumes: len(volumeMessages) == 0,
  279. }
  280. }
  281. func (s *Store) Close() {
  282. for _, location := range s.Locations {
  283. location.Close()
  284. }
  285. }
  286. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, fsync bool) (isUnchanged bool, err error) {
  287. if v := s.findVolume(i); v != nil {
  288. if v.IsReadOnly() {
  289. err = fmt.Errorf("volume %d is read only", i)
  290. return
  291. }
  292. _, _, isUnchanged, err = v.writeNeedle2(n, fsync)
  293. return
  294. }
  295. glog.V(0).Infoln("volume", i, "not found!")
  296. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  297. return
  298. }
  299. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  300. if v := s.findVolume(i); v != nil {
  301. if v.noWriteOrDelete {
  302. return 0, fmt.Errorf("volume %d is read only", i)
  303. }
  304. return v.deleteNeedle2(n)
  305. }
  306. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  307. }
  308. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption) (int, error) {
  309. if v := s.findVolume(i); v != nil {
  310. return v.readNeedle(n, readOption)
  311. }
  312. return 0, fmt.Errorf("volume %d not found", i)
  313. }
  314. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  315. return s.findVolume(i)
  316. }
  317. func (s *Store) HasVolume(i needle.VolumeId) bool {
  318. v := s.findVolume(i)
  319. return v != nil
  320. }
  321. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  322. v := s.findVolume(i)
  323. if v == nil {
  324. return fmt.Errorf("volume %d not found", i)
  325. }
  326. v.noWriteLock.Lock()
  327. v.noWriteOrDelete = true
  328. v.noWriteLock.Unlock()
  329. return nil
  330. }
  331. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  332. v := s.findVolume(i)
  333. if v == nil {
  334. return fmt.Errorf("volume %d not found", i)
  335. }
  336. v.noWriteLock.Lock()
  337. v.noWriteOrDelete = false
  338. v.noWriteLock.Unlock()
  339. return nil
  340. }
  341. func (s *Store) MountVolume(i needle.VolumeId) error {
  342. for _, location := range s.Locations {
  343. if found := location.LoadVolume(i, s.NeedleMapKind); found == true {
  344. glog.V(0).Infof("mount volume %d", i)
  345. v := s.findVolume(i)
  346. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  347. Id: uint32(v.Id),
  348. Collection: v.Collection,
  349. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  350. Version: uint32(v.Version()),
  351. Ttl: v.Ttl.ToUint32(),
  352. DiskType: string(v.location.DiskType),
  353. }
  354. return nil
  355. }
  356. }
  357. return fmt.Errorf("volume %d not found on disk", i)
  358. }
  359. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  360. v := s.findVolume(i)
  361. if v == nil {
  362. return nil
  363. }
  364. message := master_pb.VolumeShortInformationMessage{
  365. Id: uint32(v.Id),
  366. Collection: v.Collection,
  367. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  368. Version: uint32(v.Version()),
  369. Ttl: v.Ttl.ToUint32(),
  370. DiskType: string(v.location.DiskType),
  371. }
  372. for _, location := range s.Locations {
  373. if err := location.UnloadVolume(i); err == nil {
  374. glog.V(0).Infof("UnmountVolume %d", i)
  375. s.DeletedVolumesChan <- message
  376. return nil
  377. }
  378. }
  379. return fmt.Errorf("volume %d not found on disk", i)
  380. }
  381. func (s *Store) DeleteVolume(i needle.VolumeId) error {
  382. v := s.findVolume(i)
  383. if v == nil {
  384. return fmt.Errorf("delete volume %d not found on disk", i)
  385. }
  386. message := master_pb.VolumeShortInformationMessage{
  387. Id: uint32(v.Id),
  388. Collection: v.Collection,
  389. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  390. Version: uint32(v.Version()),
  391. Ttl: v.Ttl.ToUint32(),
  392. DiskType: string(v.location.DiskType),
  393. }
  394. for _, location := range s.Locations {
  395. if err := location.DeleteVolume(i); err == nil {
  396. glog.V(0).Infof("DeleteVolume %d", i)
  397. s.DeletedVolumesChan <- message
  398. return nil
  399. } else {
  400. glog.Errorf("DeleteVolume %d: %v", i, err)
  401. }
  402. }
  403. return fmt.Errorf("volume %d not found on disk", i)
  404. }
  405. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  406. for _, location := range s.Locations {
  407. fileInfo, found := location.LocateVolume(i)
  408. if !found {
  409. continue
  410. }
  411. // load, modify, save
  412. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  413. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  414. volumeInfo, _, _, err := pb.MaybeLoadVolumeInfo(vifFile)
  415. if err != nil {
  416. return fmt.Errorf("volume %d fail to load vif", i)
  417. }
  418. volumeInfo.Replication = replication
  419. err = pb.SaveVolumeInfo(vifFile, volumeInfo)
  420. if err != nil {
  421. return fmt.Errorf("volume %d fail to save vif", i)
  422. }
  423. return nil
  424. }
  425. return fmt.Errorf("volume %d not found on disk", i)
  426. }
  427. func (s *Store) SetVolumeSizeLimit(x uint64) {
  428. atomic.StoreUint64(&s.volumeSizeLimit, x)
  429. }
  430. func (s *Store) GetVolumeSizeLimit() uint64 {
  431. return atomic.LoadUint64(&s.volumeSizeLimit)
  432. }
  433. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  434. volumeSizeLimit := s.GetVolumeSizeLimit()
  435. if volumeSizeLimit == 0 {
  436. return
  437. }
  438. for _, diskLocation := range s.Locations {
  439. if diskLocation.OriginalMaxVolumeCount == 0 {
  440. currentMaxVolumeCount := diskLocation.MaxVolumeCount
  441. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  442. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  443. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  444. volCount := diskLocation.VolumesLen()
  445. maxVolumeCount := volCount
  446. if unclaimedSpaces > int64(volumeSizeLimit) {
  447. maxVolumeCount += int(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  448. }
  449. diskLocation.MaxVolumeCount = maxVolumeCount
  450. glog.V(2).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  451. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  452. hasChanges = hasChanges || currentMaxVolumeCount != diskLocation.MaxVolumeCount
  453. }
  454. }
  455. return
  456. }