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.

342 lines
11 KiB

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