freezer_table.go 21 KB

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