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.

499 lines
15 KiB

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