leveldb.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Copyright 2014 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. // +build !js
  17. // Package leveldb implements the key-value database layer based on LevelDB.
  18. package leveldb
  19. import (
  20. "fmt"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/ethdb"
  27. "github.com/ethereum/go-ethereum/log"
  28. "github.com/ethereum/go-ethereum/metrics"
  29. "github.com/syndtr/goleveldb/leveldb"
  30. "github.com/syndtr/goleveldb/leveldb/errors"
  31. "github.com/syndtr/goleveldb/leveldb/filter"
  32. "github.com/syndtr/goleveldb/leveldb/opt"
  33. "github.com/syndtr/goleveldb/leveldb/util"
  34. )
  35. const (
  36. // leveldbDegradationWarnInterval specifies how often warning should be printed
  37. // if the leveldb database cannot keep up with requested writes.
  38. leveldbDegradationWarnInterval = time.Minute
  39. // leveldbMinCache is the minimum amount of memory in megabytes to allocate to
  40. // leveldb read and write caching, split half and half.
  41. leveldbMinCache = 16
  42. // leveldbMinHandles is the minimum number of files handles to allocate to the
  43. // open database files.
  44. leveldbMinHandles = 16
  45. // metricsGatheringInterval specifies the interval to retrieve leveldb database
  46. // compaction, io and pause stats to report to the user.
  47. metricsGatheringInterval = 3 * time.Second
  48. )
  49. // LevelDBDatabase is a persistent key-value store. Apart from basic data storage
  50. // functionality it also supports batch writes and iterating over the keyspace in
  51. // binary-alphabetical order.
  52. type LevelDBDatabase struct {
  53. fn string // filename for reporting
  54. db *leveldb.DB // LevelDB instance
  55. compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction
  56. compReadMeter metrics.Meter // Meter for measuring the data read during compaction
  57. compWriteMeter metrics.Meter // Meter for measuring the data written during compaction
  58. writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction
  59. writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction
  60. diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read
  61. diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written
  62. quitLock sync.Mutex // Mutex protecting the quit channel access
  63. quitChan chan chan error // Quit channel to stop the metrics collection before closing the database
  64. log log.Logger // Contextual logger tracking the database path
  65. }
  66. // New returns a wrapped LevelDB object. The namespace is the prefix that the
  67. // metrics reporting should use for surfacing internal stats.
  68. func New(file string, cache int, handles int, namespace string) (*LevelDBDatabase, error) {
  69. // Ensure we have some minimal caching and file guarantees
  70. if cache < leveldbMinCache {
  71. cache = leveldbMinCache
  72. }
  73. if handles < leveldbMinHandles {
  74. handles = leveldbMinHandles
  75. }
  76. logger := log.New("database", file)
  77. logger.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*1024*1024), "handles", handles)
  78. // Open the db and recover any potential corruptions
  79. db, err := leveldb.OpenFile(file, &opt.Options{
  80. OpenFilesCacheCapacity: handles,
  81. BlockCacheCapacity: cache / 2 * opt.MiB,
  82. WriteBuffer: cache / 4 * opt.MiB, // Two of these are used internally
  83. Filter: filter.NewBloomFilter(10),
  84. })
  85. if _, corrupted := err.(*errors.ErrCorrupted); corrupted {
  86. db, err = leveldb.RecoverFile(file, nil)
  87. }
  88. if err != nil {
  89. return nil, err
  90. }
  91. // Assemble the wrapper with all the registered metrics
  92. ldb := &LevelDBDatabase{
  93. fn: file,
  94. db: db,
  95. log: logger,
  96. quitChan: make(chan chan error),
  97. }
  98. ldb.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil)
  99. ldb.compReadMeter = metrics.NewRegisteredMeter(namespace+"compact/input", nil)
  100. ldb.compWriteMeter = metrics.NewRegisteredMeter(namespace+"compact/output", nil)
  101. ldb.diskReadMeter = metrics.NewRegisteredMeter(namespace+"disk/read", nil)
  102. ldb.diskWriteMeter = metrics.NewRegisteredMeter(namespace+"disk/write", nil)
  103. ldb.writeDelayMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/duration", nil)
  104. ldb.writeDelayNMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/counter", nil)
  105. // Start up the metrics gathering and return
  106. go ldb.meter(metricsGatheringInterval)
  107. return ldb, nil
  108. }
  109. // Close stops the metrics collection, flushes any pending data to disk and closes
  110. // all io accesses to the underlying key-value store.
  111. func (db *LevelDBDatabase) Close() error {
  112. db.quitLock.Lock()
  113. defer db.quitLock.Unlock()
  114. if db.quitChan != nil {
  115. errc := make(chan error)
  116. db.quitChan <- errc
  117. if err := <-errc; err != nil {
  118. db.log.Error("Metrics collection failed", "err", err)
  119. }
  120. db.quitChan = nil
  121. }
  122. return db.db.Close()
  123. }
  124. // Has retrieves if a key is present in the key-value store.
  125. func (db *LevelDBDatabase) Has(key []byte) (bool, error) {
  126. return db.db.Has(key, nil)
  127. }
  128. // Get retrieves the given key if it's present in the key-value store.
  129. func (db *LevelDBDatabase) Get(key []byte) ([]byte, error) {
  130. dat, err := db.db.Get(key, nil)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return dat, nil
  135. }
  136. // Put inserts the given value into the key-value store.
  137. func (db *LevelDBDatabase) Put(key []byte, value []byte) error {
  138. return db.db.Put(key, value, nil)
  139. }
  140. // Delete removes the key from the key-value store.
  141. func (db *LevelDBDatabase) Delete(key []byte) error {
  142. return db.db.Delete(key, nil)
  143. }
  144. // NewBatch creates a write-only key-value store that buffers changes to its host
  145. // database until a final write is called.
  146. func (db *LevelDBDatabase) NewBatch() ethdb.Batch {
  147. return &levelDBBatch{
  148. db: db.db,
  149. b: new(leveldb.Batch),
  150. }
  151. }
  152. // NewIterator creates a binary-alphabetical iterator over the entire keyspace
  153. // contained within the leveldb database.
  154. func (db *LevelDBDatabase) NewIterator() ethdb.Iterator {
  155. return db.NewIteratorWithPrefix(nil)
  156. }
  157. // NewIteratorWithPrefix creates a binary-alphabetical iterator over a subset
  158. // of database content with a particular key prefix.
  159. func (db *LevelDBDatabase) NewIteratorWithPrefix(prefix []byte) ethdb.Iterator {
  160. return db.db.NewIterator(util.BytesPrefix(prefix), nil)
  161. }
  162. // Stat returns a particular internal stat of the database.
  163. func (db *LevelDBDatabase) Stat(property string) (string, error) {
  164. return db.db.GetProperty(property)
  165. }
  166. // Compact flattens the underlying data store for the given key range. In essence,
  167. // deleted and overwritten versions are discarded, and the data is rearranged to
  168. // reduce the cost of operations needed to access them.
  169. //
  170. // A nil start is treated as a key before all keys in the data store; a nil limit
  171. // is treated as a key after all keys in the data store. If both is nil then it
  172. // will compact entire data store.
  173. func (db *LevelDBDatabase) Compact(start []byte, limit []byte) error {
  174. return db.db.CompactRange(util.Range{Start: start, Limit: limit})
  175. }
  176. // Path returns the path to the database directory.
  177. func (db *LevelDBDatabase) Path() string {
  178. return db.fn
  179. }
  180. // meter periodically retrieves internal leveldb counters and reports them to
  181. // the metrics subsystem.
  182. //
  183. // This is how a LevelDB stats table looks like (currently):
  184. // Compactions
  185. // Level | Tables | Size(MB) | Time(sec) | Read(MB) | Write(MB)
  186. // -------+------------+---------------+---------------+---------------+---------------
  187. // 0 | 0 | 0.00000 | 1.27969 | 0.00000 | 12.31098
  188. // 1 | 85 | 109.27913 | 28.09293 | 213.92493 | 214.26294
  189. // 2 | 523 | 1000.37159 | 7.26059 | 66.86342 | 66.77884
  190. // 3 | 570 | 1113.18458 | 0.00000 | 0.00000 | 0.00000
  191. //
  192. // This is how the write delay look like (currently):
  193. // DelayN:5 Delay:406.604657ms Paused: false
  194. //
  195. // This is how the iostats look like (currently):
  196. // Read(MB):3895.04860 Write(MB):3654.64712
  197. func (db *LevelDBDatabase) meter(refresh time.Duration) {
  198. // Create the counters to store current and previous compaction values
  199. compactions := make([][]float64, 2)
  200. for i := 0; i < 2; i++ {
  201. compactions[i] = make([]float64, 3)
  202. }
  203. // Create storage for iostats.
  204. var iostats [2]float64
  205. // Create storage and warning log tracer for write delay.
  206. var (
  207. delaystats [2]int64
  208. lastWritePaused time.Time
  209. )
  210. var (
  211. errc chan error
  212. merr error
  213. )
  214. // Iterate ad infinitum and collect the stats
  215. for i := 1; errc == nil && merr == nil; i++ {
  216. // Retrieve the database stats
  217. stats, err := db.db.GetProperty("leveldb.stats")
  218. if err != nil {
  219. db.log.Error("Failed to read database stats", "err", err)
  220. merr = err
  221. continue
  222. }
  223. // Find the compaction table, skip the header
  224. lines := strings.Split(stats, "\n")
  225. for len(lines) > 0 && strings.TrimSpace(lines[0]) != "Compactions" {
  226. lines = lines[1:]
  227. }
  228. if len(lines) <= 3 {
  229. db.log.Error("Compaction leveldbTable not found")
  230. merr = errors.New("compaction leveldbTable not found")
  231. continue
  232. }
  233. lines = lines[3:]
  234. // Iterate over all the leveldbTable rows, and accumulate the entries
  235. for j := 0; j < len(compactions[i%2]); j++ {
  236. compactions[i%2][j] = 0
  237. }
  238. for _, line := range lines {
  239. parts := strings.Split(line, "|")
  240. if len(parts) != 6 {
  241. break
  242. }
  243. for idx, counter := range parts[3:] {
  244. value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64)
  245. if err != nil {
  246. db.log.Error("Compaction entry parsing failed", "err", err)
  247. merr = err
  248. continue
  249. }
  250. compactions[i%2][idx] += value
  251. }
  252. }
  253. // Update all the requested meters
  254. if db.compTimeMeter != nil {
  255. db.compTimeMeter.Mark(int64((compactions[i%2][0] - compactions[(i-1)%2][0]) * 1000 * 1000 * 1000))
  256. }
  257. if db.compReadMeter != nil {
  258. db.compReadMeter.Mark(int64((compactions[i%2][1] - compactions[(i-1)%2][1]) * 1024 * 1024))
  259. }
  260. if db.compWriteMeter != nil {
  261. db.compWriteMeter.Mark(int64((compactions[i%2][2] - compactions[(i-1)%2][2]) * 1024 * 1024))
  262. }
  263. // Retrieve the write delay statistic
  264. writedelay, err := db.db.GetProperty("leveldb.writedelay")
  265. if err != nil {
  266. db.log.Error("Failed to read database write delay statistic", "err", err)
  267. merr = err
  268. continue
  269. }
  270. var (
  271. delayN int64
  272. delayDuration string
  273. duration time.Duration
  274. paused bool
  275. )
  276. if n, err := fmt.Sscanf(writedelay, "DelayN:%d Delay:%s Paused:%t", &delayN, &delayDuration, &paused); n != 3 || err != nil {
  277. db.log.Error("Write delay statistic not found")
  278. merr = err
  279. continue
  280. }
  281. duration, err = time.ParseDuration(delayDuration)
  282. if err != nil {
  283. db.log.Error("Failed to parse delay duration", "err", err)
  284. merr = err
  285. continue
  286. }
  287. if db.writeDelayNMeter != nil {
  288. db.writeDelayNMeter.Mark(delayN - delaystats[0])
  289. }
  290. if db.writeDelayMeter != nil {
  291. db.writeDelayMeter.Mark(duration.Nanoseconds() - delaystats[1])
  292. }
  293. // If a warning that db is performing compaction has been displayed, any subsequent
  294. // warnings will be withheld for one minute not to overwhelm the user.
  295. if paused && delayN-delaystats[0] == 0 && duration.Nanoseconds()-delaystats[1] == 0 &&
  296. time.Now().After(lastWritePaused.Add(leveldbDegradationWarnInterval)) {
  297. db.log.Warn("Database compacting, degraded performance")
  298. lastWritePaused = time.Now()
  299. }
  300. delaystats[0], delaystats[1] = delayN, duration.Nanoseconds()
  301. // Retrieve the database iostats.
  302. ioStats, err := db.db.GetProperty("leveldb.iostats")
  303. if err != nil {
  304. db.log.Error("Failed to read database iostats", "err", err)
  305. merr = err
  306. continue
  307. }
  308. var nRead, nWrite float64
  309. parts := strings.Split(ioStats, " ")
  310. if len(parts) < 2 {
  311. db.log.Error("Bad syntax of ioStats", "ioStats", ioStats)
  312. merr = fmt.Errorf("bad syntax of ioStats %s", ioStats)
  313. continue
  314. }
  315. if n, err := fmt.Sscanf(parts[0], "Read(MB):%f", &nRead); n != 1 || err != nil {
  316. db.log.Error("Bad syntax of read entry", "entry", parts[0])
  317. merr = err
  318. continue
  319. }
  320. if n, err := fmt.Sscanf(parts[1], "Write(MB):%f", &nWrite); n != 1 || err != nil {
  321. db.log.Error("Bad syntax of write entry", "entry", parts[1])
  322. merr = err
  323. continue
  324. }
  325. if db.diskReadMeter != nil {
  326. db.diskReadMeter.Mark(int64((nRead - iostats[0]) * 1024 * 1024))
  327. }
  328. if db.diskWriteMeter != nil {
  329. db.diskWriteMeter.Mark(int64((nWrite - iostats[1]) * 1024 * 1024))
  330. }
  331. iostats[0], iostats[1] = nRead, nWrite
  332. // Sleep a bit, then repeat the stats collection
  333. select {
  334. case errc = <-db.quitChan:
  335. // Quit requesting, stop hammering the database
  336. case <-time.After(refresh):
  337. // Timeout, gather a new set of stats
  338. }
  339. }
  340. if errc == nil {
  341. errc = <-db.quitChan
  342. }
  343. errc <- merr
  344. }
  345. // levelDBBatch is a write-only leveldb batch that commits changes to its host
  346. // database when Write is called. A batch cannot be used concurrently.
  347. type levelDBBatch struct {
  348. db *leveldb.DB
  349. b *leveldb.Batch
  350. size int
  351. }
  352. // Put inserts the given value into the batch for later committing.
  353. func (b *levelDBBatch) Put(key, value []byte) error {
  354. b.b.Put(key, value)
  355. b.size += len(value)
  356. return nil
  357. }
  358. // Delete inserts the a key removal into the batch for later committing.
  359. func (b *levelDBBatch) Delete(key []byte) error {
  360. b.b.Delete(key)
  361. b.size += 1
  362. return nil
  363. }
  364. // ValueSize retrieves the amount of data queued up for writing.
  365. func (b *levelDBBatch) ValueSize() int {
  366. return b.size
  367. }
  368. // Write flushes any accumulated data to disk.
  369. func (b *levelDBBatch) Write() error {
  370. return b.db.Write(b.b, nil)
  371. }
  372. // Reset resets the batch for reuse.
  373. func (b *levelDBBatch) Reset() {
  374. b.b.Reset()
  375. b.size = 0
  376. }