freezer_table.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. "io"
  22. "os"
  23. "path/filepath"
  24. "sync"
  25. "sync/atomic"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/metrics"
  29. "github.com/golang/snappy"
  30. )
  31. var (
  32. // errClosed is returned if an operation attempts to read from or write to the
  33. // freezer table after it has already been closed.
  34. errClosed = errors.New("closed")
  35. // errOutOfBounds is returned if the item requested is not contained within the
  36. // freezer table.
  37. errOutOfBounds = errors.New("out of bounds")
  38. // errNotSupported is returned if the database doesn't support the required operation.
  39. errNotSupported = errors.New("this operation is not supported")
  40. )
  41. // indexEntry contains the number/id of the file that the data resides in, aswell as the
  42. // offset within the file to the end of the data
  43. // In serialized form, the filenum is stored as uint16.
  44. type indexEntry struct {
  45. filenum uint32 // stored as uint16 ( 2 bytes)
  46. offset uint32 // stored as uint32 ( 4 bytes)
  47. }
  48. const indexEntrySize = 6
  49. // unmarshallBinary deserializes binary b into the rawIndex entry.
  50. func (i *indexEntry) unmarshalBinary(b []byte) error {
  51. i.filenum = uint32(binary.BigEndian.Uint16(b[:2]))
  52. i.offset = binary.BigEndian.Uint32(b[2:6])
  53. return nil
  54. }
  55. // marshallBinary serializes the rawIndex entry into binary.
  56. func (i *indexEntry) marshallBinary() []byte {
  57. b := make([]byte, indexEntrySize)
  58. binary.BigEndian.PutUint16(b[:2], uint16(i.filenum))
  59. binary.BigEndian.PutUint32(b[2:6], i.offset)
  60. return b
  61. }
  62. // freezerTable represents a single chained data table within the freezer (e.g. blocks).
  63. // It consists of a data file (snappy encoded arbitrary data blobs) and an indexEntry
  64. // file (uncompressed 64 bit indices into the data file).
  65. type freezerTable struct {
  66. // WARNING: The `items` field is accessed atomically. On 32 bit platforms, only
  67. // 64-bit aligned fields can be atomic. The struct is guaranteed to be so aligned,
  68. // so take advantage of that (https://golang.org/pkg/sync/atomic/#pkg-note-BUG).
  69. items uint64 // Number of items stored in the table (including items removed from tail)
  70. noCompression bool // if true, disables snappy compression. Note: does not work retroactively
  71. maxFileSize uint32 // Max file size for data-files
  72. name string
  73. path string
  74. head *os.File // File descriptor for the data head of the table
  75. files map[uint32]*os.File // open files
  76. headId uint32 // number of the currently active head file
  77. tailId uint32 // number of the earliest file
  78. index *os.File // File descriptor for the indexEntry file of the table
  79. // In the case that old items are deleted (from the tail), we use itemOffset
  80. // to count how many historic items have gone missing.
  81. itemOffset uint32 // Offset (number of discarded items)
  82. headBytes uint32 // Number of bytes written to the head file
  83. readMeter metrics.Meter // Meter for measuring the effective amount of data read
  84. writeMeter metrics.Meter // Meter for measuring the effective amount of data written
  85. logger log.Logger // Logger with database path and table name ambedded
  86. lock sync.RWMutex // Mutex protecting the data file descriptors
  87. }
  88. // newTable opens a freezer table with default settings - 2G files
  89. func newTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, disableSnappy bool) (*freezerTable, error) {
  90. return newCustomTable(path, name, readMeter, writeMeter, 2*1000*1000*1000, disableSnappy)
  91. }
  92. // openFreezerFileForAppend opens a freezer table file and seeks to the end
  93. func openFreezerFileForAppend(filename string) (*os.File, error) {
  94. // Open the file without the O_APPEND flag
  95. // because it has differing behaviour during Truncate operations
  96. // on different OS's
  97. file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0644)
  98. if err != nil {
  99. return nil, err
  100. }
  101. // Seek to end for append
  102. if _, err = file.Seek(0, io.SeekEnd); err != nil {
  103. return nil, err
  104. }
  105. return file, nil
  106. }
  107. // openFreezerFileForReadOnly opens a freezer table file for read only access
  108. func openFreezerFileForReadOnly(filename string) (*os.File, error) {
  109. return os.OpenFile(filename, os.O_RDONLY, 0644)
  110. }
  111. // openFreezerFileTruncated opens a freezer table making sure it is truncated
  112. func openFreezerFileTruncated(filename string) (*os.File, error) {
  113. return os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
  114. }
  115. // truncateFreezerFile resizes a freezer table file and seeks to the end
  116. func truncateFreezerFile(file *os.File, size int64) error {
  117. if err := file.Truncate(size); err != nil {
  118. return err
  119. }
  120. // Seek to end for append
  121. if _, err := file.Seek(0, io.SeekEnd); err != nil {
  122. return err
  123. }
  124. return nil
  125. }
  126. // newCustomTable opens a freezer table, creating the data and index files if they are
  127. // non existent. Both files are truncated to the shortest common length to ensure
  128. // they don't go out of sync.
  129. func newCustomTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, maxFilesize uint32, noCompression bool) (*freezerTable, error) {
  130. // Ensure the containing directory exists and open the indexEntry file
  131. if err := os.MkdirAll(path, 0755); err != nil {
  132. return nil, err
  133. }
  134. var idxName string
  135. if noCompression {
  136. // Raw idx
  137. idxName = fmt.Sprintf("%s.ridx", name)
  138. } else {
  139. // Compressed idx
  140. idxName = fmt.Sprintf("%s.cidx", name)
  141. }
  142. offsets, err := openFreezerFileForAppend(filepath.Join(path, idxName))
  143. if err != nil {
  144. return nil, err
  145. }
  146. // Create the table and repair any past inconsistency
  147. tab := &freezerTable{
  148. index: offsets,
  149. files: make(map[uint32]*os.File),
  150. readMeter: readMeter,
  151. writeMeter: writeMeter,
  152. name: name,
  153. path: path,
  154. logger: log.New("database", path, "table", name),
  155. noCompression: noCompression,
  156. maxFileSize: maxFilesize,
  157. }
  158. if err := tab.repair(); err != nil {
  159. tab.Close()
  160. return nil, err
  161. }
  162. return tab, nil
  163. }
  164. // repair cross checks the head and the index file and truncates them to
  165. // be in sync with each other after a potential crash / data loss.
  166. func (t *freezerTable) repair() error {
  167. // Create a temporary offset buffer to init files with and read indexEntry into
  168. buffer := make([]byte, indexEntrySize)
  169. // If we've just created the files, initialize the index with the 0 indexEntry
  170. stat, err := t.index.Stat()
  171. if err != nil {
  172. return err
  173. }
  174. if stat.Size() == 0 {
  175. if _, err := t.index.Write(buffer); err != nil {
  176. return err
  177. }
  178. }
  179. // Ensure the index is a multiple of indexEntrySize bytes
  180. if overflow := stat.Size() % indexEntrySize; overflow != 0 {
  181. truncateFreezerFile(t.index, stat.Size()-overflow) // New file can't trigger this path
  182. }
  183. // Retrieve the file sizes and prepare for truncation
  184. if stat, err = t.index.Stat(); err != nil {
  185. return err
  186. }
  187. offsetsSize := stat.Size()
  188. // Open the head file
  189. var (
  190. firstIndex indexEntry
  191. lastIndex indexEntry
  192. contentSize int64
  193. contentExp int64
  194. )
  195. // Read index zero, determine what file is the earliest
  196. // and what item offset to use
  197. t.index.ReadAt(buffer, 0)
  198. firstIndex.unmarshalBinary(buffer)
  199. t.tailId = firstIndex.offset
  200. t.itemOffset = firstIndex.filenum
  201. t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
  202. lastIndex.unmarshalBinary(buffer)
  203. t.head, err = t.openFile(lastIndex.filenum, openFreezerFileForAppend)
  204. if err != nil {
  205. return err
  206. }
  207. if stat, err = t.head.Stat(); err != nil {
  208. return err
  209. }
  210. contentSize = stat.Size()
  211. // Keep truncating both files until they come in sync
  212. contentExp = int64(lastIndex.offset)
  213. for contentExp != contentSize {
  214. // Truncate the head file to the last offset pointer
  215. if contentExp < contentSize {
  216. t.logger.Warn("Truncating dangling head", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  217. if err := truncateFreezerFile(t.head, contentExp); err != nil {
  218. return err
  219. }
  220. contentSize = contentExp
  221. }
  222. // Truncate the index to point within the head file
  223. if contentExp > contentSize {
  224. t.logger.Warn("Truncating dangling indexes", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  225. if err := truncateFreezerFile(t.index, offsetsSize-indexEntrySize); err != nil {
  226. return err
  227. }
  228. offsetsSize -= indexEntrySize
  229. t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
  230. var newLastIndex indexEntry
  231. newLastIndex.unmarshalBinary(buffer)
  232. // We might have slipped back into an earlier head-file here
  233. if newLastIndex.filenum != lastIndex.filenum {
  234. // Release earlier opened file
  235. t.releaseFile(lastIndex.filenum)
  236. t.head, err = t.openFile(newLastIndex.filenum, openFreezerFileForAppend)
  237. if stat, err = t.head.Stat(); err != nil {
  238. // TODO, anything more we can do here?
  239. // A data file has gone missing...
  240. return err
  241. }
  242. contentSize = stat.Size()
  243. }
  244. lastIndex = newLastIndex
  245. contentExp = int64(lastIndex.offset)
  246. }
  247. }
  248. // Ensure all reparation changes have been written to disk
  249. if err := t.index.Sync(); err != nil {
  250. return err
  251. }
  252. if err := t.head.Sync(); err != nil {
  253. return err
  254. }
  255. // Update the item and byte counters and return
  256. t.items = uint64(t.itemOffset) + uint64(offsetsSize/indexEntrySize-1) // last indexEntry points to the end of the data file
  257. t.headBytes = uint32(contentSize)
  258. t.headId = lastIndex.filenum
  259. // Close opened files and preopen all files
  260. if err := t.preopen(); err != nil {
  261. return err
  262. }
  263. t.logger.Debug("Chain freezer table opened", "items", t.items, "size", common.StorageSize(t.headBytes))
  264. return nil
  265. }
  266. // preopen opens all files that the freezer will need. This method should be called from an init-context,
  267. // since it assumes that it doesn't have to bother with locking
  268. // The rationale for doing preopen is to not have to do it from within Retrieve, thus not needing to ever
  269. // obtain a write-lock within Retrieve.
  270. func (t *freezerTable) preopen() (err error) {
  271. // The repair might have already opened (some) files
  272. t.releaseFilesAfter(0, false)
  273. // Open all except head in RDONLY
  274. for i := t.tailId; i < t.headId; i++ {
  275. if _, err = t.openFile(i, openFreezerFileForReadOnly); err != nil {
  276. return err
  277. }
  278. }
  279. // Open head in read/write
  280. t.head, err = t.openFile(t.headId, openFreezerFileForAppend)
  281. return err
  282. }
  283. // truncate discards any recent data above the provided threshold number.
  284. func (t *freezerTable) truncate(items uint64) error {
  285. t.lock.Lock()
  286. defer t.lock.Unlock()
  287. // If our item count is correct, don't do anything
  288. if atomic.LoadUint64(&t.items) <= items {
  289. return nil
  290. }
  291. // Something's out of sync, truncate the table's offset index
  292. t.logger.Warn("Truncating freezer table", "items", t.items, "limit", items)
  293. if err := truncateFreezerFile(t.index, int64(items+1)*indexEntrySize); err != nil {
  294. return err
  295. }
  296. // Calculate the new expected size of the data file and truncate it
  297. buffer := make([]byte, indexEntrySize)
  298. if _, err := t.index.ReadAt(buffer, int64(items*indexEntrySize)); err != nil {
  299. return err
  300. }
  301. var expected indexEntry
  302. expected.unmarshalBinary(buffer)
  303. // We might need to truncate back to older files
  304. if expected.filenum != t.headId {
  305. // If already open for reading, force-reopen for writing
  306. t.releaseFile(expected.filenum)
  307. newHead, err := t.openFile(expected.filenum, openFreezerFileForAppend)
  308. if err != nil {
  309. return err
  310. }
  311. // Release any files _after the current head -- both the previous head
  312. // and any files which may have been opened for reading
  313. t.releaseFilesAfter(expected.filenum, true)
  314. // Set back the historic head
  315. t.head = newHead
  316. atomic.StoreUint32(&t.headId, expected.filenum)
  317. }
  318. if err := truncateFreezerFile(t.head, int64(expected.offset)); err != nil {
  319. return err
  320. }
  321. // All data files truncated, set internal counters and return
  322. atomic.StoreUint64(&t.items, items)
  323. atomic.StoreUint32(&t.headBytes, expected.offset)
  324. return nil
  325. }
  326. // Close closes all opened files.
  327. func (t *freezerTable) Close() error {
  328. t.lock.Lock()
  329. defer t.lock.Unlock()
  330. var errs []error
  331. if err := t.index.Close(); err != nil {
  332. errs = append(errs, err)
  333. }
  334. t.index = nil
  335. for _, f := range t.files {
  336. if err := f.Close(); err != nil {
  337. errs = append(errs, err)
  338. }
  339. }
  340. t.head = nil
  341. if errs != nil {
  342. return fmt.Errorf("%v", errs)
  343. }
  344. return nil
  345. }
  346. // openFile assumes that the write-lock is held by the caller
  347. func (t *freezerTable) openFile(num uint32, opener func(string) (*os.File, error)) (f *os.File, err error) {
  348. var exist bool
  349. if f, exist = t.files[num]; !exist {
  350. var name string
  351. if t.noCompression {
  352. name = fmt.Sprintf("%s.%04d.rdat", t.name, num)
  353. } else {
  354. name = fmt.Sprintf("%s.%04d.cdat", t.name, num)
  355. }
  356. f, err = opener(filepath.Join(t.path, name))
  357. if err != nil {
  358. return nil, err
  359. }
  360. t.files[num] = f
  361. }
  362. return f, err
  363. }
  364. // releaseFile closes a file, and removes it from the open file cache.
  365. // Assumes that the caller holds the write lock
  366. func (t *freezerTable) releaseFile(num uint32) {
  367. if f, exist := t.files[num]; exist {
  368. delete(t.files, num)
  369. f.Close()
  370. }
  371. }
  372. // releaseFilesAfter closes all open files with a higher number, and optionally also deletes the files
  373. func (t *freezerTable) releaseFilesAfter(num uint32, remove bool) {
  374. for fnum, f := range t.files {
  375. if fnum > num {
  376. delete(t.files, fnum)
  377. f.Close()
  378. if remove {
  379. os.Remove(f.Name())
  380. }
  381. }
  382. }
  383. }
  384. // Append injects a binary blob at the end of the freezer table. The item number
  385. // is a precautionary parameter to ensure data correctness, but the table will
  386. // reject already existing data.
  387. //
  388. // Note, this method will *not* flush any data to disk so be sure to explicitly
  389. // fsync before irreversibly deleting data from the database.
  390. func (t *freezerTable) Append(item uint64, blob []byte) error {
  391. // Read lock prevents competition with truncate
  392. t.lock.RLock()
  393. // Ensure the table is still accessible
  394. if t.index == nil || t.head == nil {
  395. t.lock.RUnlock()
  396. return errClosed
  397. }
  398. // Ensure only the next item can be written, nothing else
  399. if atomic.LoadUint64(&t.items) != item {
  400. t.lock.RUnlock()
  401. return fmt.Errorf("appending unexpected item: want %d, have %d", t.items, item)
  402. }
  403. // Encode the blob and write it into the data file
  404. if !t.noCompression {
  405. blob = snappy.Encode(nil, blob)
  406. }
  407. bLen := uint32(len(blob))
  408. if t.headBytes+bLen < bLen ||
  409. t.headBytes+bLen > t.maxFileSize {
  410. // we need a new file, writing would overflow
  411. t.lock.RUnlock()
  412. t.lock.Lock()
  413. nextID := atomic.LoadUint32(&t.headId) + 1
  414. // We open the next file in truncated mode -- if this file already
  415. // exists, we need to start over from scratch on it
  416. newHead, err := t.openFile(nextID, openFreezerFileTruncated)
  417. if err != nil {
  418. t.lock.Unlock()
  419. return err
  420. }
  421. // Close old file, and reopen in RDONLY mode
  422. t.releaseFile(t.headId)
  423. t.openFile(t.headId, openFreezerFileForReadOnly)
  424. // Swap out the current head
  425. t.head = newHead
  426. atomic.StoreUint32(&t.headBytes, 0)
  427. atomic.StoreUint32(&t.headId, nextID)
  428. t.lock.Unlock()
  429. t.lock.RLock()
  430. }
  431. defer t.lock.RUnlock()
  432. if _, err := t.head.Write(blob); err != nil {
  433. return err
  434. }
  435. newOffset := atomic.AddUint32(&t.headBytes, bLen)
  436. idx := indexEntry{
  437. filenum: atomic.LoadUint32(&t.headId),
  438. offset: newOffset,
  439. }
  440. // Write indexEntry
  441. t.index.Write(idx.marshallBinary())
  442. t.writeMeter.Mark(int64(bLen + indexEntrySize))
  443. atomic.AddUint64(&t.items, 1)
  444. return nil
  445. }
  446. // getBounds returns the indexes for the item
  447. // returns start, end, filenumber and error
  448. func (t *freezerTable) getBounds(item uint64) (uint32, uint32, uint32, error) {
  449. var startIdx, endIdx indexEntry
  450. buffer := make([]byte, indexEntrySize)
  451. if _, err := t.index.ReadAt(buffer, int64(item*indexEntrySize)); err != nil {
  452. return 0, 0, 0, err
  453. }
  454. startIdx.unmarshalBinary(buffer)
  455. if _, err := t.index.ReadAt(buffer, int64((item+1)*indexEntrySize)); err != nil {
  456. return 0, 0, 0, err
  457. }
  458. endIdx.unmarshalBinary(buffer)
  459. if startIdx.filenum != endIdx.filenum {
  460. // If a piece of data 'crosses' a data-file,
  461. // it's actually in one piece on the second data-file.
  462. // We return a zero-indexEntry for the second file as start
  463. return 0, endIdx.offset, endIdx.filenum, nil
  464. }
  465. return startIdx.offset, endIdx.offset, endIdx.filenum, nil
  466. }
  467. // Retrieve looks up the data offset of an item with the given number and retrieves
  468. // the raw binary blob from the data file.
  469. func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
  470. // Ensure the table and the item is accessible
  471. if t.index == nil || t.head == nil {
  472. return nil, errClosed
  473. }
  474. if atomic.LoadUint64(&t.items) <= item {
  475. return nil, errOutOfBounds
  476. }
  477. // Ensure the item was not deleted from the tail either
  478. offset := atomic.LoadUint32(&t.itemOffset)
  479. if uint64(offset) > item {
  480. return nil, errOutOfBounds
  481. }
  482. t.lock.RLock()
  483. startOffset, endOffset, filenum, err := t.getBounds(item - uint64(offset))
  484. if err != nil {
  485. t.lock.RUnlock()
  486. return nil, err
  487. }
  488. dataFile, exist := t.files[filenum]
  489. if !exist {
  490. t.lock.RUnlock()
  491. return nil, fmt.Errorf("missing data file %d", filenum)
  492. }
  493. // Retrieve the data itself, decompress and return
  494. blob := make([]byte, endOffset-startOffset)
  495. if _, err := dataFile.ReadAt(blob, int64(startOffset)); err != nil {
  496. t.lock.RUnlock()
  497. return nil, err
  498. }
  499. t.lock.RUnlock()
  500. t.readMeter.Mark(int64(len(blob) + 2*indexEntrySize))
  501. if t.noCompression {
  502. return blob, nil
  503. }
  504. return snappy.Decode(nil, blob)
  505. }
  506. // has returns an indicator whether the specified number data
  507. // exists in the freezer table.
  508. func (t *freezerTable) has(number uint64) bool {
  509. return atomic.LoadUint64(&t.items) > number
  510. }
  511. // size returns the total data size in the freezer table.
  512. func (t *freezerTable) size() (uint64, error) {
  513. t.lock.RLock()
  514. defer t.lock.RUnlock()
  515. stat, err := t.index.Stat()
  516. if err != nil {
  517. return 0, err
  518. }
  519. total := uint64(t.maxFileSize)*uint64(t.headId-t.tailId) + uint64(t.headBytes) + uint64(stat.Size())
  520. return total, nil
  521. }
  522. // Sync pushes any pending data from memory out to disk. This is an expensive
  523. // operation, so use it with care.
  524. func (t *freezerTable) Sync() error {
  525. if err := t.index.Sync(); err != nil {
  526. return err
  527. }
  528. return t.head.Sync()
  529. }
  530. // printIndex is a debug print utility function for testing
  531. func (t *freezerTable) printIndex() {
  532. buf := make([]byte, indexEntrySize)
  533. fmt.Printf("|-----------------|\n")
  534. fmt.Printf("| fileno | offset |\n")
  535. fmt.Printf("|--------+--------|\n")
  536. for i := uint64(0); ; i++ {
  537. if _, err := t.index.ReadAt(buf, int64(i*indexEntrySize)); err != nil {
  538. break
  539. }
  540. var entry indexEntry
  541. entry.unmarshalBinary(buf)
  542. fmt.Printf("| %03d | %03d | \n", entry.filenum, entry.offset)
  543. if i > 100 {
  544. fmt.Printf(" ... \n")
  545. break
  546. }
  547. }
  548. fmt.Printf("|-----------------|\n")
  549. }