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.

400 lines
12 KiB

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