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.

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