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.

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