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.

455 lines
14 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. collectionVolumeReadOnlyCount := make(map[string]uint8)
  182. for _, location := range s.Locations {
  183. var deleteVids []needle.VolumeId
  184. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  185. location.volumesLock.RLock()
  186. for _, v := range location.volumes {
  187. if maxFileKey < v.MaxFileKey() {
  188. maxFileKey = v.MaxFileKey()
  189. }
  190. if !v.expired(s.GetVolumeSizeLimit()) {
  191. volumeMessages = append(volumeMessages, v.ToVolumeInformationMessage())
  192. } else {
  193. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  194. deleteVids = append(deleteVids, v.Id)
  195. } else {
  196. glog.V(0).Infoln("volume", v.Id, "is expired.")
  197. }
  198. }
  199. fileSize, _, _ := v.FileStat()
  200. collectionVolumeSize[v.Collection] += fileSize
  201. if v.IsReadOnly() {
  202. collectionVolumeReadOnlyCount[v.Collection] += 1
  203. }
  204. }
  205. location.volumesLock.RUnlock()
  206. if len(deleteVids) > 0 {
  207. // delete expired volumes.
  208. location.volumesLock.Lock()
  209. for _, vid := range deleteVids {
  210. found, err := location.deleteVolumeById(vid)
  211. if found {
  212. if err == nil {
  213. glog.V(0).Infof("volume %d is deleted", vid)
  214. } else {
  215. glog.V(0).Infof("delete volume %d: %v", vid, err)
  216. }
  217. }
  218. }
  219. location.volumesLock.Unlock()
  220. }
  221. }
  222. for col, size := range collectionVolumeSize {
  223. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  224. }
  225. for col, count := range collectionVolumeReadOnlyCount {
  226. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, "normal").Set(float64(count))
  227. }
  228. return &master_pb.Heartbeat{
  229. Ip: s.Ip,
  230. Port: uint32(s.Port),
  231. PublicUrl: s.PublicUrl,
  232. MaxVolumeCount: uint32(maxVolumeCount),
  233. MaxFileKey: NeedleIdToUint64(maxFileKey),
  234. DataCenter: s.dataCenter,
  235. Rack: s.rack,
  236. Volumes: volumeMessages,
  237. HasNoVolumes: len(volumeMessages) == 0,
  238. }
  239. }
  240. func (s *Store) Close() {
  241. for _, location := range s.Locations {
  242. location.Close()
  243. }
  244. }
  245. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, fsync bool) (isUnchanged bool, err error) {
  246. if v := s.findVolume(i); v != nil {
  247. if v.IsReadOnly() {
  248. err = fmt.Errorf("volume %d is read only", i)
  249. return
  250. }
  251. _, _, isUnchanged, err = v.writeNeedle2(n, fsync)
  252. return
  253. }
  254. glog.V(0).Infoln("volume", i, "not found!")
  255. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  256. return
  257. }
  258. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  259. if v := s.findVolume(i); v != nil {
  260. if v.noWriteOrDelete {
  261. return 0, fmt.Errorf("volume %d is read only", i)
  262. }
  263. return v.deleteNeedle2(n)
  264. }
  265. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  266. }
  267. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption) (int, error) {
  268. if v := s.findVolume(i); v != nil {
  269. return v.readNeedle(n, readOption)
  270. }
  271. return 0, fmt.Errorf("volume %d not found", i)
  272. }
  273. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  274. return s.findVolume(i)
  275. }
  276. func (s *Store) HasVolume(i needle.VolumeId) bool {
  277. v := s.findVolume(i)
  278. return v != nil
  279. }
  280. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  281. v := s.findVolume(i)
  282. if v == nil {
  283. return fmt.Errorf("volume %d not found", i)
  284. }
  285. v.noWriteLock.Lock()
  286. v.noWriteOrDelete = true
  287. v.noWriteLock.Unlock()
  288. return nil
  289. }
  290. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  291. v := s.findVolume(i)
  292. if v == nil {
  293. return fmt.Errorf("volume %d not found", i)
  294. }
  295. v.noWriteLock.Lock()
  296. v.noWriteOrDelete = false
  297. v.noWriteLock.Unlock()
  298. return nil
  299. }
  300. func (s *Store) MountVolume(i needle.VolumeId) error {
  301. for _, location := range s.Locations {
  302. if found := location.LoadVolume(i, s.NeedleMapType); found == true {
  303. glog.V(0).Infof("mount volume %d", i)
  304. v := s.findVolume(i)
  305. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  306. Id: uint32(v.Id),
  307. Collection: v.Collection,
  308. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  309. Version: uint32(v.Version()),
  310. Ttl: v.Ttl.ToUint32(),
  311. }
  312. return nil
  313. }
  314. }
  315. return fmt.Errorf("volume %d not found on disk", i)
  316. }
  317. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  318. v := s.findVolume(i)
  319. if v == nil {
  320. return nil
  321. }
  322. message := master_pb.VolumeShortInformationMessage{
  323. Id: uint32(v.Id),
  324. Collection: v.Collection,
  325. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  326. Version: uint32(v.Version()),
  327. Ttl: v.Ttl.ToUint32(),
  328. }
  329. for _, location := range s.Locations {
  330. if err := location.UnloadVolume(i); err == nil {
  331. glog.V(0).Infof("UnmountVolume %d", i)
  332. s.DeletedVolumesChan <- message
  333. return nil
  334. }
  335. }
  336. return fmt.Errorf("volume %d not found on disk", i)
  337. }
  338. func (s *Store) DeleteVolume(i needle.VolumeId) error {
  339. v := s.findVolume(i)
  340. if v == nil {
  341. return fmt.Errorf("delete volume %d not found on disk", i)
  342. }
  343. message := master_pb.VolumeShortInformationMessage{
  344. Id: uint32(v.Id),
  345. Collection: v.Collection,
  346. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  347. Version: uint32(v.Version()),
  348. Ttl: v.Ttl.ToUint32(),
  349. }
  350. for _, location := range s.Locations {
  351. if err := location.DeleteVolume(i); err == nil {
  352. glog.V(0).Infof("DeleteVolume %d", i)
  353. s.DeletedVolumesChan <- message
  354. return nil
  355. } else {
  356. glog.Errorf("DeleteVolume %d: %v", i, err)
  357. }
  358. }
  359. return fmt.Errorf("volume %d not found on disk", i)
  360. }
  361. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  362. for _, location := range s.Locations {
  363. fileInfo, found := location.LocateVolume(i)
  364. if !found {
  365. continue
  366. }
  367. // load, modify, save
  368. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  369. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  370. volumeInfo, _, err := pb.MaybeLoadVolumeInfo(vifFile)
  371. if err != nil {
  372. return fmt.Errorf("volume %d fail to load vif", i)
  373. }
  374. volumeInfo.Replication = replication
  375. err = pb.SaveVolumeInfo(vifFile, volumeInfo)
  376. if err != nil {
  377. return fmt.Errorf("volume %d fail to save vif", i)
  378. }
  379. return nil
  380. }
  381. return fmt.Errorf("volume %d not found on disk", i)
  382. }
  383. func (s *Store) SetVolumeSizeLimit(x uint64) {
  384. atomic.StoreUint64(&s.volumeSizeLimit, x)
  385. }
  386. func (s *Store) GetVolumeSizeLimit() uint64 {
  387. return atomic.LoadUint64(&s.volumeSizeLimit)
  388. }
  389. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  390. volumeSizeLimit := s.GetVolumeSizeLimit()
  391. for _, diskLocation := range s.Locations {
  392. if diskLocation.MaxVolumeCount == 0 {
  393. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  394. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  395. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  396. volCount := diskLocation.VolumesLen()
  397. maxVolumeCount := volCount
  398. if unclaimedSpaces > int64(volumeSizeLimit) {
  399. maxVolumeCount += int(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  400. }
  401. diskLocation.MaxVolumeCount = maxVolumeCount
  402. glog.V(0).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  403. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  404. hasChanges = true
  405. }
  406. }
  407. return
  408. }