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.

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