database.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. package ethdb
  17. import (
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "time"
  22. "github.com/ethereum/go-ethereum/log"
  23. "github.com/ethereum/go-ethereum/metrics"
  24. "github.com/syndtr/goleveldb/leveldb"
  25. "github.com/syndtr/goleveldb/leveldb/errors"
  26. "github.com/syndtr/goleveldb/leveldb/filter"
  27. "github.com/syndtr/goleveldb/leveldb/iterator"
  28. "github.com/syndtr/goleveldb/leveldb/opt"
  29. )
  30. var OpenFileLimit = 64
  31. type LDBDatabase struct {
  32. fn string // filename for reporting
  33. db *leveldb.DB // LevelDB instance
  34. getTimer metrics.Timer // Timer for measuring the database get request counts and latencies
  35. putTimer metrics.Timer // Timer for measuring the database put request counts and latencies
  36. delTimer metrics.Timer // Timer for measuring the database delete request counts and latencies
  37. missMeter metrics.Meter // Meter for measuring the missed database get requests
  38. readMeter metrics.Meter // Meter for measuring the database get request data usage
  39. writeMeter metrics.Meter // Meter for measuring the database put request data usage
  40. compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction
  41. compReadMeter metrics.Meter // Meter for measuring the data read during compaction
  42. compWriteMeter metrics.Meter // Meter for measuring the data written during compaction
  43. quitLock sync.Mutex // Mutex protecting the quit channel access
  44. quitChan chan chan error // Quit channel to stop the metrics collection before closing the database
  45. log log.Logger // Contextual logger tracking the database path
  46. }
  47. // NewLDBDatabase returns a LevelDB wrapped object.
  48. func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) {
  49. logger := log.New("database", file)
  50. // Ensure we have some minimal caching and file guarantees
  51. if cache < 16 {
  52. cache = 16
  53. }
  54. if handles < 16 {
  55. handles = 16
  56. }
  57. logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles)
  58. // Open the db and recover any potential corruptions
  59. db, err := leveldb.OpenFile(file, &opt.Options{
  60. OpenFilesCacheCapacity: handles,
  61. BlockCacheCapacity: cache / 2 * opt.MiB,
  62. WriteBuffer: cache / 4 * opt.MiB, // Two of these are used internally
  63. Filter: filter.NewBloomFilter(10),
  64. })
  65. if _, corrupted := err.(*errors.ErrCorrupted); corrupted {
  66. db, err = leveldb.RecoverFile(file, nil)
  67. }
  68. // (Re)check for errors and abort if opening of the db failed
  69. if err != nil {
  70. return nil, err
  71. }
  72. return &LDBDatabase{
  73. fn: file,
  74. db: db,
  75. log: logger,
  76. }, nil
  77. }
  78. // Path returns the path to the database directory.
  79. func (db *LDBDatabase) Path() string {
  80. return db.fn
  81. }
  82. // Put puts the given key / value to the queue
  83. func (db *LDBDatabase) Put(key []byte, value []byte) error {
  84. // Measure the database put latency, if requested
  85. if db.putTimer != nil {
  86. defer db.putTimer.UpdateSince(time.Now())
  87. }
  88. // Generate the data to write to disk, update the meter and write
  89. //value = rle.Compress(value)
  90. if db.writeMeter != nil {
  91. db.writeMeter.Mark(int64(len(value)))
  92. }
  93. return db.db.Put(key, value, nil)
  94. }
  95. func (db *LDBDatabase) Has(key []byte) (bool, error) {
  96. return db.db.Has(key, nil)
  97. }
  98. // Get returns the given key if it's present.
  99. func (db *LDBDatabase) Get(key []byte) ([]byte, error) {
  100. // Measure the database get latency, if requested
  101. if db.getTimer != nil {
  102. defer db.getTimer.UpdateSince(time.Now())
  103. }
  104. // Retrieve the key and increment the miss counter if not found
  105. dat, err := db.db.Get(key, nil)
  106. if err != nil {
  107. if db.missMeter != nil {
  108. db.missMeter.Mark(1)
  109. }
  110. return nil, err
  111. }
  112. // Otherwise update the actually retrieved amount of data
  113. if db.readMeter != nil {
  114. db.readMeter.Mark(int64(len(dat)))
  115. }
  116. return dat, nil
  117. //return rle.Decompress(dat)
  118. }
  119. // Delete deletes the key from the queue and database
  120. func (db *LDBDatabase) Delete(key []byte) error {
  121. // Measure the database delete latency, if requested
  122. if db.delTimer != nil {
  123. defer db.delTimer.UpdateSince(time.Now())
  124. }
  125. // Execute the actual operation
  126. return db.db.Delete(key, nil)
  127. }
  128. func (db *LDBDatabase) NewIterator() iterator.Iterator {
  129. return db.db.NewIterator(nil, nil)
  130. }
  131. func (db *LDBDatabase) Close() {
  132. // Stop the metrics collection to avoid internal database races
  133. db.quitLock.Lock()
  134. defer db.quitLock.Unlock()
  135. if db.quitChan != nil {
  136. errc := make(chan error)
  137. db.quitChan <- errc
  138. if err := <-errc; err != nil {
  139. db.log.Error("Metrics collection failed", "err", err)
  140. }
  141. }
  142. err := db.db.Close()
  143. if err == nil {
  144. db.log.Info("Database closed")
  145. } else {
  146. db.log.Error("Failed to close database", "err", err)
  147. }
  148. }
  149. func (db *LDBDatabase) LDB() *leveldb.DB {
  150. return db.db
  151. }
  152. // Meter configures the database metrics collectors and
  153. func (db *LDBDatabase) Meter(prefix string) {
  154. // Short circuit metering if the metrics system is disabled
  155. if !metrics.Enabled {
  156. return
  157. }
  158. // Initialize all the metrics collector at the requested prefix
  159. db.getTimer = metrics.NewRegisteredTimer(prefix+"user/gets", nil)
  160. db.putTimer = metrics.NewRegisteredTimer(prefix+"user/puts", nil)
  161. db.delTimer = metrics.NewRegisteredTimer(prefix+"user/dels", nil)
  162. db.missMeter = metrics.NewRegisteredMeter(prefix+"user/misses", nil)
  163. db.readMeter = metrics.NewRegisteredMeter(prefix+"user/reads", nil)
  164. db.writeMeter = metrics.NewRegisteredMeter(prefix+"user/writes", nil)
  165. db.compTimeMeter = metrics.NewRegisteredMeter(prefix+"compact/time", nil)
  166. db.compReadMeter = metrics.NewRegisteredMeter(prefix+"compact/input", nil)
  167. db.compWriteMeter = metrics.NewRegisteredMeter(prefix+"compact/output", nil)
  168. // Create a quit channel for the periodic collector and run it
  169. db.quitLock.Lock()
  170. db.quitChan = make(chan chan error)
  171. db.quitLock.Unlock()
  172. go db.meter(3 * time.Second)
  173. }
  174. // meter periodically retrieves internal leveldb counters and reports them to
  175. // the metrics subsystem.
  176. //
  177. // This is how a stats table look like (currently):
  178. // Compactions
  179. // Level | Tables | Size(MB) | Time(sec) | Read(MB) | Write(MB)
  180. // -------+------------+---------------+---------------+---------------+---------------
  181. // 0 | 0 | 0.00000 | 1.27969 | 0.00000 | 12.31098
  182. // 1 | 85 | 109.27913 | 28.09293 | 213.92493 | 214.26294
  183. // 2 | 523 | 1000.37159 | 7.26059 | 66.86342 | 66.77884
  184. // 3 | 570 | 1113.18458 | 0.00000 | 0.00000 | 0.00000
  185. func (db *LDBDatabase) meter(refresh time.Duration) {
  186. // Create the counters to store current and previous values
  187. counters := make([][]float64, 2)
  188. for i := 0; i < 2; i++ {
  189. counters[i] = make([]float64, 3)
  190. }
  191. // Iterate ad infinitum and collect the stats
  192. for i := 1; ; i++ {
  193. // Retrieve the database stats
  194. stats, err := db.db.GetProperty("leveldb.stats")
  195. if err != nil {
  196. db.log.Error("Failed to read database stats", "err", err)
  197. return
  198. }
  199. // Find the compaction table, skip the header
  200. lines := strings.Split(stats, "\n")
  201. for len(lines) > 0 && strings.TrimSpace(lines[0]) != "Compactions" {
  202. lines = lines[1:]
  203. }
  204. if len(lines) <= 3 {
  205. db.log.Error("Compaction table not found")
  206. return
  207. }
  208. lines = lines[3:]
  209. // Iterate over all the table rows, and accumulate the entries
  210. for j := 0; j < len(counters[i%2]); j++ {
  211. counters[i%2][j] = 0
  212. }
  213. for _, line := range lines {
  214. parts := strings.Split(line, "|")
  215. if len(parts) != 6 {
  216. break
  217. }
  218. for idx, counter := range parts[3:] {
  219. value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64)
  220. if err != nil {
  221. db.log.Error("Compaction entry parsing failed", "err", err)
  222. return
  223. }
  224. counters[i%2][idx] += value
  225. }
  226. }
  227. // Update all the requested meters
  228. if db.compTimeMeter != nil {
  229. db.compTimeMeter.Mark(int64((counters[i%2][0] - counters[(i-1)%2][0]) * 1000 * 1000 * 1000))
  230. }
  231. if db.compReadMeter != nil {
  232. db.compReadMeter.Mark(int64((counters[i%2][1] - counters[(i-1)%2][1]) * 1024 * 1024))
  233. }
  234. if db.compWriteMeter != nil {
  235. db.compWriteMeter.Mark(int64((counters[i%2][2] - counters[(i-1)%2][2]) * 1024 * 1024))
  236. }
  237. // Sleep a bit, then repeat the stats collection
  238. select {
  239. case errc := <-db.quitChan:
  240. // Quit requesting, stop hammering the database
  241. errc <- nil
  242. return
  243. case <-time.After(refresh):
  244. // Timeout, gather a new set of stats
  245. }
  246. }
  247. }
  248. func (db *LDBDatabase) NewBatch() Batch {
  249. return &ldbBatch{db: db.db, b: new(leveldb.Batch)}
  250. }
  251. type ldbBatch struct {
  252. db *leveldb.DB
  253. b *leveldb.Batch
  254. size int
  255. }
  256. func (b *ldbBatch) Put(key, value []byte) error {
  257. b.b.Put(key, value)
  258. b.size += len(value)
  259. return nil
  260. }
  261. func (b *ldbBatch) Write() error {
  262. return b.db.Write(b.b, nil)
  263. }
  264. func (b *ldbBatch) ValueSize() int {
  265. return b.size
  266. }
  267. func (b *ldbBatch) Reset() {
  268. b.b.Reset()
  269. b.size = 0
  270. }
  271. type table struct {
  272. db Database
  273. prefix string
  274. }
  275. // NewTable returns a Database object that prefixes all keys with a given
  276. // string.
  277. func NewTable(db Database, prefix string) Database {
  278. return &table{
  279. db: db,
  280. prefix: prefix,
  281. }
  282. }
  283. func (dt *table) Put(key []byte, value []byte) error {
  284. return dt.db.Put(append([]byte(dt.prefix), key...), value)
  285. }
  286. func (dt *table) Has(key []byte) (bool, error) {
  287. return dt.db.Has(append([]byte(dt.prefix), key...))
  288. }
  289. func (dt *table) Get(key []byte) ([]byte, error) {
  290. return dt.db.Get(append([]byte(dt.prefix), key...))
  291. }
  292. func (dt *table) Delete(key []byte) error {
  293. return dt.db.Delete(append([]byte(dt.prefix), key...))
  294. }
  295. func (dt *table) Close() {
  296. // Do nothing; don't close the underlying DB.
  297. }
  298. type tableBatch struct {
  299. batch Batch
  300. prefix string
  301. }
  302. // NewTableBatch returns a Batch object which prefixes all keys with a given string.
  303. func NewTableBatch(db Database, prefix string) Batch {
  304. return &tableBatch{db.NewBatch(), prefix}
  305. }
  306. func (dt *table) NewBatch() Batch {
  307. return &tableBatch{dt.db.NewBatch(), dt.prefix}
  308. }
  309. func (tb *tableBatch) Put(key, value []byte) error {
  310. return tb.batch.Put(append([]byte(tb.prefix), key...), value)
  311. }
  312. func (tb *tableBatch) Write() error {
  313. return tb.batch.Write()
  314. }
  315. func (tb *tableBatch) ValueSize() int {
  316. return tb.batch.ValueSize()
  317. }
  318. func (tb *tableBatch) Reset() {
  319. tb.batch.Reset()
  320. }