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.

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