volume_vacuum.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. package storage
  2. import (
  3. "fmt"
  4. "os"
  5. "runtime"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/stats"
  9. "github.com/chrislusf/seaweedfs/weed/storage/backend"
  10. idx2 "github.com/chrislusf/seaweedfs/weed/storage/idx"
  11. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  12. "github.com/chrislusf/seaweedfs/weed/storage/needle_map"
  13. "github.com/chrislusf/seaweedfs/weed/storage/super_block"
  14. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. type ProgressFunc func(processed int64) bool
  18. func (v *Volume) garbageLevel() float64 {
  19. if v.ContentSize() == 0 {
  20. return 0
  21. }
  22. deletedSize := v.DeletedSize()
  23. fileSize := v.ContentSize()
  24. if v.DeletedCount() > 0 && v.DeletedSize() == 0 {
  25. // this happens for .sdx converted back to normal .idx
  26. // where deleted entry size is missing
  27. datFileSize, _, _ := v.FileStat()
  28. deletedSize = datFileSize - fileSize - super_block.SuperBlockSize
  29. fileSize = datFileSize
  30. }
  31. return float64(deletedSize) / float64(fileSize)
  32. }
  33. // compact a volume based on deletions in .dat files
  34. func (v *Volume) Compact(preallocate int64, compactionBytePerSecond int64) error {
  35. if v.MemoryMapMaxSizeMb != 0 { //it makes no sense to compact in memory
  36. return nil
  37. }
  38. glog.V(3).Infof("Compacting volume %d ...", v.Id)
  39. //no need to lock for copy on write
  40. //v.accessLock.Lock()
  41. //defer v.accessLock.Unlock()
  42. //glog.V(3).Infof("Got Compaction lock...")
  43. v.isCompacting = true
  44. defer func() {
  45. v.isCompacting = false
  46. }()
  47. v.lastCompactIndexOffset = v.IndexFileSize()
  48. v.lastCompactRevision = v.SuperBlock.CompactionRevision
  49. glog.V(3).Infof("creating copies for volume %d ,last offset %d...", v.Id, v.lastCompactIndexOffset)
  50. if err := v.DataBackend.Sync(); err != nil {
  51. glog.V(0).Infof("compact fail to sync volume %d", v.Id)
  52. }
  53. if err := v.nm.Sync(); err != nil {
  54. glog.V(0).Infof("compact fail to sync volume idx %d", v.Id)
  55. }
  56. return v.copyDataAndGenerateIndexFile(v.FileName(".cpd"), v.FileName(".cpx"), preallocate, compactionBytePerSecond)
  57. }
  58. // compact a volume based on deletions in .idx files
  59. func (v *Volume) Compact2(preallocate int64, compactionBytePerSecond int64, progressFn ProgressFunc) error {
  60. if v.MemoryMapMaxSizeMb != 0 { //it makes no sense to compact in memory
  61. return nil
  62. }
  63. glog.V(3).Infof("Compact2 volume %d ...", v.Id)
  64. v.isCompacting = true
  65. defer func() {
  66. v.isCompacting = false
  67. }()
  68. v.lastCompactIndexOffset = v.IndexFileSize()
  69. v.lastCompactRevision = v.SuperBlock.CompactionRevision
  70. glog.V(3).Infof("creating copies for volume %d ...", v.Id)
  71. if err := v.DataBackend.Sync(); err != nil {
  72. glog.V(0).Infof("compact2 fail to sync volume dat %d: %v", v.Id, err)
  73. }
  74. if err := v.nm.Sync(); err != nil {
  75. glog.V(0).Infof("compact2 fail to sync volume idx %d: %v", v.Id, err)
  76. }
  77. return copyDataBasedOnIndexFile(v.FileName(".dat"), v.FileName(".idx"), v.FileName(".cpd"), v.FileName(".cpx"), v.SuperBlock, v.Version(), preallocate, compactionBytePerSecond, progressFn)
  78. }
  79. func (v *Volume) CommitCompact() error {
  80. if v.MemoryMapMaxSizeMb != 0 { //it makes no sense to compact in memory
  81. return nil
  82. }
  83. glog.V(0).Infof("Committing volume %d vacuuming...", v.Id)
  84. v.isCompacting = true
  85. defer func() {
  86. v.isCompacting = false
  87. }()
  88. v.dataFileAccessLock.Lock()
  89. defer v.dataFileAccessLock.Unlock()
  90. glog.V(3).Infof("Got volume %d committing lock...", v.Id)
  91. v.nm.Close()
  92. if v.DataBackend != nil {
  93. if err := v.DataBackend.Close(); err != nil {
  94. glog.V(0).Infof("fail to close volume %d", v.Id)
  95. }
  96. }
  97. v.DataBackend = nil
  98. stats.VolumeServerVolumeCounter.WithLabelValues(v.Collection, "volume").Dec()
  99. var e error
  100. if e = v.makeupDiff(v.FileName(".cpd"), v.FileName(".cpx"), v.FileName(".dat"), v.FileName(".idx")); e != nil {
  101. glog.V(0).Infof("makeupDiff in CommitCompact volume %d failed %v", v.Id, e)
  102. e = os.Remove(v.FileName(".cpd"))
  103. if e != nil {
  104. return e
  105. }
  106. e = os.Remove(v.FileName(".cpx"))
  107. if e != nil {
  108. return e
  109. }
  110. } else {
  111. if runtime.GOOS == "windows" {
  112. e = os.RemoveAll(v.FileName(".dat"))
  113. if e != nil {
  114. return e
  115. }
  116. e = os.RemoveAll(v.FileName(".idx"))
  117. if e != nil {
  118. return e
  119. }
  120. }
  121. var e error
  122. if e = os.Rename(v.FileName(".cpd"), v.FileName(".dat")); e != nil {
  123. return fmt.Errorf("rename %s: %v", v.FileName(".cpd"), e)
  124. }
  125. if e = os.Rename(v.FileName(".cpx"), v.FileName(".idx")); e != nil {
  126. return fmt.Errorf("rename %s: %v", v.FileName(".cpx"), e)
  127. }
  128. }
  129. //glog.V(3).Infof("Pretending to be vacuuming...")
  130. //time.Sleep(20 * time.Second)
  131. os.RemoveAll(v.FileName(".ldb"))
  132. glog.V(3).Infof("Loading volume %d commit file...", v.Id)
  133. if e = v.load(true, false, v.needleMapKind, 0); e != nil {
  134. return e
  135. }
  136. return nil
  137. }
  138. func (v *Volume) cleanupCompact() error {
  139. glog.V(0).Infof("Cleaning up volume %d vacuuming...", v.Id)
  140. e1 := os.Remove(v.FileName(".cpd"))
  141. e2 := os.Remove(v.FileName(".cpx"))
  142. if e1 != nil && !os.IsNotExist(e1) {
  143. return e1
  144. }
  145. if e2 != nil && !os.IsNotExist(e2) {
  146. return e2
  147. }
  148. return nil
  149. }
  150. func fetchCompactRevisionFromDatFile(datBackend backend.BackendStorageFile) (compactRevision uint16, err error) {
  151. superBlock, err := super_block.ReadSuperBlock(datBackend)
  152. if err != nil {
  153. return 0, err
  154. }
  155. return superBlock.CompactionRevision, nil
  156. }
  157. // if old .dat and .idx files are updated, this func tries to apply the same changes to new files accordingly
  158. func (v *Volume) makeupDiff(newDatFileName, newIdxFileName, oldDatFileName, oldIdxFileName string) (err error) {
  159. var indexSize int64
  160. oldIdxFile, err := os.Open(oldIdxFileName)
  161. if err != nil {
  162. return fmt.Errorf("makeupDiff open %s failed: %v", oldIdxFileName, err)
  163. }
  164. defer oldIdxFile.Close()
  165. oldDatFile, err := os.Open(oldDatFileName)
  166. if err != nil {
  167. return fmt.Errorf("makeupDiff open %s failed: %v", oldDatFileName, err)
  168. }
  169. oldDatBackend := backend.NewDiskFile(oldDatFile)
  170. defer oldDatBackend.Close()
  171. // skip if the old .idx file has not changed
  172. if indexSize, err = verifyIndexFileIntegrity(oldIdxFile); err != nil {
  173. return fmt.Errorf("verifyIndexFileIntegrity %s failed: %v", oldIdxFileName, err)
  174. }
  175. if indexSize == 0 || uint64(indexSize) <= v.lastCompactIndexOffset {
  176. return nil
  177. }
  178. // fail if the old .dat file has changed to a new revision
  179. oldDatCompactRevision, err := fetchCompactRevisionFromDatFile(oldDatBackend)
  180. if err != nil {
  181. return fmt.Errorf("fetchCompactRevisionFromDatFile src %s failed: %v", oldDatFile.Name(), err)
  182. }
  183. if oldDatCompactRevision != v.lastCompactRevision {
  184. return fmt.Errorf("current old dat file's compact revision %d is not the expected one %d", oldDatCompactRevision, v.lastCompactRevision)
  185. }
  186. type keyField struct {
  187. offset Offset
  188. size Size
  189. }
  190. incrementedHasUpdatedIndexEntry := make(map[NeedleId]keyField)
  191. for idxOffset := indexSize - NeedleMapEntrySize; uint64(idxOffset) >= v.lastCompactIndexOffset; idxOffset -= NeedleMapEntrySize {
  192. var IdxEntry []byte
  193. if IdxEntry, err = readIndexEntryAtOffset(oldIdxFile, idxOffset); err != nil {
  194. return fmt.Errorf("readIndexEntry %s at offset %d failed: %v", oldIdxFileName, idxOffset, err)
  195. }
  196. key, offset, size := idx2.IdxFileEntry(IdxEntry)
  197. glog.V(4).Infof("key %d offset %d size %d", key, offset, size)
  198. if _, found := incrementedHasUpdatedIndexEntry[key]; !found {
  199. incrementedHasUpdatedIndexEntry[key] = keyField{
  200. offset: offset,
  201. size: size,
  202. }
  203. }
  204. }
  205. // no updates during commit step
  206. if len(incrementedHasUpdatedIndexEntry) == 0 {
  207. return nil
  208. }
  209. // deal with updates during commit step
  210. var (
  211. dst, idx *os.File
  212. )
  213. if dst, err = os.OpenFile(newDatFileName, os.O_RDWR, 0644); err != nil {
  214. return fmt.Errorf("open dat file %s failed: %v", newDatFileName, err)
  215. }
  216. dstDatBackend := backend.NewDiskFile(dst)
  217. defer dstDatBackend.Close()
  218. if idx, err = os.OpenFile(newIdxFileName, os.O_RDWR, 0644); err != nil {
  219. return fmt.Errorf("open idx file %s failed: %v", newIdxFileName, err)
  220. }
  221. defer idx.Close()
  222. var newDatCompactRevision uint16
  223. newDatCompactRevision, err = fetchCompactRevisionFromDatFile(dstDatBackend)
  224. if err != nil {
  225. return fmt.Errorf("fetchCompactRevisionFromDatFile dst %s failed: %v", dst.Name(), err)
  226. }
  227. if oldDatCompactRevision+1 != newDatCompactRevision {
  228. return fmt.Errorf("oldDatFile %s 's compact revision is %d while newDatFile %s 's compact revision is %d", oldDatFileName, oldDatCompactRevision, newDatFileName, newDatCompactRevision)
  229. }
  230. for key, increIdxEntry := range incrementedHasUpdatedIndexEntry {
  231. idxEntryBytes := needle_map.ToBytes(key, increIdxEntry.offset, increIdxEntry.size)
  232. var offset int64
  233. if offset, err = dst.Seek(0, 2); err != nil {
  234. glog.V(0).Infof("failed to seek the end of file: %v", err)
  235. return
  236. }
  237. //ensure file writing starting from aligned positions
  238. if offset%NeedlePaddingSize != 0 {
  239. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  240. if offset, err = dst.Seek(offset, 0); err != nil {
  241. glog.V(0).Infof("failed to align in datafile %s: %v", dst.Name(), err)
  242. return
  243. }
  244. }
  245. //updated needle
  246. if !increIdxEntry.offset.IsZero() && increIdxEntry.size != 0 && increIdxEntry.size.IsValid() {
  247. //even the needle cache in memory is hit, the need_bytes is correct
  248. glog.V(4).Infof("file %d offset %d size %d", key, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size)
  249. var needleBytes []byte
  250. needleBytes, err = needle.ReadNeedleBlob(oldDatBackend, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size, v.Version())
  251. if err != nil {
  252. return fmt.Errorf("ReadNeedleBlob %s key %d offset %d size %d failed: %v", oldDatFile.Name(), key, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size, err)
  253. }
  254. dstDatBackend.Write(needleBytes)
  255. util.Uint32toBytes(idxEntryBytes[8:12], uint32(offset/NeedlePaddingSize))
  256. } else { //deleted needle
  257. //fakeDelNeedle 's default Data field is nil
  258. fakeDelNeedle := new(needle.Needle)
  259. fakeDelNeedle.Id = key
  260. fakeDelNeedle.Cookie = 0x12345678
  261. fakeDelNeedle.AppendAtNs = uint64(time.Now().UnixNano())
  262. _, _, _, err = fakeDelNeedle.Append(dstDatBackend, v.Version())
  263. if err != nil {
  264. return fmt.Errorf("append deleted %d failed: %v", key, err)
  265. }
  266. util.Uint32toBytes(idxEntryBytes[8:12], uint32(0))
  267. }
  268. if _, err := idx.Seek(0, 2); err != nil {
  269. return fmt.Errorf("cannot seek end of indexfile %s: %v",
  270. newIdxFileName, err)
  271. }
  272. _, err = idx.Write(idxEntryBytes)
  273. }
  274. return nil
  275. }
  276. type VolumeFileScanner4Vacuum struct {
  277. version needle.Version
  278. v *Volume
  279. dstBackend backend.BackendStorageFile
  280. nm *needle_map.MemDb
  281. newOffset int64
  282. now uint64
  283. writeThrottler *util.WriteThrottler
  284. }
  285. func (scanner *VolumeFileScanner4Vacuum) VisitSuperBlock(superBlock super_block.SuperBlock) error {
  286. scanner.version = superBlock.Version
  287. superBlock.CompactionRevision++
  288. _, err := scanner.dstBackend.WriteAt(superBlock.Bytes(), 0)
  289. scanner.newOffset = int64(superBlock.BlockSize())
  290. return err
  291. }
  292. func (scanner *VolumeFileScanner4Vacuum) ReadNeedleBody() bool {
  293. return true
  294. }
  295. func (scanner *VolumeFileScanner4Vacuum) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
  296. if n.HasTtl() && scanner.now >= n.LastModified+uint64(scanner.v.Ttl.Minutes()*60) {
  297. return nil
  298. }
  299. nv, ok := scanner.v.nm.Get(n.Id)
  300. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  301. if ok && nv.Offset.ToActualOffset() == offset && nv.Size > 0 && nv.Size.IsValid() {
  302. if err := scanner.nm.Set(n.Id, ToOffset(scanner.newOffset), n.Size); err != nil {
  303. return fmt.Errorf("cannot put needle: %s", err)
  304. }
  305. if _, _, _, err := n.Append(scanner.dstBackend, scanner.v.Version()); err != nil {
  306. return fmt.Errorf("cannot append needle: %s", err)
  307. }
  308. delta := n.DiskSize(scanner.version)
  309. scanner.newOffset += delta
  310. scanner.writeThrottler.MaybeSlowdown(delta)
  311. glog.V(4).Infoln("saving key", n.Id, "volume offset", offset, "=>", scanner.newOffset, "data_size", n.Size)
  312. }
  313. return nil
  314. }
  315. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, preallocate int64, compactionBytePerSecond int64) (err error) {
  316. var (
  317. dst backend.BackendStorageFile
  318. )
  319. if dst, err = backend.CreateVolumeFile(dstName, preallocate, 0); err != nil {
  320. return
  321. }
  322. defer dst.Close()
  323. nm := needle_map.NewMemDb()
  324. defer nm.Close()
  325. scanner := &VolumeFileScanner4Vacuum{
  326. v: v,
  327. now: uint64(time.Now().Unix()),
  328. nm: nm,
  329. dstBackend: dst,
  330. writeThrottler: util.NewWriteThrottler(compactionBytePerSecond),
  331. }
  332. err = ScanVolumeFile(v.dir, v.Collection, v.Id, v.needleMapKind, scanner)
  333. if err != nil {
  334. return nil
  335. }
  336. err = nm.SaveToIdx(idxName)
  337. return
  338. }
  339. func copyDataBasedOnIndexFile(srcDatName, srcIdxName, dstDatName, datIdxName string, sb super_block.SuperBlock, version needle.Version, preallocate, compactionBytePerSecond int64, progressFn ProgressFunc) (err error) {
  340. var (
  341. srcDatBackend, dstDatBackend backend.BackendStorageFile
  342. dataFile *os.File
  343. )
  344. if dstDatBackend, err = backend.CreateVolumeFile(dstDatName, preallocate, 0); err != nil {
  345. return
  346. }
  347. defer dstDatBackend.Close()
  348. oldNm := needle_map.NewMemDb()
  349. defer oldNm.Close()
  350. newNm := needle_map.NewMemDb()
  351. defer newNm.Close()
  352. if err = oldNm.LoadFromIdx(srcIdxName); err != nil {
  353. return
  354. }
  355. if dataFile, err = os.Open(srcDatName); err != nil {
  356. return err
  357. }
  358. srcDatBackend = backend.NewDiskFile(dataFile)
  359. defer srcDatBackend.Close()
  360. now := uint64(time.Now().Unix())
  361. sb.CompactionRevision++
  362. dstDatBackend.WriteAt(sb.Bytes(), 0)
  363. newOffset := int64(sb.BlockSize())
  364. writeThrottler := util.NewWriteThrottler(compactionBytePerSecond)
  365. oldNm.AscendingVisit(func(value needle_map.NeedleValue) error {
  366. offset, size := value.Offset, value.Size
  367. if offset.IsZero() || size.IsDeleted() {
  368. return nil
  369. }
  370. if progressFn != nil {
  371. if !progressFn(offset.ToActualOffset()) {
  372. return fmt.Errorf("interrupted")
  373. }
  374. }
  375. n := new(needle.Needle)
  376. err := n.ReadData(srcDatBackend, offset.ToActualOffset(), size, version)
  377. if err != nil {
  378. return nil
  379. }
  380. if n.HasTtl() && now >= n.LastModified+uint64(sb.Ttl.Minutes()*60) {
  381. return nil
  382. }
  383. if err = newNm.Set(n.Id, ToOffset(newOffset), n.Size); err != nil {
  384. return fmt.Errorf("cannot put needle: %s", err)
  385. }
  386. if _, _, _, err = n.Append(dstDatBackend, sb.Version); err != nil {
  387. return fmt.Errorf("cannot append needle: %s", err)
  388. }
  389. delta := n.DiskSize(version)
  390. newOffset += delta
  391. writeThrottler.MaybeSlowdown(delta)
  392. glog.V(4).Infoln("saving key", n.Id, "volume offset", offset, "=>", newOffset, "data_size", n.Size)
  393. return nil
  394. })
  395. newNm.SaveToIdx(datIdxName)
  396. return
  397. }