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.

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