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.

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