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.

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