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.

367 lines
12 KiB

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