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.

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