freezer_table.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  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.offset
  209. t.itemOffset = firstIndex.filenum
  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. if atomic.LoadUint64(&t.items) <= items {
  300. return nil
  301. }
  302. // We need to truncate, save the old size for metrics tracking
  303. oldSize, err := t.sizeNolock()
  304. if err != nil {
  305. return err
  306. }
  307. // Something's out of sync, truncate the table's offset index
  308. t.logger.Warn("Truncating freezer table", "items", t.items, "limit", items)
  309. if err := truncateFreezerFile(t.index, int64(items+1)*indexEntrySize); err != nil {
  310. return err
  311. }
  312. // Calculate the new expected size of the data file and truncate it
  313. buffer := make([]byte, indexEntrySize)
  314. if _, err := t.index.ReadAt(buffer, int64(items*indexEntrySize)); err != nil {
  315. return err
  316. }
  317. var expected indexEntry
  318. expected.unmarshalBinary(buffer)
  319. // We might need to truncate back to older files
  320. if expected.filenum != t.headId {
  321. // If already open for reading, force-reopen for writing
  322. t.releaseFile(expected.filenum)
  323. newHead, err := t.openFile(expected.filenum, openFreezerFileForAppend)
  324. if err != nil {
  325. return err
  326. }
  327. // Release any files _after the current head -- both the previous head
  328. // and any files which may have been opened for reading
  329. t.releaseFilesAfter(expected.filenum, true)
  330. // Set back the historic head
  331. t.head = newHead
  332. atomic.StoreUint32(&t.headId, expected.filenum)
  333. }
  334. if err := truncateFreezerFile(t.head, int64(expected.offset)); err != nil {
  335. return err
  336. }
  337. // All data files truncated, set internal counters and return
  338. atomic.StoreUint64(&t.items, items)
  339. atomic.StoreUint32(&t.headBytes, expected.offset)
  340. // Retrieve the new size and update the total size counter
  341. newSize, err := t.sizeNolock()
  342. if err != nil {
  343. return err
  344. }
  345. t.sizeGauge.Dec(int64(oldSize - newSize))
  346. return nil
  347. }
  348. // Close closes all opened files.
  349. func (t *freezerTable) Close() error {
  350. t.lock.Lock()
  351. defer t.lock.Unlock()
  352. var errs []error
  353. if err := t.index.Close(); err != nil {
  354. errs = append(errs, err)
  355. }
  356. t.index = nil
  357. for _, f := range t.files {
  358. if err := f.Close(); err != nil {
  359. errs = append(errs, err)
  360. }
  361. }
  362. t.head = nil
  363. if errs != nil {
  364. return fmt.Errorf("%v", errs)
  365. }
  366. return nil
  367. }
  368. // openFile assumes that the write-lock is held by the caller
  369. func (t *freezerTable) openFile(num uint32, opener func(string) (*os.File, error)) (f *os.File, err error) {
  370. var exist bool
  371. if f, exist = t.files[num]; !exist {
  372. var name string
  373. if t.noCompression {
  374. name = fmt.Sprintf("%s.%04d.rdat", t.name, num)
  375. } else {
  376. name = fmt.Sprintf("%s.%04d.cdat", t.name, num)
  377. }
  378. f, err = opener(filepath.Join(t.path, name))
  379. if err != nil {
  380. return nil, err
  381. }
  382. t.files[num] = f
  383. }
  384. return f, err
  385. }
  386. // releaseFile closes a file, and removes it from the open file cache.
  387. // Assumes that the caller holds the write lock
  388. func (t *freezerTable) releaseFile(num uint32) {
  389. if f, exist := t.files[num]; exist {
  390. delete(t.files, num)
  391. f.Close()
  392. }
  393. }
  394. // releaseFilesAfter closes all open files with a higher number, and optionally also deletes the files
  395. func (t *freezerTable) releaseFilesAfter(num uint32, remove bool) {
  396. for fnum, f := range t.files {
  397. if fnum > num {
  398. delete(t.files, fnum)
  399. f.Close()
  400. if remove {
  401. os.Remove(f.Name())
  402. }
  403. }
  404. }
  405. }
  406. // Append injects a binary blob at the end of the freezer table. The item number
  407. // is a precautionary parameter to ensure data correctness, but the table will
  408. // reject already existing data.
  409. //
  410. // Note, this method will *not* flush any data to disk so be sure to explicitly
  411. // fsync before irreversibly deleting data from the database.
  412. func (t *freezerTable) Append(item uint64, blob []byte) error {
  413. // Read lock prevents competition with truncate
  414. t.lock.RLock()
  415. // Ensure the table is still accessible
  416. if t.index == nil || t.head == nil {
  417. t.lock.RUnlock()
  418. return errClosed
  419. }
  420. // Ensure only the next item can be written, nothing else
  421. if atomic.LoadUint64(&t.items) != item {
  422. t.lock.RUnlock()
  423. return fmt.Errorf("appending unexpected item: want %d, have %d", t.items, item)
  424. }
  425. // Encode the blob and write it into the data file
  426. if !t.noCompression {
  427. blob = snappy.Encode(nil, blob)
  428. }
  429. bLen := uint32(len(blob))
  430. if t.headBytes+bLen < bLen ||
  431. t.headBytes+bLen > t.maxFileSize {
  432. // we need a new file, writing would overflow
  433. t.lock.RUnlock()
  434. t.lock.Lock()
  435. nextID := atomic.LoadUint32(&t.headId) + 1
  436. // We open the next file in truncated mode -- if this file already
  437. // exists, we need to start over from scratch on it
  438. newHead, err := t.openFile(nextID, openFreezerFileTruncated)
  439. if err != nil {
  440. t.lock.Unlock()
  441. return err
  442. }
  443. // Close old file, and reopen in RDONLY mode
  444. t.releaseFile(t.headId)
  445. t.openFile(t.headId, openFreezerFileForReadOnly)
  446. // Swap out the current head
  447. t.head = newHead
  448. atomic.StoreUint32(&t.headBytes, 0)
  449. atomic.StoreUint32(&t.headId, nextID)
  450. t.lock.Unlock()
  451. t.lock.RLock()
  452. }
  453. defer t.lock.RUnlock()
  454. if _, err := t.head.Write(blob); err != nil {
  455. return err
  456. }
  457. newOffset := atomic.AddUint32(&t.headBytes, bLen)
  458. idx := indexEntry{
  459. filenum: atomic.LoadUint32(&t.headId),
  460. offset: newOffset,
  461. }
  462. // Write indexEntry
  463. t.index.Write(idx.marshallBinary())
  464. t.writeMeter.Mark(int64(bLen + indexEntrySize))
  465. t.sizeGauge.Inc(int64(bLen + indexEntrySize))
  466. atomic.AddUint64(&t.items, 1)
  467. return nil
  468. }
  469. // getBounds returns the indexes for the item
  470. // returns start, end, filenumber and error
  471. func (t *freezerTable) getBounds(item uint64) (uint32, uint32, uint32, error) {
  472. var startIdx, endIdx indexEntry
  473. buffer := make([]byte, indexEntrySize)
  474. if _, err := t.index.ReadAt(buffer, int64(item*indexEntrySize)); err != nil {
  475. return 0, 0, 0, err
  476. }
  477. startIdx.unmarshalBinary(buffer)
  478. if _, err := t.index.ReadAt(buffer, int64((item+1)*indexEntrySize)); err != nil {
  479. return 0, 0, 0, err
  480. }
  481. endIdx.unmarshalBinary(buffer)
  482. if startIdx.filenum != endIdx.filenum {
  483. // If a piece of data 'crosses' a data-file,
  484. // it's actually in one piece on the second data-file.
  485. // We return a zero-indexEntry for the second file as start
  486. return 0, endIdx.offset, endIdx.filenum, nil
  487. }
  488. return startIdx.offset, endIdx.offset, endIdx.filenum, nil
  489. }
  490. // Retrieve looks up the data offset of an item with the given number and retrieves
  491. // the raw binary blob from the data file.
  492. func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
  493. // Ensure the table and the item is accessible
  494. if t.index == nil || t.head == nil {
  495. return nil, errClosed
  496. }
  497. if atomic.LoadUint64(&t.items) <= item {
  498. return nil, errOutOfBounds
  499. }
  500. // Ensure the item was not deleted from the tail either
  501. offset := atomic.LoadUint32(&t.itemOffset)
  502. if uint64(offset) > item {
  503. return nil, errOutOfBounds
  504. }
  505. t.lock.RLock()
  506. startOffset, endOffset, filenum, err := t.getBounds(item - uint64(offset))
  507. if err != nil {
  508. t.lock.RUnlock()
  509. return nil, err
  510. }
  511. dataFile, exist := t.files[filenum]
  512. if !exist {
  513. t.lock.RUnlock()
  514. return nil, fmt.Errorf("missing data file %d", filenum)
  515. }
  516. // Retrieve the data itself, decompress and return
  517. blob := make([]byte, endOffset-startOffset)
  518. if _, err := dataFile.ReadAt(blob, int64(startOffset)); err != nil {
  519. t.lock.RUnlock()
  520. return nil, err
  521. }
  522. t.lock.RUnlock()
  523. t.readMeter.Mark(int64(len(blob) + 2*indexEntrySize))
  524. if t.noCompression {
  525. return blob, nil
  526. }
  527. return snappy.Decode(nil, blob)
  528. }
  529. // has returns an indicator whether the specified number data
  530. // exists in the freezer table.
  531. func (t *freezerTable) has(number uint64) bool {
  532. return atomic.LoadUint64(&t.items) > number
  533. }
  534. // size returns the total data size in the freezer table.
  535. func (t *freezerTable) size() (uint64, error) {
  536. t.lock.RLock()
  537. defer t.lock.RUnlock()
  538. return t.sizeNolock()
  539. }
  540. // sizeNolock returns the total data size in the freezer table without obtaining
  541. // the mutex first.
  542. func (t *freezerTable) sizeNolock() (uint64, error) {
  543. stat, err := t.index.Stat()
  544. if err != nil {
  545. return 0, err
  546. }
  547. total := uint64(t.maxFileSize)*uint64(t.headId-t.tailId) + uint64(t.headBytes) + uint64(stat.Size())
  548. return total, nil
  549. }
  550. // Sync pushes any pending data from memory out to disk. This is an expensive
  551. // operation, so use it with care.
  552. func (t *freezerTable) Sync() error {
  553. if err := t.index.Sync(); err != nil {
  554. return err
  555. }
  556. return t.head.Sync()
  557. }
  558. // printIndex is a debug print utility function for testing
  559. func (t *freezerTable) printIndex() {
  560. buf := make([]byte, indexEntrySize)
  561. fmt.Printf("|-----------------|\n")
  562. fmt.Printf("| fileno | offset |\n")
  563. fmt.Printf("|--------+--------|\n")
  564. for i := uint64(0); ; i++ {
  565. if _, err := t.index.ReadAt(buf, int64(i*indexEntrySize)); err != nil {
  566. break
  567. }
  568. var entry indexEntry
  569. entry.unmarshalBinary(buf)
  570. fmt.Printf("| %03d | %03d | \n", entry.filenum, entry.offset)
  571. if i > 100 {
  572. fmt.Printf(" ... \n")
  573. break
  574. }
  575. }
  576. fmt.Printf("|-----------------|\n")
  577. }