store.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. package storage
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/pb"
  5. "github.com/chrislusf/seaweedfs/weed/storage/volume_info"
  6. "github.com/chrislusf/seaweedfs/weed/util"
  7. "path/filepath"
  8. "strings"
  9. "sync/atomic"
  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. for col, size := range collectionVolumeSize {
  278. stats.VolumeServerDiskSizeGauge.WithLabelValues(col, "normal").Set(float64(size))
  279. }
  280. for col, types := range collectionVolumeReadOnlyCount {
  281. for t, count := range types {
  282. stats.VolumeServerReadOnlyVolumeGauge.WithLabelValues(col, t).Set(float64(count))
  283. }
  284. }
  285. return &master_pb.Heartbeat{
  286. Ip: s.Ip,
  287. Port: uint32(s.Port),
  288. GrpcPort: uint32(s.GrpcPort),
  289. PublicUrl: s.PublicUrl,
  290. MaxVolumeCounts: maxVolumeCounts,
  291. MaxFileKey: NeedleIdToUint64(maxFileKey),
  292. DataCenter: s.dataCenter,
  293. Rack: s.rack,
  294. Volumes: volumeMessages,
  295. HasNoVolumes: len(volumeMessages) == 0,
  296. }
  297. }
  298. func (s *Store) SetStopping() {
  299. s.isStopping = true
  300. }
  301. func (s *Store) Close() {
  302. for _, location := range s.Locations {
  303. location.Close()
  304. }
  305. }
  306. func (s *Store) WriteVolumeNeedle(i needle.VolumeId, n *needle.Needle, checkCookie bool, fsync bool) (isUnchanged bool, err error) {
  307. if v := s.findVolume(i); v != nil {
  308. if v.IsReadOnly() {
  309. err = fmt.Errorf("volume %d is read only", i)
  310. return
  311. }
  312. _, _, isUnchanged, err = v.writeNeedle2(n, checkCookie, fsync && s.isStopping)
  313. return
  314. }
  315. glog.V(0).Infoln("volume", i, "not found!")
  316. err = fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  317. return
  318. }
  319. func (s *Store) DeleteVolumeNeedle(i needle.VolumeId, n *needle.Needle) (Size, error) {
  320. if v := s.findVolume(i); v != nil {
  321. if v.noWriteOrDelete {
  322. return 0, fmt.Errorf("volume %d is read only", i)
  323. }
  324. return v.deleteNeedle2(n)
  325. }
  326. return 0, fmt.Errorf("volume %d not found on %s:%d", i, s.Ip, s.Port)
  327. }
  328. func (s *Store) ReadVolumeNeedle(i needle.VolumeId, n *needle.Needle, readOption *ReadOption, onReadSizeFn func(size Size)) (int, error) {
  329. if v := s.findVolume(i); v != nil {
  330. return v.readNeedle(n, readOption, onReadSizeFn)
  331. }
  332. return 0, fmt.Errorf("volume %d not found", i)
  333. }
  334. func (s *Store) GetVolume(i needle.VolumeId) *Volume {
  335. return s.findVolume(i)
  336. }
  337. func (s *Store) HasVolume(i needle.VolumeId) bool {
  338. v := s.findVolume(i)
  339. return v != nil
  340. }
  341. func (s *Store) MarkVolumeReadonly(i needle.VolumeId) error {
  342. v := s.findVolume(i)
  343. if v == nil {
  344. return fmt.Errorf("volume %d not found", i)
  345. }
  346. v.noWriteLock.Lock()
  347. v.noWriteOrDelete = true
  348. v.noWriteLock.Unlock()
  349. return nil
  350. }
  351. func (s *Store) MarkVolumeWritable(i needle.VolumeId) error {
  352. v := s.findVolume(i)
  353. if v == nil {
  354. return fmt.Errorf("volume %d not found", i)
  355. }
  356. v.noWriteLock.Lock()
  357. v.noWriteOrDelete = false
  358. v.noWriteLock.Unlock()
  359. return nil
  360. }
  361. func (s *Store) MountVolume(i needle.VolumeId) error {
  362. for _, location := range s.Locations {
  363. if found := location.LoadVolume(i, s.NeedleMapKind); found == true {
  364. glog.V(0).Infof("mount volume %d", i)
  365. v := s.findVolume(i)
  366. s.NewVolumesChan <- master_pb.VolumeShortInformationMessage{
  367. Id: uint32(v.Id),
  368. Collection: v.Collection,
  369. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  370. Version: uint32(v.Version()),
  371. Ttl: v.Ttl.ToUint32(),
  372. DiskType: string(v.location.DiskType),
  373. }
  374. return nil
  375. }
  376. }
  377. return fmt.Errorf("volume %d not found on disk", i)
  378. }
  379. func (s *Store) UnmountVolume(i needle.VolumeId) error {
  380. v := s.findVolume(i)
  381. if v == nil {
  382. return nil
  383. }
  384. message := master_pb.VolumeShortInformationMessage{
  385. Id: uint32(v.Id),
  386. Collection: v.Collection,
  387. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  388. Version: uint32(v.Version()),
  389. Ttl: v.Ttl.ToUint32(),
  390. DiskType: string(v.location.DiskType),
  391. }
  392. for _, location := range s.Locations {
  393. if err := location.UnloadVolume(i); err == nil || err == ErrVolumeNotFound {
  394. glog.V(0).Infof("UnmountVolume %d", i)
  395. s.DeletedVolumesChan <- message
  396. return nil
  397. }
  398. }
  399. return fmt.Errorf("volume %d not found on disk", i)
  400. }
  401. func (s *Store) DeleteVolume(i needle.VolumeId) error {
  402. v := s.findVolume(i)
  403. if v == nil {
  404. return fmt.Errorf("delete volume %d not found on disk", i)
  405. }
  406. message := master_pb.VolumeShortInformationMessage{
  407. Id: uint32(v.Id),
  408. Collection: v.Collection,
  409. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  410. Version: uint32(v.Version()),
  411. Ttl: v.Ttl.ToUint32(),
  412. DiskType: string(v.location.DiskType),
  413. }
  414. for _, location := range s.Locations {
  415. if err := location.DeleteVolume(i); err == nil || err == ErrVolumeNotFound {
  416. glog.V(0).Infof("DeleteVolume %d", i)
  417. s.DeletedVolumesChan <- message
  418. return nil
  419. } else {
  420. glog.Errorf("DeleteVolume %d: %v", i, err)
  421. }
  422. }
  423. return fmt.Errorf("volume %d not found on disk", i)
  424. }
  425. func (s *Store) ConfigureVolume(i needle.VolumeId, replication string) error {
  426. for _, location := range s.Locations {
  427. fileInfo, found := location.LocateVolume(i)
  428. if !found {
  429. continue
  430. }
  431. // load, modify, save
  432. baseFileName := strings.TrimSuffix(fileInfo.Name(), filepath.Ext(fileInfo.Name()))
  433. vifFile := filepath.Join(location.Directory, baseFileName+".vif")
  434. volumeInfo, _, _, err := volume_info.MaybeLoadVolumeInfo(vifFile)
  435. if err != nil {
  436. return fmt.Errorf("volume %d fail to load vif", i)
  437. }
  438. volumeInfo.Replication = replication
  439. err = volume_info.SaveVolumeInfo(vifFile, volumeInfo)
  440. if err != nil {
  441. return fmt.Errorf("volume %d fail to save vif", i)
  442. }
  443. return nil
  444. }
  445. return fmt.Errorf("volume %d not found on disk", i)
  446. }
  447. func (s *Store) SetVolumeSizeLimit(x uint64) {
  448. atomic.StoreUint64(&s.volumeSizeLimit, x)
  449. }
  450. func (s *Store) GetVolumeSizeLimit() uint64 {
  451. return atomic.LoadUint64(&s.volumeSizeLimit)
  452. }
  453. func (s *Store) MaybeAdjustVolumeMax() (hasChanges bool) {
  454. volumeSizeLimit := s.GetVolumeSizeLimit()
  455. if volumeSizeLimit == 0 {
  456. return
  457. }
  458. for _, diskLocation := range s.Locations {
  459. if diskLocation.OriginalMaxVolumeCount == 0 {
  460. currentMaxVolumeCount := diskLocation.MaxVolumeCount
  461. diskStatus := stats.NewDiskStatus(diskLocation.Directory)
  462. unusedSpace := diskLocation.UnUsedSpace(volumeSizeLimit)
  463. unclaimedSpaces := int64(diskStatus.Free) - int64(unusedSpace)
  464. volCount := diskLocation.VolumesLen()
  465. maxVolumeCount := volCount
  466. if unclaimedSpaces > int64(volumeSizeLimit) {
  467. maxVolumeCount += int(uint64(unclaimedSpaces)/volumeSizeLimit) - 1
  468. }
  469. diskLocation.MaxVolumeCount = maxVolumeCount
  470. glog.V(2).Infof("disk %s max %d unclaimedSpace:%dMB, unused:%dMB volumeSizeLimit:%dMB",
  471. diskLocation.Directory, maxVolumeCount, unclaimedSpaces/1024/1024, unusedSpace/1024/1024, volumeSizeLimit/1024/1024)
  472. hasChanges = hasChanges || currentMaxVolumeCount != diskLocation.MaxVolumeCount
  473. }
  474. }
  475. return
  476. }