You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

532 lines
16 KiB

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