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.

363 lines
11 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
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) 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)
  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. }
  215. func (scanner *VolumeFileScanner4Vacuum) VisitSuperBlock(superBlock SuperBlock) error {
  216. scanner.version = superBlock.Version()
  217. superBlock.CompactionRevision++
  218. _, err := scanner.dst.Write(superBlock.Bytes())
  219. scanner.newOffset = int64(superBlock.BlockSize())
  220. return err
  221. }
  222. func (scanner *VolumeFileScanner4Vacuum) ReadNeedleBody() bool {
  223. return true
  224. }
  225. func (scanner *VolumeFileScanner4Vacuum) VisitNeedle(n *needle.Needle, offset int64) error {
  226. if n.HasTtl() && scanner.now >= n.LastModified+uint64(scanner.v.Ttl.Minutes()*60) {
  227. return nil
  228. }
  229. nv, ok := scanner.v.nm.Get(n.Id)
  230. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  231. if ok && nv.Offset.ToAcutalOffset() == offset && nv.Size > 0 && nv.Size != TombstoneFileSize {
  232. if err := scanner.nm.Put(n.Id, ToOffset(scanner.newOffset), n.Size); err != nil {
  233. return fmt.Errorf("cannot put needle: %s", err)
  234. }
  235. if _, _, _, err := n.Append(scanner.dst, scanner.v.Version()); err != nil {
  236. return fmt.Errorf("cannot append needle: %s", err)
  237. }
  238. scanner.newOffset += n.DiskSize(scanner.version)
  239. glog.V(4).Infoln("saving key", n.Id, "volume offset", offset, "=>", scanner.newOffset, "data_size", n.Size)
  240. }
  241. return nil
  242. }
  243. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, preallocate int64) (err error) {
  244. var (
  245. dst, idx *os.File
  246. )
  247. if dst, err = createVolumeFile(dstName, preallocate); err != nil {
  248. return
  249. }
  250. defer dst.Close()
  251. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  252. return
  253. }
  254. defer idx.Close()
  255. scanner := &VolumeFileScanner4Vacuum{
  256. v: v,
  257. now: uint64(time.Now().Unix()),
  258. nm: NewBtreeNeedleMap(idx),
  259. dst: dst,
  260. }
  261. err = ScanVolumeFile(v.dir, v.Collection, v.Id, v.needleMapKind, scanner)
  262. return
  263. }
  264. func (v *Volume) copyDataBasedOnIndexFile(dstName, idxName string) (err error) {
  265. var (
  266. dst, idx, oldIndexFile *os.File
  267. )
  268. if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  269. return
  270. }
  271. defer dst.Close()
  272. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  273. return
  274. }
  275. defer idx.Close()
  276. if oldIndexFile, err = os.OpenFile(v.FileName()+".idx", os.O_RDONLY, 0644); err != nil {
  277. return
  278. }
  279. defer oldIndexFile.Close()
  280. nm := NewBtreeNeedleMap(idx)
  281. now := uint64(time.Now().Unix())
  282. v.SuperBlock.CompactionRevision++
  283. dst.Write(v.SuperBlock.Bytes())
  284. newOffset := int64(v.SuperBlock.BlockSize())
  285. WalkIndexFile(oldIndexFile, func(key NeedleId, offset Offset, size uint32) error {
  286. if offset.IsZero() || size == TombstoneFileSize {
  287. return nil
  288. }
  289. nv, ok := v.nm.Get(key)
  290. if !ok {
  291. return nil
  292. }
  293. n := new(needle.Needle)
  294. err := n.ReadData(v.dataFile, offset.ToAcutalOffset(), size, v.Version())
  295. if err != nil {
  296. return nil
  297. }
  298. if n.HasTtl() && now >= n.LastModified+uint64(v.Ttl.Minutes()*60) {
  299. return nil
  300. }
  301. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  302. if nv.Offset == offset && nv.Size > 0 {
  303. if err = nm.Put(n.Id, ToOffset(newOffset), n.Size); err != nil {
  304. return fmt.Errorf("cannot put needle: %s", err)
  305. }
  306. if _, _, _, err = n.Append(dst, v.Version()); err != nil {
  307. return fmt.Errorf("cannot append needle: %s", err)
  308. }
  309. newOffset += n.DiskSize(v.Version())
  310. glog.V(3).Infoln("saving key", n.Id, "volume offset", offset, "=>", newOffset, "data_size", n.Size)
  311. }
  312. return nil
  313. })
  314. return
  315. }