volume.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. package storage
  2. import (
  3. "fmt"
  4. "path"
  5. "strconv"
  6. "sync"
  7. "time"
  8. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  9. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  10. "github.com/seaweedfs/seaweedfs/weed/stats"
  11. "github.com/seaweedfs/seaweedfs/weed/storage/backend"
  12. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  13. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  14. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  15. "github.com/seaweedfs/seaweedfs/weed/glog"
  16. )
  17. type Volume struct {
  18. Id needle.VolumeId
  19. dir string
  20. dirIdx string
  21. Collection string
  22. DataBackend backend.BackendStorageFile
  23. nm NeedleMapper
  24. tmpNm TempNeedleMapper
  25. needleMapKind NeedleMapKind
  26. noWriteOrDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
  27. noWriteCanDelete bool // if readonly, either noWriteOrDelete or noWriteCanDelete
  28. noWriteLock sync.RWMutex
  29. hasRemoteFile bool // if the volume has a remote file
  30. MemoryMapMaxSizeMb uint32
  31. super_block.SuperBlock
  32. dataFileAccessLock sync.RWMutex
  33. superBlockAccessLock sync.Mutex
  34. asyncRequestsChan chan *needle.AsyncRequest
  35. lastModifiedTsSeconds uint64 // unix time in seconds
  36. lastAppendAtNs uint64 // unix time in nanoseconds
  37. lastCompactIndexOffset uint64
  38. lastCompactRevision uint16
  39. ldbTimeout int64
  40. isCompacting bool
  41. isCommitCompacting bool
  42. volumeInfo *volume_server_pb.VolumeInfo
  43. location *DiskLocation
  44. lastIoError error
  45. }
  46. func NewVolume(dirname string, dirIdx string, collection string, id needle.VolumeId, needleMapKind NeedleMapKind, replicaPlacement *super_block.ReplicaPlacement, ttl *needle.TTL, preallocate int64, memoryMapMaxSizeMb uint32, ldbTimeout int64) (v *Volume, e error) {
  47. // if replicaPlacement is nil, the superblock will be loaded from disk
  48. v = &Volume{dir: dirname, dirIdx: dirIdx, Collection: collection, Id: id, MemoryMapMaxSizeMb: memoryMapMaxSizeMb,
  49. asyncRequestsChan: make(chan *needle.AsyncRequest, 128)}
  50. v.SuperBlock = super_block.SuperBlock{ReplicaPlacement: replicaPlacement, Ttl: ttl}
  51. v.needleMapKind = needleMapKind
  52. v.ldbTimeout = ldbTimeout
  53. e = v.load(true, true, needleMapKind, preallocate)
  54. v.startWorker()
  55. return
  56. }
  57. func (v *Volume) String() string {
  58. v.noWriteLock.RLock()
  59. defer v.noWriteLock.RUnlock()
  60. return fmt.Sprintf("Id:%v dir:%s dirIdx:%s Collection:%s dataFile:%v nm:%v noWrite:%v canDelete:%v", v.Id, v.dir, v.dirIdx, v.Collection, v.DataBackend, v.nm, v.noWriteOrDelete || v.noWriteCanDelete, v.noWriteCanDelete)
  61. }
  62. func VolumeFileName(dir string, collection string, id int) (fileName string) {
  63. idString := strconv.Itoa(id)
  64. if collection == "" {
  65. fileName = path.Join(dir, idString)
  66. } else {
  67. fileName = path.Join(dir, collection+"_"+idString)
  68. }
  69. return
  70. }
  71. func (v *Volume) DataFileName() (fileName string) {
  72. return VolumeFileName(v.dir, v.Collection, int(v.Id))
  73. }
  74. func (v *Volume) IndexFileName() (fileName string) {
  75. return VolumeFileName(v.dirIdx, v.Collection, int(v.Id))
  76. }
  77. func (v *Volume) FileName(ext string) (fileName string) {
  78. switch ext {
  79. case ".idx", ".cpx", ".ldb":
  80. return VolumeFileName(v.dirIdx, v.Collection, int(v.Id)) + ext
  81. }
  82. // .dat, .cpd, .vif
  83. return VolumeFileName(v.dir, v.Collection, int(v.Id)) + ext
  84. }
  85. func (v *Volume) Version() needle.Version {
  86. v.superBlockAccessLock.Lock()
  87. defer v.superBlockAccessLock.Unlock()
  88. if v.volumeInfo.Version != 0 {
  89. v.SuperBlock.Version = needle.Version(v.volumeInfo.Version)
  90. }
  91. return v.SuperBlock.Version
  92. }
  93. func (v *Volume) FileStat() (datSize uint64, idxSize uint64, modTime time.Time) {
  94. v.dataFileAccessLock.RLock()
  95. defer v.dataFileAccessLock.RUnlock()
  96. if v.DataBackend == nil {
  97. return
  98. }
  99. datFileSize, modTime, e := v.DataBackend.GetStat()
  100. if e == nil {
  101. return uint64(datFileSize), v.nm.IndexFileSize(), modTime
  102. }
  103. glog.V(0).Infof("Failed to read file size %s %v", v.DataBackend.Name(), e)
  104. return // -1 causes integer overflow and the volume to become unwritable.
  105. }
  106. func (v *Volume) ContentSize() uint64 {
  107. v.dataFileAccessLock.RLock()
  108. defer v.dataFileAccessLock.RUnlock()
  109. if v.nm == nil {
  110. return 0
  111. }
  112. return v.nm.ContentSize()
  113. }
  114. func (v *Volume) DeletedSize() uint64 {
  115. v.dataFileAccessLock.RLock()
  116. defer v.dataFileAccessLock.RUnlock()
  117. if v.nm == nil {
  118. return 0
  119. }
  120. return v.nm.DeletedSize()
  121. }
  122. func (v *Volume) FileCount() uint64 {
  123. v.dataFileAccessLock.RLock()
  124. defer v.dataFileAccessLock.RUnlock()
  125. if v.nm == nil {
  126. return 0
  127. }
  128. return uint64(v.nm.FileCount())
  129. }
  130. func (v *Volume) DeletedCount() uint64 {
  131. v.dataFileAccessLock.RLock()
  132. defer v.dataFileAccessLock.RUnlock()
  133. if v.nm == nil {
  134. return 0
  135. }
  136. return uint64(v.nm.DeletedCount())
  137. }
  138. func (v *Volume) MaxFileKey() types.NeedleId {
  139. v.dataFileAccessLock.RLock()
  140. defer v.dataFileAccessLock.RUnlock()
  141. if v.nm == nil {
  142. return 0
  143. }
  144. return v.nm.MaxFileKey()
  145. }
  146. func (v *Volume) IndexFileSize() uint64 {
  147. v.dataFileAccessLock.RLock()
  148. defer v.dataFileAccessLock.RUnlock()
  149. if v.nm == nil {
  150. return 0
  151. }
  152. return v.nm.IndexFileSize()
  153. }
  154. func (v *Volume) DiskType() types.DiskType {
  155. return v.location.DiskType
  156. }
  157. func (v *Volume) SyncToDisk() {
  158. v.dataFileAccessLock.Lock()
  159. defer v.dataFileAccessLock.Unlock()
  160. if v.nm != nil {
  161. if err := v.nm.Sync(); err != nil {
  162. glog.Warningf("Volume Close fail to sync volume idx %d", v.Id)
  163. }
  164. }
  165. if v.DataBackend != nil {
  166. if err := v.DataBackend.Sync(); err != nil {
  167. glog.Warningf("Volume Close fail to sync volume %d", v.Id)
  168. }
  169. }
  170. }
  171. // Close cleanly shuts down this volume
  172. func (v *Volume) Close() {
  173. v.dataFileAccessLock.Lock()
  174. defer v.dataFileAccessLock.Unlock()
  175. for v.isCommitCompacting {
  176. time.Sleep(521 * time.Millisecond)
  177. glog.Warningf("Volume Close wait for compaction %d", v.Id)
  178. }
  179. if v.nm != nil {
  180. if err := v.nm.Sync(); err != nil {
  181. glog.Warningf("Volume Close fail to sync volume idx %d", v.Id)
  182. }
  183. v.nm.Close()
  184. v.nm = nil
  185. }
  186. if v.DataBackend != nil {
  187. if err := v.DataBackend.Close(); err != nil {
  188. glog.Warningf("Volume Close fail to sync volume %d", v.Id)
  189. }
  190. v.DataBackend = nil
  191. stats.VolumeServerVolumeCounter.WithLabelValues(v.Collection, "volume").Dec()
  192. }
  193. }
  194. func (v *Volume) NeedToReplicate() bool {
  195. return v.ReplicaPlacement.GetCopyCount() > 1
  196. }
  197. // volume is expired if modified time + volume ttl < now
  198. // except when volume is empty
  199. // or when the volume does not have a ttl
  200. // or when volumeSizeLimit is 0 when server just starts
  201. func (v *Volume) expired(contentSize uint64, volumeSizeLimit uint64) bool {
  202. if volumeSizeLimit == 0 {
  203. // skip if we don't know size limit
  204. return false
  205. }
  206. if contentSize <= super_block.SuperBlockSize {
  207. return false
  208. }
  209. if v.Ttl == nil || v.Ttl.Minutes() == 0 {
  210. return false
  211. }
  212. glog.V(2).Infof("volume %d now:%v lastModified:%v", v.Id, time.Now().Unix(), v.lastModifiedTsSeconds)
  213. livedMinutes := (time.Now().Unix() - int64(v.lastModifiedTsSeconds)) / 60
  214. glog.V(2).Infof("volume %d ttl:%v lived:%v", v.Id, v.Ttl, livedMinutes)
  215. if int64(v.Ttl.Minutes()) < livedMinutes {
  216. return true
  217. }
  218. return false
  219. }
  220. // wait either maxDelayMinutes or 10% of ttl minutes
  221. func (v *Volume) expiredLongEnough(maxDelayMinutes uint32) bool {
  222. if v.Ttl == nil || v.Ttl.Minutes() == 0 {
  223. return false
  224. }
  225. removalDelay := v.Ttl.Minutes() / 10
  226. if removalDelay > maxDelayMinutes {
  227. removalDelay = maxDelayMinutes
  228. }
  229. if uint64(v.Ttl.Minutes()+removalDelay)*60+v.lastModifiedTsSeconds < uint64(time.Now().Unix()) {
  230. return true
  231. }
  232. return false
  233. }
  234. func (v *Volume) collectStatus() (maxFileKey types.NeedleId, datFileSize int64, modTime time.Time, fileCount, deletedCount, deletedSize uint64, ok bool) {
  235. v.dataFileAccessLock.RLock()
  236. defer v.dataFileAccessLock.RUnlock()
  237. glog.V(4).Infof("collectStatus volume %d", v.Id)
  238. if v.nm == nil || v.DataBackend == nil {
  239. return
  240. }
  241. ok = true
  242. maxFileKey = v.nm.MaxFileKey()
  243. datFileSize, modTime, _ = v.DataBackend.GetStat()
  244. fileCount = uint64(v.nm.FileCount())
  245. deletedCount = uint64(v.nm.DeletedCount())
  246. deletedSize = v.nm.DeletedSize()
  247. fileCount = uint64(v.nm.FileCount())
  248. return
  249. }
  250. func (v *Volume) ToVolumeInformationMessage() (types.NeedleId, *master_pb.VolumeInformationMessage) {
  251. maxFileKey, volumeSize, modTime, fileCount, deletedCount, deletedSize, ok := v.collectStatus()
  252. if !ok {
  253. return 0, nil
  254. }
  255. volumeInfo := &master_pb.VolumeInformationMessage{
  256. Id: uint32(v.Id),
  257. Size: uint64(volumeSize),
  258. Collection: v.Collection,
  259. FileCount: fileCount,
  260. DeleteCount: deletedCount,
  261. DeletedByteCount: deletedSize,
  262. ReadOnly: v.IsReadOnly(),
  263. ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
  264. Version: uint32(v.Version()),
  265. Ttl: v.Ttl.ToUint32(),
  266. CompactRevision: uint32(v.SuperBlock.CompactionRevision),
  267. ModifiedAtSecond: modTime.Unix(),
  268. DiskType: string(v.location.DiskType),
  269. }
  270. volumeInfo.RemoteStorageName, volumeInfo.RemoteStorageKey = v.RemoteStorageNameKey()
  271. return maxFileKey, volumeInfo
  272. }
  273. func (v *Volume) RemoteStorageNameKey() (storageName, storageKey string) {
  274. if v.volumeInfo == nil {
  275. return
  276. }
  277. if len(v.volumeInfo.GetFiles()) == 0 {
  278. return
  279. }
  280. return v.volumeInfo.GetFiles()[0].BackendName(), v.volumeInfo.GetFiles()[0].GetKey()
  281. }
  282. func (v *Volume) IsReadOnly() bool {
  283. v.noWriteLock.RLock()
  284. defer v.noWriteLock.RUnlock()
  285. return v.noWriteOrDelete || v.noWriteCanDelete || v.location.isDiskSpaceLow
  286. }