volume.go 10 KB

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