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.

476 lines
15 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 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
6 years ago
4 years ago
4 years ago
6 years ago
4 years ago
6 years ago
8 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/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. cpdFile := v.FileName(".cpd")
  123. if _, err := os.Stat(cpdFile); err == nil {
  124. if e = os.Rename(cpdFile, v.FileName(".dat")); e != nil {
  125. return fmt.Errorf("rename %s: %v", v.FileName(".cpd"), e)
  126. }
  127. }
  128. cpxFile := v.FileName(".cpx")
  129. if _, err := os.Stat(cpdFile); err == nil {
  130. if e = os.Rename(cpxFile, v.FileName(".idx")); e != nil {
  131. return fmt.Errorf("rename %s: %v", v.FileName(".cpx"), e)
  132. }
  133. }
  134. }
  135. //glog.V(3).Infof("Pretending to be vacuuming...")
  136. //time.Sleep(20 * time.Second)
  137. os.RemoveAll(v.FileName(".ldb"))
  138. glog.V(3).Infof("Loading volume %d commit file...", v.Id)
  139. if e = v.load(true, false, v.needleMapKind, 0); e != nil {
  140. return e
  141. }
  142. return nil
  143. }
  144. func (v *Volume) cleanupCompact() error {
  145. glog.V(0).Infof("Cleaning up volume %d vacuuming...", v.Id)
  146. e1 := os.Remove(v.FileName(".cpd"))
  147. e2 := os.Remove(v.FileName(".cpx"))
  148. if e1 != nil && !os.IsNotExist(e1) {
  149. return e1
  150. }
  151. if e2 != nil && !os.IsNotExist(e2) {
  152. return e2
  153. }
  154. return nil
  155. }
  156. func fetchCompactRevisionFromDatFile(datBackend backend.BackendStorageFile) (compactRevision uint16, err error) {
  157. superBlock, err := super_block.ReadSuperBlock(datBackend)
  158. if err != nil {
  159. return 0, err
  160. }
  161. return superBlock.CompactionRevision, nil
  162. }
  163. // if old .dat and .idx files are updated, this func tries to apply the same changes to new files accordingly
  164. func (v *Volume) makeupDiff(newDatFileName, newIdxFileName, oldDatFileName, oldIdxFileName string) (err error) {
  165. var indexSize int64
  166. oldIdxFile, err := os.Open(oldIdxFileName)
  167. if err != nil {
  168. return fmt.Errorf("makeupDiff open %s failed: %v", oldIdxFileName, err)
  169. }
  170. defer oldIdxFile.Close()
  171. oldDatFile, err := os.Open(oldDatFileName)
  172. if err != nil {
  173. return fmt.Errorf("makeupDiff open %s failed: %v", oldDatFileName, err)
  174. }
  175. oldDatBackend := backend.NewDiskFile(oldDatFile)
  176. defer oldDatBackend.Close()
  177. // skip if the old .idx file has not changed
  178. if indexSize, err = verifyIndexFileIntegrity(oldIdxFile); err != nil {
  179. return fmt.Errorf("verifyIndexFileIntegrity %s failed: %v", oldIdxFileName, err)
  180. }
  181. if indexSize == 0 || uint64(indexSize) <= v.lastCompactIndexOffset {
  182. return nil
  183. }
  184. // fail if the old .dat file has changed to a new revision
  185. oldDatCompactRevision, err := fetchCompactRevisionFromDatFile(oldDatBackend)
  186. if err != nil {
  187. return fmt.Errorf("fetchCompactRevisionFromDatFile src %s failed: %v", oldDatFile.Name(), err)
  188. }
  189. if oldDatCompactRevision != v.lastCompactRevision {
  190. return fmt.Errorf("current old dat file's compact revision %d is not the expected one %d", oldDatCompactRevision, v.lastCompactRevision)
  191. }
  192. type keyField struct {
  193. offset Offset
  194. size Size
  195. }
  196. incrementedHasUpdatedIndexEntry := make(map[NeedleId]keyField)
  197. for idxOffset := indexSize - NeedleMapEntrySize; uint64(idxOffset) >= v.lastCompactIndexOffset; idxOffset -= NeedleMapEntrySize {
  198. var IdxEntry []byte
  199. if IdxEntry, err = readIndexEntryAtOffset(oldIdxFile, idxOffset); err != nil {
  200. return fmt.Errorf("readIndexEntry %s at offset %d failed: %v", oldIdxFileName, idxOffset, err)
  201. }
  202. key, offset, size := idx2.IdxFileEntry(IdxEntry)
  203. glog.V(4).Infof("key %d offset %d size %d", key, offset, size)
  204. if _, found := incrementedHasUpdatedIndexEntry[key]; !found {
  205. incrementedHasUpdatedIndexEntry[key] = keyField{
  206. offset: offset,
  207. size: size,
  208. }
  209. }
  210. }
  211. // no updates during commit step
  212. if len(incrementedHasUpdatedIndexEntry) == 0 {
  213. return nil
  214. }
  215. // deal with updates during commit step
  216. var (
  217. dst, idx *os.File
  218. )
  219. if dst, err = os.OpenFile(newDatFileName, os.O_RDWR, 0644); err != nil {
  220. return fmt.Errorf("open dat file %s failed: %v", newDatFileName, err)
  221. }
  222. dstDatBackend := backend.NewDiskFile(dst)
  223. defer dstDatBackend.Close()
  224. if idx, err = os.OpenFile(newIdxFileName, os.O_RDWR, 0644); err != nil {
  225. return fmt.Errorf("open idx file %s failed: %v", newIdxFileName, err)
  226. }
  227. defer idx.Close()
  228. var newDatCompactRevision uint16
  229. newDatCompactRevision, err = fetchCompactRevisionFromDatFile(dstDatBackend)
  230. if err != nil {
  231. return fmt.Errorf("fetchCompactRevisionFromDatFile dst %s failed: %v", dst.Name(), err)
  232. }
  233. if oldDatCompactRevision+1 != newDatCompactRevision {
  234. return fmt.Errorf("oldDatFile %s 's compact revision is %d while newDatFile %s 's compact revision is %d", oldDatFileName, oldDatCompactRevision, newDatFileName, newDatCompactRevision)
  235. }
  236. for key, increIdxEntry := range incrementedHasUpdatedIndexEntry {
  237. idxEntryBytes := needle_map.ToBytes(key, increIdxEntry.offset, increIdxEntry.size)
  238. var offset int64
  239. if offset, err = dst.Seek(0, 2); err != nil {
  240. glog.V(0).Infof("failed to seek the end of file: %v", err)
  241. return
  242. }
  243. //ensure file writing starting from aligned positions
  244. if offset%NeedlePaddingSize != 0 {
  245. offset = offset + (NeedlePaddingSize - offset%NeedlePaddingSize)
  246. if offset, err = dst.Seek(offset, 0); err != nil {
  247. glog.V(0).Infof("failed to align in datafile %s: %v", dst.Name(), err)
  248. return
  249. }
  250. }
  251. //updated needle
  252. if !increIdxEntry.offset.IsZero() && increIdxEntry.size != 0 && increIdxEntry.size.IsValid() {
  253. //even the needle cache in memory is hit, the need_bytes is correct
  254. glog.V(4).Infof("file %d offset %d size %d", key, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size)
  255. var needleBytes []byte
  256. needleBytes, err = needle.ReadNeedleBlob(oldDatBackend, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size, v.Version())
  257. if err != nil {
  258. return fmt.Errorf("ReadNeedleBlob %s key %d offset %d size %d failed: %v", oldDatFile.Name(), key, increIdxEntry.offset.ToActualOffset(), increIdxEntry.size, err)
  259. }
  260. dstDatBackend.Write(needleBytes)
  261. if err := dstDatBackend.Sync(); err != nil {
  262. return fmt.Errorf("cannot sync needle %s: %v", dstDatBackend.File.Name(), err)
  263. }
  264. util.Uint32toBytes(idxEntryBytes[8:12], uint32(offset/NeedlePaddingSize))
  265. } else { //deleted needle
  266. //fakeDelNeedle 's default Data field is nil
  267. fakeDelNeedle := new(needle.Needle)
  268. fakeDelNeedle.Id = key
  269. fakeDelNeedle.Cookie = 0x12345678
  270. fakeDelNeedle.AppendAtNs = uint64(time.Now().UnixNano())
  271. _, _, _, err = fakeDelNeedle.Append(dstDatBackend, v.Version())
  272. if err != nil {
  273. return fmt.Errorf("append deleted %d failed: %v", key, err)
  274. }
  275. util.Uint32toBytes(idxEntryBytes[8:12], uint32(0))
  276. }
  277. if _, err := idx.Seek(0, 2); err != nil {
  278. return fmt.Errorf("cannot seek end of indexfile %s: %v",
  279. newIdxFileName, err)
  280. }
  281. _, err = idx.Write(idxEntryBytes)
  282. if err != nil {
  283. return fmt.Errorf("cannot write indexfile %s: %v", newIdxFileName, err)
  284. }
  285. if err := idx.Sync(); err != nil {
  286. return fmt.Errorf("cannot sync indexfile %s: %v", newIdxFileName, err)
  287. }
  288. }
  289. return nil
  290. }
  291. type VolumeFileScanner4Vacuum struct {
  292. version needle.Version
  293. v *Volume
  294. dstBackend backend.BackendStorageFile
  295. nm *needle_map.MemDb
  296. newOffset int64
  297. now uint64
  298. writeThrottler *util.WriteThrottler
  299. }
  300. func (scanner *VolumeFileScanner4Vacuum) VisitSuperBlock(superBlock super_block.SuperBlock) error {
  301. scanner.version = superBlock.Version
  302. superBlock.CompactionRevision++
  303. _, err := scanner.dstBackend.WriteAt(superBlock.Bytes(), 0)
  304. scanner.newOffset = int64(superBlock.BlockSize())
  305. return err
  306. }
  307. func (scanner *VolumeFileScanner4Vacuum) ReadNeedleBody() bool {
  308. return true
  309. }
  310. func (scanner *VolumeFileScanner4Vacuum) VisitNeedle(n *needle.Needle, offset int64, needleHeader, needleBody []byte) error {
  311. if n.HasTtl() && scanner.now >= n.LastModified+uint64(scanner.v.Ttl.Minutes()*60) {
  312. return nil
  313. }
  314. nv, ok := scanner.v.nm.Get(n.Id)
  315. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  316. if ok && nv.Offset.ToActualOffset() == offset && nv.Size > 0 && nv.Size.IsValid() {
  317. if err := scanner.nm.Set(n.Id, ToOffset(scanner.newOffset), n.Size); err != nil {
  318. return fmt.Errorf("cannot put needle: %s", err)
  319. }
  320. if _, _, _, err := n.Append(scanner.dstBackend, scanner.v.Version()); err != nil {
  321. return fmt.Errorf("cannot append needle: %s", err)
  322. }
  323. delta := n.DiskSize(scanner.version)
  324. scanner.newOffset += delta
  325. scanner.writeThrottler.MaybeSlowdown(delta)
  326. glog.V(4).Infoln("saving key", n.Id, "volume offset", offset, "=>", scanner.newOffset, "data_size", n.Size)
  327. }
  328. return nil
  329. }
  330. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, preallocate int64, compactionBytePerSecond int64) (err error) {
  331. var (
  332. dst backend.BackendStorageFile
  333. )
  334. if dst, err = backend.CreateVolumeFile(dstName, preallocate, 0); err != nil {
  335. return err
  336. }
  337. defer dst.Close()
  338. nm := needle_map.NewMemDb()
  339. defer nm.Close()
  340. scanner := &VolumeFileScanner4Vacuum{
  341. v: v,
  342. now: uint64(time.Now().Unix()),
  343. nm: nm,
  344. dstBackend: dst,
  345. writeThrottler: util.NewWriteThrottler(compactionBytePerSecond),
  346. }
  347. err = ScanVolumeFile(v.dir, v.Collection, v.Id, v.needleMapKind, scanner)
  348. if err != nil {
  349. return err
  350. }
  351. return nm.SaveToIdx(idxName)
  352. }
  353. func copyDataBasedOnIndexFile(srcDatName, srcIdxName, dstDatName, datIdxName string, sb super_block.SuperBlock, version needle.Version, preallocate, compactionBytePerSecond int64, progressFn ProgressFunc) (err error) {
  354. var (
  355. srcDatBackend, dstDatBackend backend.BackendStorageFile
  356. dataFile *os.File
  357. )
  358. if dstDatBackend, err = backend.CreateVolumeFile(dstDatName, preallocate, 0); err != nil {
  359. return err
  360. }
  361. defer dstDatBackend.Close()
  362. oldNm := needle_map.NewMemDb()
  363. defer oldNm.Close()
  364. newNm := needle_map.NewMemDb()
  365. defer newNm.Close()
  366. if err = oldNm.LoadFromIdx(srcIdxName); err != nil {
  367. return err
  368. }
  369. if dataFile, err = os.Open(srcDatName); err != nil {
  370. return err
  371. }
  372. srcDatBackend = backend.NewDiskFile(dataFile)
  373. defer srcDatBackend.Close()
  374. now := uint64(time.Now().Unix())
  375. sb.CompactionRevision++
  376. dstDatBackend.WriteAt(sb.Bytes(), 0)
  377. newOffset := int64(sb.BlockSize())
  378. writeThrottler := util.NewWriteThrottler(compactionBytePerSecond)
  379. err = oldNm.AscendingVisit(func(value needle_map.NeedleValue) error {
  380. offset, size := value.Offset, value.Size
  381. if offset.IsZero() || size.IsDeleted() {
  382. return nil
  383. }
  384. if progressFn != nil {
  385. if !progressFn(offset.ToActualOffset()) {
  386. return fmt.Errorf("interrupted")
  387. }
  388. }
  389. n := new(needle.Needle)
  390. err := n.ReadData(srcDatBackend, offset.ToActualOffset(), size, version)
  391. if err != nil {
  392. return fmt.Errorf("cannot hydrate needle from file: %s", err)
  393. }
  394. if n.HasTtl() && now >= n.LastModified+uint64(sb.Ttl.Minutes()*60) {
  395. return nil
  396. }
  397. if err = newNm.Set(n.Id, ToOffset(newOffset), n.Size); err != nil {
  398. return fmt.Errorf("cannot put needle: %s", err)
  399. }
  400. if _, _, _, err = n.Append(dstDatBackend, sb.Version); err != nil {
  401. return fmt.Errorf("cannot append needle: %s", err)
  402. }
  403. delta := n.DiskSize(version)
  404. newOffset += delta
  405. writeThrottler.MaybeSlowdown(delta)
  406. glog.V(4).Infoln("saving key", n.Id, "volume offset", offset, "=>", newOffset, "data_size", n.Size)
  407. return nil
  408. })
  409. if err != nil {
  410. return err
  411. }
  412. return newNm.SaveToIdx(datIdxName)
  413. }