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.

421 lines
13 KiB

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