volume_vacuum.go 14 KB

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