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.

491 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. NeedleMapType NeedleMapType
  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 NeedleMapType, diskType DiskType) (s *Store) {
  48. s = &Store{grpcDialOption: grpcDialOption, Port: port, Ip: ip, PublicUrl: publicUrl, NeedleMapType: 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, diskType)
  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 NeedleMapType, replicaPlacement string, ttlString string, preallocate int64, MemoryMapMaxSizeMb uint32) 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)
  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() (ret *DiskLocation) {
  93. max := 0
  94. for _, location := range s.Locations {
  95. currentFreeCount := location.MaxVolumeCount - location.VolumesLen()
  96. currentFreeCount *= erasure_coding.DataShardsCount
  97. currentFreeCount -= location.EcVolumesLen()
  98. currentFreeCount /= erasure_coding.DataShardsCount
  99. if currentFreeCount > max {
  100. max = currentFreeCount
  101. ret = location
  102. }
  103. }
  104. return ret
  105. }
  106. func (s *Store) addVolume(vid needle.VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement *super_block.ReplicaPlacement, ttl *needle.TTL, preallocate int64, memoryMapMaxSizeMb uint32) error {
  107. if s.findVolume(vid) != nil {
  108. return fmt.Errorf("Volume Id %d already exists!", vid)
  109. }
  110. if location := s.FindFreeLocation(); location != nil {
  111. glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
  112. location.Directory, vid, collection, replicaPlacement, ttl)
  113. if volume, err := NewVolume(location.Directory, location.IdxDirectory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate, memoryMapMaxSizeMb); err == nil {
  114. location.SetVolume(vid, volume)
  115. glog.V(0).Infof("add volume %d", vid)
  116. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  117. Id: uint32(vid),
  118. Collection: collection,
  119. ReplicaPlacement: uint32(replicaPlacement.Byte()),
  120. Version: uint32(volume.Version()),
  121. Ttl: ttl.ToUint32(),
  122. }
  123. return nil
  124. } else {
  125. return err
  126. }
  127. }
  128. return fmt.Errorf("No more free space left")
  129. }
  130. func (s *Store) VolumeInfos() (allStats []*VolumeInfo) {
  131. for _, location := range s.Locations {
  132. stats := collectStatsForOneLocation(location)
  133. allStats = append(allStats, stats...)
  134. }
  135. sortVolumeInfos(allStats)
  136. return allStats
  137. }
  138. func collectStatsForOneLocation(location *DiskLocation) (stats []*VolumeInfo) {
  139. location.volumesLock.RLock()
  140. defer location.volumesLock.RUnlock()
  141. for k, v := range location.volumes {
  142. s := collectStatForOneVolume(k, v)
  143. stats = append(stats, s)
  144. }
  145. return stats
  146. }
  147. func collectStatForOneVolume(vid needle.VolumeId, v *Volume) (s *VolumeInfo) {
  148. s = &VolumeInfo{
  149. Id: vid,
  150. Collection: v.Collection,
  151. ReplicaPlacement: v.ReplicaPlacement,
  152. Version: v.Version(),
  153. ReadOnly: v.IsReadOnly(),
  154. Ttl: v.Ttl,
  155. CompactRevision: uint32(v.CompactionRevision),
  156. }
  157. s.RemoteStorageName, s.RemoteStorageKey = v.RemoteStorageNameKey()
  158. v.dataFileAccessLock.RLock()
  159. defer v.dataFileAccessLock.RUnlock()
  160. if v.nm == nil {
  161. return
  162. }
  163. s.FileCount = v.nm.FileCount()
  164. s.DeleteCount = v.nm.DeletedCount()
  165. s.DeletedByteCount = v.nm.DeletedSize()
  166. s.Size = v.nm.ContentSize()
  167. return
  168. }
  169. func (s *Store) SetDataCenter(dataCenter string) {
  170. s.dataCenter = dataCenter
  171. }
  172. func (s *Store) SetRack(rack string) {
  173. s.rack = rack
  174. }
  175. func (s *Store) GetDataCenter() string {
  176. return s.dataCenter
  177. }
  178. func (s *Store) GetRack() string {
  179. return s.rack
  180. }
  181. func (s *Store) CollectHeartbeat() *master_pb.Heartbeat {
  182. var volumeMessages []*master_pb.VolumeInformationMessage
  183. maxVolumeCount := 0
  184. maxSsdVolumeCount := 0
  185. var maxFileKey NeedleId
  186. collectionVolumeSize := make(map[string]uint64)
  187. collectionVolumeReadOnlyCount := make(map[string]map[string]uint8)
  188. for _, location := range s.Locations {
  189. var deleteVids []needle.VolumeId
  190. switch location.DiskType {
  191. case SsdType:
  192. maxSsdVolumeCount = maxSsdVolumeCount + location.MaxVolumeCount
  193. case HardDriveType:
  194. maxVolumeCount = maxVolumeCount + location.MaxVolumeCount
  195. }
  196. location.volumesLock.RLock()
  197. for _, v := range location.volumes {
  198. curMaxFileKey, volumeMessage := v.ToVolumeInformationMessage()
  199. if maxFileKey < curMaxFileKey {
  200. maxFileKey = curMaxFileKey
  201. }
  202. if !v.expired(volumeMessage.Size, s.GetVolumeSizeLimit()) {
  203. volumeMessages = append(volumeMessages, volumeMessage)
  204. } else {
  205. if v.expiredLongEnough(MAX_TTL_VOLUME_REMOVAL_DELAY) {
  206. deleteVids = append(deleteVids, v.Id)
  207. } else {
  208. glog.V(0).Infof("volume %d is expired", v.Id)
  209. }
  210. if v.lastIoError != nil {
  211. deleteVids = append(deleteVids, v.Id)
  212. glog.Warningf("volume %d has IO error: %v", v.Id, v.lastIoError)
  213. }
  214. }
  215. collectionVolumeSize[v.Collection] += volumeMessage.Size
  216. if _, exist := collectionVolumeReadOnlyCount[v.Collection]; !exist {
  217. collectionVolumeReadOnlyCount[v.Collection] = map[string]uint8{
  218. "IsReadOnly": 0,
  219. "noWriteOrDelete": 0,
  220. "noWriteCanDelete": 0,
  221. "isDiskSpaceLow": 0,
  222. }
  223. }
  224. if v.IsReadOnly() {
  225. collectionVolumeReadOnlyCount[v.Collection]["IsReadOnly"] += 1
  226. if v.noWriteOrDelete {
  227. collectionVolumeReadOnlyCount[v.Collection]["noWriteOrDelete"] += 1
  228. }
  229. if v.noWriteCanDelete {
  230. collectionVolumeReadOnlyCount[v.Collection]["noWriteCanDelete"] += 1
  231. }
  232. if v.location.isDiskSpaceLow {
  233. collectionVolumeReadOnlyCount[v.Collection]["isDiskSpaceLow"] += 1
  234. }
  235. }
  236. }
  237. location.volumesLock.RUnlock()
  238. if len(deleteVids) > 0 {
  239. // delete expired volumes.
  240. location.volumesLock.Lock()
  241. for _, vid := range deleteVids {
  242. found, err := location.deleteVolumeById(vid)
  243. if found {
  244. if err == nil {
  245. glog.V(0).Infof("volume %d is deleted", vid)
  246. } else {
  247. glog.V(0).Infof("delete volume %d: %v", vid, err)
  248. }
  249. }
  250. }
  251. location.volumesLock.Unlock()
  252. }
  253. }
  254. for col, size := range collectionVolumeSize {
  255. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  256. }
  257. for col, types := range collectionVolumeReadOnlyCount {
  258. for t, count := range types {
  259. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, t).Set(float64(count))
  260. }
  261. }
  262. return &master_pb.Heartbeat{
  263. Ip: s.Ip,
  264. Port: uint32(s.Port),
  265. PublicUrl: s.PublicUrl,
  266. MaxVolumeCount: uint32(maxVolumeCount),
  267. MaxSsdVolumeCount: uint32(maxSsdVolumeCount),
  268. MaxFileKey: NeedleIdToUint64(maxFileKey),
  269. DataCenter: s.dataCenter,
  270. Rack: s.rack,
  271. Volumes: volumeMessages,
  272. HasNoVolumes: len(volumeMessages) == 0,
  273. }
  274. }
  275. func (s *Store) Close() {
  276. for _, location := range s.Locations {
  277. location.Close()
  278. }
  279. }
  280. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, fsync bool) (isUnchanged bool, err error) {
  281. if v := s.findVolume(i); v != nil {
  282. if v.IsReadOnly() {
  283. err = fmt.Errorf("volume %d is read only", i)
  284. return
  285. }
  286. _, _, isUnchanged, err = v.writeNeedle2(n, fsync)
  287. return
  288. }
  289. glog.V(0).Infoln("volume", i, "not found!")
  290. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  291. return
  292. }
  293. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  294. if v := s.findVolume(i); v != nil {
  295. if v.noWriteOrDelete {
  296. return 0, fmt.Errorf("volume %d is read only", i)
  297. }
  298. return v.deleteNeedle2(n)
  299. }
  300. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  301. }
  302. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption) (int, error) {
  303. if v := s.findVolume(i); v != nil {
  304. return v.readNeedle(n, readOption)
  305. }
  306. return 0, fmt.Errorf("volume %d not found", i)
  307. }
  308. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  309. return s.findVolume(i)
  310. }
  311. func (s *Store) HasVolume(i needle.VolumeId) bool {
  312. v := s.findVolume(i)
  313. return v != nil
  314. }
  315. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  316. v := s.findVolume(i)
  317. if v == nil {
  318. return fmt.Errorf("volume %d not found", i)
  319. }
  320. v.noWriteLock.Lock()
  321. v.noWriteOrDelete = true
  322. v.noWriteLock.Unlock()
  323. return nil
  324. }
  325. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  326. v := s.findVolume(i)
  327. if v == nil {
  328. return fmt.Errorf("volume %d not found", i)
  329. }
  330. v.noWriteLock.Lock()
  331. v.noWriteOrDelete = false
  332. v.noWriteLock.Unlock()
  333. return nil
  334. }
  335. func (s *Store) MountVolume(i needle.VolumeId) error {
  336. for _, location := range s.Locations {
  337. if found := location.LoadVolume(i, s.NeedleMapType); found == true {
  338. glog.V(0).Infof("mount volume %d", i)
  339. v := s.findVolume(i)
  340. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  341. Id: uint32(v.Id),
  342. Collection: v.Collection,
  343. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  344. Version: uint32(v.Version()),
  345. Ttl: v.Ttl.ToUint32(),
  346. }
  347. return nil
  348. }
  349. }
  350. return fmt.Errorf("volume %d not found on disk", i)
  351. }
  352. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  353. v := s.findVolume(i)
  354. if v == nil {
  355. return nil
  356. }
  357. message := master_pb.VolumeShortInformationMessage{
  358. Id: uint32(v.Id),
  359. Collection: v.Collection,
  360. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  361. Version: uint32(v.Version()),
  362. Ttl: v.Ttl.ToUint32(),
  363. }
  364. for _, location := range s.Locations {
  365. if err := location.UnloadVolume(i); err == nil {
  366. glog.V(0).Infof("UnmountVolume %d", i)
  367. s.DeletedVolumesChan <- message
  368. return nil
  369. }
  370. }
  371. return fmt.Errorf("volume %d not found on disk", i)
  372. }
  373. func (s *Store) DeleteVolume(i needle.VolumeId) error {
  374. v := s.findVolume(i)
  375. if v == nil {
  376. return fmt.Errorf("delete volume %d not found on disk", i)
  377. }
  378. message := master_pb.VolumeShortInformationMessage{
  379. Id: uint32(v.Id),
  380. Collection: v.Collection,
  381. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  382. Version: uint32(v.Version()),
  383. Ttl: v.Ttl.ToUint32(),
  384. }
  385. for _, location := range s.Locations {
  386. if err := location.DeleteVolume(i); err == nil {
  387. glog.V(0).Infof("DeleteVolume %d", i)
  388. s.DeletedVolumesChan <- message
  389. return nil
  390. } else {
  391. glog.Errorf("DeleteVolume %d: %v", i, err)
  392. }
  393. }
  394. return fmt.Errorf("volume %d not found on disk", i)
  395. }
  396. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  397. for _, location := range s.Locations {
  398. fileInfo, found := location.LocateVolume(i)
  399. if !found {
  400. continue
  401. }
  402. // load, modify, save
  403. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  404. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  405. volumeInfo, _, err := pb.MaybeLoadVolumeInfo(vifFile)
  406. if err != nil {
  407. return fmt.Errorf("volume %d fail to load vif", i)
  408. }
  409. volumeInfo.Replication = replication
  410. err = pb.SaveVolumeInfo(vifFile, volumeInfo)
  411. if err != nil {
  412. return fmt.Errorf("volume %d fail to save vif", i)
  413. }
  414. return nil
  415. }
  416. return fmt.Errorf("volume %d not found on disk", i)
  417. }
  418. func (s *Store) SetVolumeSizeLimit(x uint64) {
  419. atomic.StoreUint64(&s.volumeSizeLimit, x)
  420. }
  421. func (s *Store) GetVolumeSizeLimit() uint64 {
  422. return atomic.LoadUint64(&s.volumeSizeLimit)
  423. }
  424. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  425. volumeSizeLimit := s.GetVolumeSizeLimit()
  426. for _, diskLocation := range s.Locations {
  427. if diskLocation.OriginalMaxVolumeCount == 0 {
  428. currentMaxVolumeCount := diskLocation.MaxVolumeCount
  429. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  430. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  431. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  432. volCount := diskLocation.VolumesLen()
  433. maxVolumeCount := volCount
  434. if unclaimedSpaces > int64(volumeSizeLimit) {
  435. maxVolumeCount += int(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  436. }
  437. diskLocation.MaxVolumeCount = maxVolumeCount
  438. glog.V(2).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  439. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  440. hasChanges = hasChanges || currentMaxVolumeCount != diskLocation.MaxVolumeCount
  441. }
  442. }
  443. return
  444. }