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.

339 lines
10 KiB

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