freezer_table.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package rawdb
  17. import (
  18. "encoding/binary"
  19. "errors"
  20. "fmt"
  21. "os"
  22. "path/filepath"
  23. "sync"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/log"
  26. "github.com/ethereum/go-ethereum/metrics"
  27. "github.com/golang/snappy"
  28. )
  29. var (
  30. // errClosed is returned if an operation attempts to read from or write to the
  31. // freezer table after it has already been closed.
  32. errClosed = errors.New("closed")
  33. // errOutOfBounds is returned if the item requested is not contained within the
  34. // freezer table.
  35. errOutOfBounds = errors.New("out of bounds")
  36. )
  37. // freezerTable represents a single chained data table within the freezer (e.g. blocks).
  38. // It consists of a data file (snappy encoded arbitrary data blobs) and an index
  39. // file (uncompressed 64 bit indices into the data file).
  40. type freezerTable struct {
  41. content *os.File // File descriptor for the data content of the table
  42. offsets *os.File // File descriptor for the index file of the table
  43. items uint64 // Number of items stored in the table
  44. bytes uint64 // Number of content bytes stored in the table
  45. readMeter metrics.Meter // Meter for measuring the effective amount of data read
  46. writeMeter metrics.Meter // Meter for measuring the effective amount of data written
  47. logger log.Logger // Logger with database path and table name ambedded
  48. lock sync.RWMutex // Mutex protecting the data file descriptors
  49. }
  50. // newTable opens a freezer table, creating the data and index files if they are
  51. // non existent. Both files are truncated to the shortest common length to ensure
  52. // they don't go out of sync.
  53. func newTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter) (*freezerTable, error) {
  54. // Ensure the containing directory exists and open the two data files
  55. if err := os.MkdirAll(path, 0755); err != nil {
  56. return nil, err
  57. }
  58. content, err := os.OpenFile(filepath.Join(path, name+".dat"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  59. if err != nil {
  60. return nil, err
  61. }
  62. offsets, err := os.OpenFile(filepath.Join(path, name+".idx"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
  63. if err != nil {
  64. content.Close()
  65. return nil, err
  66. }
  67. // Create the table and repair any past inconsistency
  68. tab := &freezerTable{
  69. content: content,
  70. offsets: offsets,
  71. readMeter: readMeter,
  72. writeMeter: writeMeter,
  73. logger: log.New("database", path, "table", name),
  74. }
  75. if err := tab.repair(); err != nil {
  76. offsets.Close()
  77. content.Close()
  78. return nil, err
  79. }
  80. return tab, nil
  81. }
  82. // repair cross checks the content and the offsets file and truncates them to
  83. // be in sync with each other after a potential crash / data loss.
  84. func (t *freezerTable) repair() error {
  85. // Create a temporary offset buffer to init files with and read offsts into
  86. offset := make([]byte, 8)
  87. // If we've just created the files, initialize the offsets with the 0 index
  88. stat, err := t.offsets.Stat()
  89. if err != nil {
  90. return err
  91. }
  92. if stat.Size() == 0 {
  93. if _, err := t.offsets.Write(offset); err != nil {
  94. return err
  95. }
  96. }
  97. // Ensure the offsets are a multiple of 8 bytes
  98. if overflow := stat.Size() % 8; overflow != 0 {
  99. t.offsets.Truncate(stat.Size() - overflow) // New file can't trigger this path
  100. }
  101. // Retrieve the file sizes and prepare for truncation
  102. if stat, err = t.offsets.Stat(); err != nil {
  103. return err
  104. }
  105. offsetsSize := stat.Size()
  106. if stat, err = t.content.Stat(); err != nil {
  107. return err
  108. }
  109. contentSize := stat.Size()
  110. // Keep truncating both files until they come in sync
  111. t.offsets.ReadAt(offset, offsetsSize-8)
  112. contentExp := int64(binary.LittleEndian.Uint64(offset))
  113. for contentExp != contentSize {
  114. // Truncate the content file to the last offset pointer
  115. if contentExp < contentSize {
  116. t.logger.Warn("Truncating dangling content", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  117. if err := t.content.Truncate(contentExp); err != nil {
  118. return err
  119. }
  120. contentSize = contentExp
  121. }
  122. // Truncate the offsets to point within the content file
  123. if contentExp > contentSize {
  124. t.logger.Warn("Truncating dangling offsets", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
  125. if err := t.offsets.Truncate(offsetsSize - 8); err != nil {
  126. return err
  127. }
  128. offsetsSize -= 8
  129. t.offsets.ReadAt(offset, offsetsSize-8)
  130. contentExp = int64(binary.LittleEndian.Uint64(offset))
  131. }
  132. }
  133. // Ensure all reparation changes have been written to disk
  134. if err := t.offsets.Sync(); err != nil {
  135. return err
  136. }
  137. if err := t.content.Sync(); err != nil {
  138. return err
  139. }
  140. // Update the item and byte counters and return
  141. t.items = uint64(offsetsSize/8 - 1) // last index points to the end of the data file
  142. t.bytes = uint64(contentSize)
  143. t.logger.Debug("Chain freezer table opened", "items", t.items, "size", common.StorageSize(t.bytes))
  144. return nil
  145. }
  146. // truncate discards any recent data above the provided threashold number.
  147. func (t *freezerTable) truncate(items uint64) error {
  148. // If out item count is corrent, don't do anything
  149. if t.items <= items {
  150. return nil
  151. }
  152. // Something's out of sync, truncate the table's offset index
  153. t.logger.Warn("Truncating freezer table", "items", t.items, "limit", items)
  154. if err := t.offsets.Truncate(int64(items+1) * 8); err != nil {
  155. return err
  156. }
  157. // Calculate the new expected size of the data file and truncate it
  158. offset := make([]byte, 8)
  159. t.offsets.ReadAt(offset, int64(items)*8)
  160. expected := binary.LittleEndian.Uint64(offset)
  161. if err := t.content.Truncate(int64(expected)); err != nil {
  162. return err
  163. }
  164. // All data files truncated, set internal counters and return
  165. t.items, t.bytes = items, expected
  166. return nil
  167. }
  168. // Close unmaps all active memory mapped regions.
  169. func (t *freezerTable) Close() error {
  170. t.lock.Lock()
  171. defer t.lock.Unlock()
  172. var errs []error
  173. if err := t.offsets.Close(); err != nil {
  174. errs = append(errs, err)
  175. }
  176. t.offsets = nil
  177. if err := t.content.Close(); err != nil {
  178. errs = append(errs, err)
  179. }
  180. t.content = nil
  181. if errs != nil {
  182. return fmt.Errorf("%v", errs)
  183. }
  184. return nil
  185. }
  186. // Append injects a binary blob at the end of the freezer table. The item index
  187. // is a precautionary parameter to ensure data correctness, but the table will
  188. // reject already existing data.
  189. //
  190. // Note, this method will *not* flush any data to disk so be sure to explicitly
  191. // fsync before irreversibly deleting data from the database.
  192. func (t *freezerTable) Append(item uint64, blob []byte) error {
  193. // Ensure the table is still accessible
  194. if t.offsets == nil || t.content == nil {
  195. return errClosed
  196. }
  197. // Ensure only the next item can be written, nothing else
  198. if t.items != item {
  199. panic(fmt.Sprintf("appending unexpected item: want %d, have %d", t.items, item))
  200. }
  201. // Encode the blob and write it into the data file
  202. blob = snappy.Encode(nil, blob)
  203. if _, err := t.content.Write(blob); err != nil {
  204. return err
  205. }
  206. t.bytes += uint64(len(blob))
  207. offset := make([]byte, 8)
  208. binary.LittleEndian.PutUint64(offset, t.bytes)
  209. if _, err := t.offsets.Write(offset); err != nil {
  210. return err
  211. }
  212. t.items++
  213. t.writeMeter.Mark(int64(len(blob) + 8)) // 8 = 1 x 8 byte offset
  214. return nil
  215. }
  216. // Retrieve looks up the data offset of an item with the given index and retrieves
  217. // the raw binary blob from the data file.
  218. func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
  219. t.lock.RLock()
  220. defer t.lock.RUnlock()
  221. // Ensure the table and the item is accessible
  222. if t.offsets == nil || t.content == nil {
  223. return nil, errClosed
  224. }
  225. if t.items <= item {
  226. return nil, errOutOfBounds
  227. }
  228. // Item reachable, retrieve the data content boundaries
  229. offset := make([]byte, 8)
  230. if _, err := t.offsets.ReadAt(offset, int64(item*8)); err != nil {
  231. return nil, err
  232. }
  233. start := binary.LittleEndian.Uint64(offset)
  234. if _, err := t.offsets.ReadAt(offset, int64((item+1)*8)); err != nil {
  235. return nil, err
  236. }
  237. end := binary.LittleEndian.Uint64(offset)
  238. // Retrieve the data itself, decompress and return
  239. blob := make([]byte, end-start)
  240. if _, err := t.content.ReadAt(blob, int64(start)); err != nil {
  241. return nil, err
  242. }
  243. t.readMeter.Mark(int64(len(blob) + 16)) // 16 = 2 x 8 byte offset
  244. return snappy.Decode(nil, blob)
  245. }
  246. // Sync pushes any pending data from memory out to disk. This is an expensive
  247. // operation, so use it with care.
  248. func (t *freezerTable) Sync() error {
  249. if err := t.offsets.Sync(); err != nil {
  250. return err
  251. }
  252. return t.content.Sync()
  253. }