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.

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