freezer_table.go 18 KB

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