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