database.go 11 KB

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