freezer_table.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rawdb
  17. import (
  18. "encoding/binary"
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "sync"
  24. "sync/atomic"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/log"
  27. "github.com/ethereum/go-ethereum/metrics"
  28. "github.com/golang/snappy"
  29. )
  30. var (
  31. // errClosed is returned if an operation attempts to read from or write to the
  32. // freezer table after it has already been closed.
  33. errClosed = errors.New("closed")
  34. // errOutOfBounds is returned if the item requested is not contained within the
  35. // freezer table.
  36. errOutOfBounds = errors.New("out of bounds")
  37. // errNotSupported is returned if the database doesn't support the required operation.
  38. errNotSupported = errors.New("this operation is not supported")
  39. )
  40. // indexEntry contains the number/id of the file that the data resides in, aswell as the
  41. // offset within the file to the end of the data
  42. // In serialized form, the filenum is stored as uint16.
  43. type indexEntry struct {
  44. filenum uint32 // stored as uint16 ( 2 bytes)
  45. offset uint32 // stored as uint32 ( 4 bytes)
  46. }
  47. const indexEntrySize = 6
  48. // unmarshallBinary deserializes binary b into the rawIndex entry.
  49. func (i *indexEntry) unmarshalBinary(b []byte) error {
  50. i.filenum = uint32(binary.BigEndian.Uint16(b[:2]))
  51. i.offset = binary.BigEndian.Uint32(b[2:6])
  52. return nil
  53. }
  54. // marshallBinary serializes the rawIndex entry into binary.
  55. func (i *indexEntry) marshallBinary() []byte {
  56. b := make([]byte, indexEntrySize)
  57. binary.BigEndian.PutUint16(b[:2], uint16(i.filenum))
  58. binary.BigEndian.PutUint32(b[2:6], i.offset)
  59. return b
  60. }
  61. // freezerTable represents a single chained data table within the freezer (e.g. blocks).
  62. // It consists of a data file (snappy encoded arbitrary data blobs) and an indexEntry
  63. // file (uncompressed 64 bit indices into the data file).
  64. type freezerTable struct {
  65. noCompression bool // if true, disables snappy compression. Note: does not work retroactively
  66. maxFileSize uint32 // Max file size for data-files
  67. name string
  68. path string
  69. head *os.File // File descriptor for the data head of the table
  70. files map[uint32]*os.File // open files
  71. headId uint32 // number of the currently active head file
  72. index *os.File // File descriptor for the indexEntry file of the table
  73. items uint64 // Number of items stored in the table
  74. headBytes uint32 // Number of bytes written to the head file
  75. readMeter metrics.Meter // Meter for measuring the effective amount of data read
  76. writeMeter metrics.Meter // Meter for measuring the effective amount of data written
  77. logger log.Logger // Logger with database path and table name ambedded
  78. lock sync.RWMutex // Mutex protecting the data file descriptors
  79. }
  80. // newTable opens a freezer table with default settings - 2G files and snappy compression
  81. func newTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter) (*freezerTable, error) {
  82. return newCustomTable(path, name, readMeter, writeMeter, 2*1000*1000*1000, false)
  83. }
  84. // newCustomTable opens a freezer table, creating the data and index files if they are
  85. // non existent. Both files are truncated to the shortest common length to ensure
  86. // they don't go out of sync.
  87. func newCustomTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, maxFilesize uint32, noCompression bool) (*freezerTable, error) {
  88. // Ensure the containing directory exists and open the indexEntry file
  89. if err := os.MkdirAll(path, 0755); err != nil {
  90. return nil, err
  91. }
  92. var idxName string
  93. if noCompression {
  94. // raw idx
  95. idxName = fmt.Sprintf("%s.ridx", name)
  96. } else {
  97. // compressed idx
  98. idxName = fmt.Sprintf("%s.cidx", name)
  99. }
  100. offsets, err := os.OpenFile(filepath.Join(path, idxName), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  101. if err != nil {
  102. return nil, err
  103. }
  104. // Create the table and repair any past inconsistency
  105. tab := &freezerTable{
  106. index: offsets,
  107. files: make(map[uint32]*os.File),
  108. readMeter: readMeter,
  109. writeMeter: writeMeter,
  110. name: name,
  111. path: path,
  112. logger: log.New("database", path, "table", name),
  113. noCompression: noCompression,
  114. maxFileSize: maxFilesize,
  115. }
  116. if err := tab.repair(); err != nil {
  117. tab.Close()
  118. return nil, err
  119. }
  120. return tab, nil
  121. }
  122. // repair cross checks the head and the index file and truncates them to
  123. // be in sync with each other after a potential crash / data loss.
  124. func (t *freezerTable) repair() error {
  125. // Create a temporary offset buffer to init files with and read indexEntry into
  126. buffer := make([]byte, indexEntrySize)
  127. // If we've just created the files, initialize the index with the 0 indexEntry
  128. stat, err := t.index.Stat()
  129. if err != nil {
  130. return err
  131. }
  132. if stat.Size() == 0 {
  133. if _, err := t.index.Write(buffer); err != nil {
  134. return err
  135. }
  136. }
  137. // Ensure the index is a multiple of indexEntrySize bytes
  138. if overflow := stat.Size() % indexEntrySize; overflow != 0 {
  139. t.index.Truncate(stat.Size() - overflow) // New file can't trigger this path
  140. }
  141. // Retrieve the file sizes and prepare for truncation
  142. if stat, err = t.index.Stat(); err != nil {
  143. return err
  144. }
  145. offsetsSize := stat.Size()
  146. // Open the head file
  147. var (
  148. lastIndex indexEntry
  149. contentSize int64
  150. contentExp int64
  151. )
  152. t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
  153. lastIndex.unmarshalBinary(buffer)
  154. t.head, err = t.openFile(lastIndex.filenum, os.O_RDWR|os.O_CREATE|os.O_APPEND)
  155. if err != nil {
  156. return err
  157. }
  158. if stat, err = t.head.Stat(); err != nil {
  159. return err
  160. }
  161. contentSize = stat.Size()
  162. // Keep truncating both files until they come in sync
  163. contentExp = int64(lastIndex.offset)
  164. for contentExp != contentSize {
  165. // Truncate the head file to the last offset pointer
  166. if contentExp < contentSize {
  167. t.logger.Warn("Truncating dangling head", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  168. if err := t.head.Truncate(contentExp); err != nil {
  169. return err
  170. }
  171. contentSize = contentExp
  172. }
  173. // Truncate the index to point within the head file
  174. if contentExp > contentSize {
  175. t.logger.Warn("Truncating dangling indexes", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  176. if err := t.index.Truncate(offsetsSize - indexEntrySize); err != nil {
  177. return err
  178. }
  179. offsetsSize -= indexEntrySize
  180. t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
  181. var newLastIndex indexEntry
  182. newLastIndex.unmarshalBinary(buffer)
  183. // We might have slipped back into an earlier head-file here
  184. if newLastIndex.filenum != lastIndex.filenum {
  185. // release earlier opened file
  186. t.releaseFile(lastIndex.filenum)
  187. t.head, err = t.openFile(newLastIndex.filenum, os.O_RDWR|os.O_CREATE|os.O_APPEND)
  188. if stat, err = t.head.Stat(); err != nil {
  189. // TODO, anything more we can do here?
  190. // A data file has gone missing...
  191. return err
  192. }
  193. contentSize = stat.Size()
  194. }
  195. lastIndex = newLastIndex
  196. contentExp = int64(lastIndex.offset)
  197. }
  198. }
  199. // Ensure all reparation changes have been written to disk
  200. if err := t.index.Sync(); err != nil {
  201. return err
  202. }
  203. if err := t.head.Sync(); err != nil {
  204. return err
  205. }
  206. // Update the item and byte counters and return
  207. t.items = uint64(offsetsSize/indexEntrySize - 1) // last indexEntry points to the end of the data file
  208. t.headBytes = uint32(contentSize)
  209. t.headId = lastIndex.filenum
  210. // Close opened files and preopen all files
  211. if err := t.preopen(); err != nil {
  212. return err
  213. }
  214. t.logger.Debug("Chain freezer table opened", "items", t.items, "size", common.StorageSize(t.headBytes))
  215. return nil
  216. }
  217. // preopen opens all files that the freezer will need. This method should be called from an init-context,
  218. // since it assumes that it doesn't have to bother with locking
  219. // The rationale for doing preopen is to not have to do it from within Retrieve, thus not needing to ever
  220. // obtain a write-lock within Retrieve.
  221. func (t *freezerTable) preopen() (err error) {
  222. // The repair might have already opened (some) files
  223. t.releaseFilesAfter(0, false)
  224. // Open all except head in RDONLY
  225. for i := uint32(0); i < t.headId; i++ {
  226. if _, err = t.openFile(i, os.O_RDONLY); err != nil {
  227. return err
  228. }
  229. }
  230. // Open head in read/write
  231. t.head, err = t.openFile(t.headId, os.O_RDWR|os.O_CREATE|os.O_APPEND)
  232. return err
  233. }
  234. // truncate discards any recent data above the provided threashold number.
  235. func (t *freezerTable) truncate(items uint64) error {
  236. t.lock.Lock()
  237. defer t.lock.Unlock()
  238. // If out item count is corrent, don't do anything
  239. if atomic.LoadUint64(&t.items) <= items {
  240. return nil
  241. }
  242. // Something's out of sync, truncate the table's offset index
  243. t.logger.Warn("Truncating freezer table", "items", t.items, "limit", items)
  244. if err := t.index.Truncate(int64(items+1) * indexEntrySize); err != nil {
  245. return err
  246. }
  247. // Calculate the new expected size of the data file and truncate it
  248. buffer := make([]byte, indexEntrySize)
  249. if _, err := t.index.ReadAt(buffer, int64(items*indexEntrySize)); err != nil {
  250. return err
  251. }
  252. var expected indexEntry
  253. expected.unmarshalBinary(buffer)
  254. // We might need to truncate back to older files
  255. if expected.filenum != t.headId {
  256. // If already open for reading, force-reopen for writing
  257. t.releaseFile(expected.filenum)
  258. newHead, err := t.openFile(expected.filenum, os.O_RDWR|os.O_CREATE|os.O_APPEND)
  259. if err != nil {
  260. return err
  261. }
  262. // release any files _after the current head -- both the previous head
  263. // and any files which may have been opened for reading
  264. t.releaseFilesAfter(expected.filenum, true)
  265. // set back the historic head
  266. t.head = newHead
  267. atomic.StoreUint32(&t.headId, expected.filenum)
  268. }
  269. if err := t.head.Truncate(int64(expected.offset)); err != nil {
  270. return err
  271. }
  272. // All data files truncated, set internal counters and return
  273. atomic.StoreUint64(&t.items, items)
  274. atomic.StoreUint32(&t.headBytes, expected.offset)
  275. return nil
  276. }
  277. // Close closes all opened files.
  278. func (t *freezerTable) Close() error {
  279. t.lock.Lock()
  280. defer t.lock.Unlock()
  281. var errs []error
  282. if err := t.index.Close(); err != nil {
  283. errs = append(errs, err)
  284. }
  285. t.index = nil
  286. for _, f := range t.files {
  287. if err := f.Close(); err != nil {
  288. errs = append(errs, err)
  289. }
  290. }
  291. t.head = nil
  292. if errs != nil {
  293. return fmt.Errorf("%v", errs)
  294. }
  295. return nil
  296. }
  297. // openFile assumes that the write-lock is held by the caller
  298. func (t *freezerTable) openFile(num uint32, flag int) (f *os.File, err error) {
  299. var exist bool
  300. if f, exist = t.files[num]; !exist {
  301. var name string
  302. if t.noCompression {
  303. name = fmt.Sprintf("%s.%d.rdat", t.name, num)
  304. } else {
  305. name = fmt.Sprintf("%s.%d.cdat", t.name, num)
  306. }
  307. f, err = os.OpenFile(filepath.Join(t.path, name), flag, 0644)
  308. if err != nil {
  309. return nil, err
  310. }
  311. t.files[num] = f
  312. }
  313. return f, err
  314. }
  315. // releaseFile closes a file, and removes it from the open file cache.
  316. // Assumes that the caller holds the write lock
  317. func (t *freezerTable) releaseFile(num uint32) {
  318. if f, exist := t.files[num]; exist {
  319. delete(t.files, num)
  320. f.Close()
  321. }
  322. }
  323. // releaseFilesAfter closes all open files with a higher number, and optionally also deletes the files
  324. func (t *freezerTable) releaseFilesAfter(num uint32, remove bool) {
  325. for fnum, f := range t.files {
  326. if fnum > num {
  327. delete(t.files, fnum)
  328. f.Close()
  329. if remove {
  330. os.Remove(f.Name())
  331. }
  332. }
  333. }
  334. }
  335. // Append injects a binary blob at the end of the freezer table. The item number
  336. // is a precautionary parameter to ensure data correctness, but the table will
  337. // reject already existing data.
  338. //
  339. // Note, this method will *not* flush any data to disk so be sure to explicitly
  340. // fsync before irreversibly deleting data from the database.
  341. func (t *freezerTable) Append(item uint64, blob []byte) error {
  342. // Read lock prevents competition with truncate
  343. t.lock.RLock()
  344. // Ensure the table is still accessible
  345. if t.index == nil || t.head == nil {
  346. return errClosed
  347. }
  348. // Ensure only the next item can be written, nothing else
  349. if atomic.LoadUint64(&t.items) != item {
  350. panic(fmt.Sprintf("appending unexpected item: want %d, have %d", t.items, item))
  351. }
  352. // Encode the blob and write it into the data file
  353. if !t.noCompression {
  354. blob = snappy.Encode(nil, blob)
  355. }
  356. bLen := uint32(len(blob))
  357. if t.headBytes+bLen < bLen ||
  358. t.headBytes+bLen > t.maxFileSize {
  359. // we need a new file, writing would overflow
  360. t.lock.RUnlock()
  361. t.lock.Lock()
  362. nextId := atomic.LoadUint32(&t.headId) + 1
  363. // We open the next file in truncated mode -- if this file already
  364. // exists, we need to start over from scratch on it
  365. newHead, err := t.openFile(nextId, os.O_RDWR|os.O_CREATE|os.O_TRUNC)
  366. if err != nil {
  367. t.lock.Unlock()
  368. return err
  369. }
  370. // Close old file, and reopen in RDONLY mode
  371. t.releaseFile(t.headId)
  372. t.openFile(t.headId, os.O_RDONLY)
  373. // Swap out the current head
  374. t.head = newHead
  375. atomic.StoreUint32(&t.headBytes, 0)
  376. atomic.StoreUint32(&t.headId, nextId)
  377. t.lock.Unlock()
  378. t.lock.RLock()
  379. }
  380. defer t.lock.RUnlock()
  381. if _, err := t.head.Write(blob); err != nil {
  382. return err
  383. }
  384. newOffset := atomic.AddUint32(&t.headBytes, bLen)
  385. idx := indexEntry{
  386. filenum: atomic.LoadUint32(&t.headId),
  387. offset: newOffset,
  388. }
  389. // Write indexEntry
  390. t.index.Write(idx.marshallBinary())
  391. t.writeMeter.Mark(int64(bLen + indexEntrySize))
  392. atomic.AddUint64(&t.items, 1)
  393. return nil
  394. }
  395. // getBounds returns the indexes for the item
  396. // returns start, end, filenumber and error
  397. func (t *freezerTable) getBounds(item uint64) (uint32, uint32, uint32, error) {
  398. var startIdx, endIdx indexEntry
  399. buffer := make([]byte, indexEntrySize)
  400. if _, err := t.index.ReadAt(buffer, int64(item*indexEntrySize)); err != nil {
  401. return 0, 0, 0, err
  402. }
  403. startIdx.unmarshalBinary(buffer)
  404. if _, err := t.index.ReadAt(buffer, int64((item+1)*indexEntrySize)); err != nil {
  405. return 0, 0, 0, err
  406. }
  407. endIdx.unmarshalBinary(buffer)
  408. if startIdx.filenum != endIdx.filenum {
  409. // If a piece of data 'crosses' a data-file,
  410. // it's actually in one piece on the second data-file.
  411. // We return a zero-indexEntry for the second file as start
  412. return 0, endIdx.offset, endIdx.filenum, nil
  413. }
  414. return startIdx.offset, endIdx.offset, endIdx.filenum, nil
  415. }
  416. // Retrieve looks up the data offset of an item with the given number and retrieves
  417. // the raw binary blob from the data file.
  418. func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
  419. // Ensure the table and the item is accessible
  420. if t.index == nil || t.head == nil {
  421. return nil, errClosed
  422. }
  423. if atomic.LoadUint64(&t.items) <= item {
  424. return nil, errOutOfBounds
  425. }
  426. t.lock.RLock()
  427. startOffset, endOffset, filenum, err := t.getBounds(item)
  428. if err != nil {
  429. return nil, err
  430. }
  431. dataFile, exist := t.files[filenum]
  432. if !exist {
  433. return nil, fmt.Errorf("missing data file %d", filenum)
  434. }
  435. // Retrieve the data itself, decompress and return
  436. blob := make([]byte, endOffset-startOffset)
  437. if _, err := dataFile.ReadAt(blob, int64(startOffset)); err != nil {
  438. t.lock.RUnlock()
  439. return nil, err
  440. }
  441. t.lock.RUnlock()
  442. t.readMeter.Mark(int64(len(blob) + 2*indexEntrySize))
  443. if t.noCompression {
  444. return blob, nil
  445. }
  446. return snappy.Decode(nil, blob)
  447. }
  448. // has returns an indicator whether the specified number data
  449. // exists in the freezer table.
  450. func (t *freezerTable) has(number uint64) bool {
  451. return atomic.LoadUint64(&t.items) > number
  452. }
  453. // Sync pushes any pending data from memory out to disk. This is an expensive
  454. // operation, so use it with care.
  455. func (t *freezerTable) Sync() error {
  456. if err := t.index.Sync(); err != nil {
  457. return err
  458. }
  459. return t.head.Sync()
  460. }