freezer_table.go 21 KB

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