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.

459 lines
14 KiB

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