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.

447 lines
13 KiB

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