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.

328 lines
9.5 KiB

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