freezer_table.go 20 KB

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