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.

402 lines
12 KiB

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