freezer_table.go 18 KB

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