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.

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