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.

332 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/storage/types"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  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)
  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. _, _, err = fakeDelNeedle.Append(dst, v.Version())
  185. if err != nil {
  186. return fmt.Errorf("append deleted %d failed: %v", key, err)
  187. }
  188. util.Uint32toBytes(idx_entry_bytes[8:12], uint32(0))
  189. }
  190. if _, err := idx.Seek(0, 2); err != nil {
  191. return fmt.Errorf("cannot seek end of indexfile %s: %v",
  192. newIdxFileName, err)
  193. }
  194. _, err = idx.Write(idx_entry_bytes)
  195. }
  196. return nil
  197. }
  198. func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, preallocate int64) (err error) {
  199. var (
  200. dst, idx *os.File
  201. )
  202. if dst, err = createVolumeFile(dstName, preallocate); err != nil {
  203. return
  204. }
  205. defer dst.Close()
  206. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  207. return
  208. }
  209. defer idx.Close()
  210. nm := NewBtreeNeedleMap(idx)
  211. new_offset := int64(0)
  212. now := uint64(time.Now().Unix())
  213. err = ScanVolumeFile(v.dir, v.Collection, v.Id, v.needleMapKind,
  214. func(superBlock SuperBlock) error {
  215. superBlock.CompactRevision++
  216. _, err = dst.Write(superBlock.Bytes())
  217. new_offset = int64(superBlock.BlockSize())
  218. return err
  219. }, true, func(n *Needle, offset int64) error {
  220. if n.HasTtl() && now >= n.LastModified+uint64(v.Ttl.Minutes()*60) {
  221. return nil
  222. }
  223. nv, ok := v.nm.Get(n.Id)
  224. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  225. if ok && int64(nv.Offset)*NeedlePaddingSize == offset && nv.Size > 0 {
  226. if err = nm.Put(n.Id, Offset(new_offset/NeedlePaddingSize), n.Size); err != nil {
  227. return fmt.Errorf("cannot put needle: %s", err)
  228. }
  229. if _, _, err := n.Append(dst, v.Version()); err != nil {
  230. return fmt.Errorf("cannot append needle: %s", err)
  231. }
  232. new_offset += n.DiskSize()
  233. glog.V(3).Infoln("saving key", n.Id, "volume offset", offset, "=>", new_offset, "data_size", n.Size)
  234. }
  235. return nil
  236. })
  237. return
  238. }
  239. func (v *Volume) copyDataBasedOnIndexFile(dstName, idxName string) (err error) {
  240. var (
  241. dst, idx, oldIndexFile *os.File
  242. )
  243. if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  244. return
  245. }
  246. defer dst.Close()
  247. if idx, err = os.OpenFile(idxName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
  248. return
  249. }
  250. defer idx.Close()
  251. if oldIndexFile, err = os.OpenFile(v.FileName()+".idx", os.O_RDONLY, 0644); err != nil {
  252. return
  253. }
  254. defer oldIndexFile.Close()
  255. nm := NewBtreeNeedleMap(idx)
  256. now := uint64(time.Now().Unix())
  257. v.SuperBlock.CompactRevision++
  258. dst.Write(v.SuperBlock.Bytes())
  259. new_offset := int64(v.SuperBlock.BlockSize())
  260. WalkIndexFile(oldIndexFile, func(key NeedleId, offset Offset, size uint32) error {
  261. if offset == 0 || size == TombstoneFileSize {
  262. return nil
  263. }
  264. nv, ok := v.nm.Get(key)
  265. if !ok {
  266. return nil
  267. }
  268. n := new(Needle)
  269. n.ReadData(v.dataFile, int64(offset)*NeedlePaddingSize, size, v.Version())
  270. if n.HasTtl() && now >= n.LastModified+uint64(v.Ttl.Minutes()*60) {
  271. return nil
  272. }
  273. glog.V(4).Infoln("needle expected offset ", offset, "ok", ok, "nv", nv)
  274. if nv.Offset == offset && nv.Size > 0 {
  275. if err = nm.Put(n.Id, Offset(new_offset/NeedlePaddingSize), n.Size); err != nil {
  276. return fmt.Errorf("cannot put needle: %s", err)
  277. }
  278. if _, _, err = n.Append(dst, v.Version()); err != nil {
  279. return fmt.Errorf("cannot append needle: %s", err)
  280. }
  281. new_offset += n.DiskSize()
  282. glog.V(3).Infoln("saving key", n.Id, "volume offset", offset, "=>", new_offset, "data_size", n.Size)
  283. }
  284. return nil
  285. })
  286. return
  287. }