database.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. "fmt"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/ethereum/go-ethereum/log"
  24. "github.com/ethereum/go-ethereum/metrics"
  25. "github.com/syndtr/goleveldb/leveldb"
  26. "github.com/syndtr/goleveldb/leveldb/errors"
  27. "github.com/syndtr/goleveldb/leveldb/filter"
  28. "github.com/syndtr/goleveldb/leveldb/iterator"
  29. "github.com/syndtr/goleveldb/leveldb/opt"
  30. "github.com/syndtr/goleveldb/leveldb/util"
  31. )
  32. const (
  33. writeDelayNThreshold = 200
  34. writeDelayThreshold = 350 * time.Millisecond
  35. writeDelayWarningThrottler = 1 * time.Minute
  36. )
  37. var OpenFileLimit = 64
  38. type LDBDatabase struct {
  39. fn string // filename for reporting
  40. db *leveldb.DB // LevelDB instance
  41. compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction
  42. compReadMeter metrics.Meter // Meter for measuring the data read during compaction
  43. compWriteMeter metrics.Meter // Meter for measuring the data written during compaction
  44. writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction
  45. writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction
  46. diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read
  47. diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written
  48. quitLock sync.Mutex // Mutex protecting the quit channel access
  49. quitChan chan chan error // Quit channel to stop the metrics collection before closing the database
  50. log log.Logger // Contextual logger tracking the database path
  51. }
  52. // NewLDBDatabase returns a LevelDB wrapped object.
  53. func NewLDBDatabase(file string, cache int, handles int) (*LDBDatabase, error) {
  54. logger := log.New("database", file)
  55. // Ensure we have some minimal caching and file guarantees
  56. if cache < 16 {
  57. cache = 16
  58. }
  59. if handles < 16 {
  60. handles = 16
  61. }
  62. logger.Info("Allocated cache and file handles", "cache", cache, "handles", handles)
  63. // Open the db and recover any potential corruptions
  64. db, err := leveldb.OpenFile(file, &opt.Options{
  65. OpenFilesCacheCapacity: handles,
  66. BlockCacheCapacity: cache / 2 * opt.MiB,
  67. WriteBuffer: cache / 4 * opt.MiB, // Two of these are used internally
  68. Filter: filter.NewBloomFilter(10),
  69. })
  70. if _, corrupted := err.(*errors.ErrCorrupted); corrupted {
  71. db, err = leveldb.RecoverFile(file, nil)
  72. }
  73. // (Re)check for errors and abort if opening of the db failed
  74. if err != nil {
  75. return nil, err
  76. }
  77. return &LDBDatabase{
  78. fn: file,
  79. db: db,
  80. log: logger,
  81. }, nil
  82. }
  83. // Path returns the path to the database directory.
  84. func (db *LDBDatabase) Path() string {
  85. return db.fn
  86. }
  87. // Put puts the given key / value to the queue
  88. func (db *LDBDatabase) Put(key []byte, value []byte) error {
  89. return db.db.Put(key, value, nil)
  90. }
  91. func (db *LDBDatabase) Has(key []byte) (bool, error) {
  92. return db.db.Has(key, nil)
  93. }
  94. // Get returns the given key if it's present.
  95. func (db *LDBDatabase) Get(key []byte) ([]byte, error) {
  96. dat, err := db.db.Get(key, nil)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return dat, nil
  101. }
  102. // Delete deletes the key from the queue and database
  103. func (db *LDBDatabase) Delete(key []byte) error {
  104. return db.db.Delete(key, nil)
  105. }
  106. func (db *LDBDatabase) NewIterator() iterator.Iterator {
  107. return db.db.NewIterator(nil, nil)
  108. }
  109. // NewIteratorWithPrefix returns a iterator to iterate over subset of database content with a particular prefix.
  110. func (db *LDBDatabase) NewIteratorWithPrefix(prefix []byte) iterator.Iterator {
  111. return db.db.NewIterator(util.BytesPrefix(prefix), nil)
  112. }
  113. func (db *LDBDatabase) Close() {
  114. // Stop the metrics collection to avoid internal database races
  115. db.quitLock.Lock()
  116. defer db.quitLock.Unlock()
  117. if db.quitChan != nil {
  118. errc := make(chan error)
  119. db.quitChan <- errc
  120. if err := <-errc; err != nil {
  121. db.log.Error("Metrics collection failed", "err", err)
  122. }
  123. }
  124. err := db.db.Close()
  125. if err == nil {
  126. db.log.Info("Database closed")
  127. } else {
  128. db.log.Error("Failed to close database", "err", err)
  129. }
  130. }
  131. func (db *LDBDatabase) LDB() *leveldb.DB {
  132. return db.db
  133. }
  134. // Meter configures the database metrics collectors and
  135. func (db *LDBDatabase) Meter(prefix string) {
  136. if metrics.Enabled {
  137. // Initialize all the metrics collector at the requested prefix
  138. db.compTimeMeter = metrics.NewRegisteredMeter(prefix+"compact/time", nil)
  139. db.compReadMeter = metrics.NewRegisteredMeter(prefix+"compact/input", nil)
  140. db.compWriteMeter = metrics.NewRegisteredMeter(prefix+"compact/output", nil)
  141. db.diskReadMeter = metrics.NewRegisteredMeter(prefix+"disk/read", nil)
  142. db.diskWriteMeter = metrics.NewRegisteredMeter(prefix+"disk/write", nil)
  143. }
  144. // Initialize write delay metrics no matter we are in metric mode or not.
  145. db.writeDelayMeter = metrics.NewRegisteredMeter(prefix+"compact/writedelay/duration", nil)
  146. db.writeDelayNMeter = metrics.NewRegisteredMeter(prefix+"compact/writedelay/counter", nil)
  147. // Create a quit channel for the periodic collector and run it
  148. db.quitLock.Lock()
  149. db.quitChan = make(chan chan error)
  150. db.quitLock.Unlock()
  151. go db.meter(3 * time.Second)
  152. }
  153. // meter periodically retrieves internal leveldb counters and reports them to
  154. // the metrics subsystem.
  155. //
  156. // This is how a stats table look like (currently):
  157. // Compactions
  158. // Level | Tables | Size(MB) | Time(sec) | Read(MB) | Write(MB)
  159. // -------+------------+---------------+---------------+---------------+---------------
  160. // 0 | 0 | 0.00000 | 1.27969 | 0.00000 | 12.31098
  161. // 1 | 85 | 109.27913 | 28.09293 | 213.92493 | 214.26294
  162. // 2 | 523 | 1000.37159 | 7.26059 | 66.86342 | 66.77884
  163. // 3 | 570 | 1113.18458 | 0.00000 | 0.00000 | 0.00000
  164. //
  165. // This is how the write delay look like (currently):
  166. // DelayN:5 Delay:406.604657ms
  167. //
  168. // This is how the iostats look like (currently):
  169. // Read(MB):3895.04860 Write(MB):3654.64712
  170. func (db *LDBDatabase) meter(refresh time.Duration) {
  171. // Create the counters to store current and previous compaction values
  172. compactions := make([][]float64, 2)
  173. for i := 0; i < 2; i++ {
  174. compactions[i] = make([]float64, 3)
  175. }
  176. // Create storage for iostats.
  177. var iostats [2]float64
  178. // Create storage and warning log tracer for write delay.
  179. var (
  180. delaystats [2]int64
  181. lastWriteDelay time.Time
  182. lastWriteDelayN time.Time
  183. lastWritePaused time.Time
  184. )
  185. // Iterate ad infinitum and collect the stats
  186. for i := 1; ; i++ {
  187. // Retrieve the database stats
  188. stats, err := db.db.GetProperty("leveldb.stats")
  189. if err != nil {
  190. db.log.Error("Failed to read database stats", "err", err)
  191. return
  192. }
  193. // Find the compaction table, skip the header
  194. lines := strings.Split(stats, "\n")
  195. for len(lines) > 0 && strings.TrimSpace(lines[0]) != "Compactions" {
  196. lines = lines[1:]
  197. }
  198. if len(lines) <= 3 {
  199. db.log.Error("Compaction table not found")
  200. return
  201. }
  202. lines = lines[3:]
  203. // Iterate over all the table rows, and accumulate the entries
  204. for j := 0; j < len(compactions[i%2]); j++ {
  205. compactions[i%2][j] = 0
  206. }
  207. for _, line := range lines {
  208. parts := strings.Split(line, "|")
  209. if len(parts) != 6 {
  210. break
  211. }
  212. for idx, counter := range parts[3:] {
  213. value, err := strconv.ParseFloat(strings.TrimSpace(counter), 64)
  214. if err != nil {
  215. db.log.Error("Compaction entry parsing failed", "err", err)
  216. return
  217. }
  218. compactions[i%2][idx] += value
  219. }
  220. }
  221. // Update all the requested meters
  222. if db.compTimeMeter != nil {
  223. db.compTimeMeter.Mark(int64((compactions[i%2][0] - compactions[(i-1)%2][0]) * 1000 * 1000 * 1000))
  224. }
  225. if db.compReadMeter != nil {
  226. db.compReadMeter.Mark(int64((compactions[i%2][1] - compactions[(i-1)%2][1]) * 1024 * 1024))
  227. }
  228. if db.compWriteMeter != nil {
  229. db.compWriteMeter.Mark(int64((compactions[i%2][2] - compactions[(i-1)%2][2]) * 1024 * 1024))
  230. }
  231. // Retrieve the write delay statistic
  232. writedelay, err := db.db.GetProperty("leveldb.writedelay")
  233. if err != nil {
  234. db.log.Error("Failed to read database write delay statistic", "err", err)
  235. return
  236. }
  237. var (
  238. delayN int64
  239. delayDuration string
  240. duration time.Duration
  241. paused bool
  242. )
  243. if n, err := fmt.Sscanf(writedelay, "DelayN:%d Delay:%s Paused:%t", &delayN, &delayDuration, &paused); n != 3 || err != nil {
  244. db.log.Error("Write delay statistic not found")
  245. return
  246. }
  247. duration, err = time.ParseDuration(delayDuration)
  248. if err != nil {
  249. db.log.Error("Failed to parse delay duration", "err", err)
  250. return
  251. }
  252. if db.writeDelayNMeter != nil {
  253. db.writeDelayNMeter.Mark(delayN - delaystats[0])
  254. // If the write delay number been collected in the last minute exceeds the predefined threshold,
  255. // print a warning log here.
  256. // If a warning that db performance is laggy has been displayed,
  257. // any subsequent warnings will be withhold for 1 minute to don't overwhelm the user.
  258. if int(db.writeDelayNMeter.Rate1()) > writeDelayNThreshold &&
  259. time.Now().After(lastWriteDelayN.Add(writeDelayWarningThrottler)) {
  260. db.log.Warn("Write delay number exceeds the threshold (200 per second) in the last minute")
  261. lastWriteDelayN = time.Now()
  262. }
  263. }
  264. if db.writeDelayMeter != nil {
  265. db.writeDelayMeter.Mark(duration.Nanoseconds() - delaystats[1])
  266. // If the write delay duration been collected in the last minute exceeds the predefined threshold,
  267. // print a warning log here.
  268. // If a warning that db performance is laggy has been displayed,
  269. // any subsequent warnings will be withhold for 1 minute to don't overwhelm the user.
  270. if int64(db.writeDelayMeter.Rate1()) > writeDelayThreshold.Nanoseconds() &&
  271. time.Now().After(lastWriteDelay.Add(writeDelayWarningThrottler)) {
  272. db.log.Warn("Write delay duration exceeds the threshold (35% of the time) in the last minute")
  273. lastWriteDelay = time.Now()
  274. }
  275. }
  276. // If a warning that db is performing compaction has been displayed, any subsequent
  277. // warnings will be withheld for one minute not to overwhelm the user.
  278. if paused && delayN-delaystats[0] == 0 && duration.Nanoseconds()-delaystats[1] == 0 &&
  279. time.Now().After(lastWritePaused.Add(writeDelayWarningThrottler)) {
  280. db.log.Warn("Database compacting, degraded performance")
  281. lastWritePaused = time.Now()
  282. }
  283. delaystats[0], delaystats[1] = delayN, duration.Nanoseconds()
  284. // Retrieve the database iostats.
  285. ioStats, err := db.db.GetProperty("leveldb.iostats")
  286. if err != nil {
  287. db.log.Error("Failed to read database iostats", "err", err)
  288. return
  289. }
  290. parts := strings.Split(ioStats, " ")
  291. if len(parts) < 2 {
  292. db.log.Error("Bad syntax of ioStats", "ioStats", ioStats)
  293. return
  294. }
  295. r := strings.Split(parts[0], ":")
  296. if len(r) < 2 {
  297. db.log.Error("Bad syntax of read entry", "entry", parts[0])
  298. return
  299. }
  300. read, err := strconv.ParseFloat(r[1], 64)
  301. if err != nil {
  302. db.log.Error("Read entry parsing failed", "err", err)
  303. return
  304. }
  305. w := strings.Split(parts[1], ":")
  306. if len(w) < 2 {
  307. db.log.Error("Bad syntax of write entry", "entry", parts[1])
  308. return
  309. }
  310. write, err := strconv.ParseFloat(w[1], 64)
  311. if err != nil {
  312. db.log.Error("Write entry parsing failed", "err", err)
  313. return
  314. }
  315. if db.diskReadMeter != nil {
  316. db.diskReadMeter.Mark(int64((read - iostats[0]) * 1024 * 1024))
  317. }
  318. if db.diskWriteMeter != nil {
  319. db.diskWriteMeter.Mark(int64((write - iostats[1]) * 1024 * 1024))
  320. }
  321. iostats[0] = read
  322. iostats[1] = write
  323. // Sleep a bit, then repeat the stats collection
  324. select {
  325. case errc := <-db.quitChan:
  326. // Quit requesting, stop hammering the database
  327. errc <- nil
  328. return
  329. case <-time.After(refresh):
  330. // Timeout, gather a new set of stats
  331. }
  332. }
  333. }
  334. func (db *LDBDatabase) NewBatch() Batch {
  335. return &ldbBatch{db: db.db, b: new(leveldb.Batch)}
  336. }
  337. type ldbBatch struct {
  338. db *leveldb.DB
  339. b *leveldb.Batch
  340. size int
  341. }
  342. func (b *ldbBatch) Put(key, value []byte) error {
  343. b.b.Put(key, value)
  344. b.size += len(value)
  345. return nil
  346. }
  347. func (b *ldbBatch) Write() error {
  348. return b.db.Write(b.b, nil)
  349. }
  350. func (b *ldbBatch) ValueSize() int {
  351. return b.size
  352. }
  353. func (b *ldbBatch) Reset() {
  354. b.b.Reset()
  355. b.size = 0
  356. }
  357. type table struct {
  358. db Database
  359. prefix string
  360. }
  361. // NewTable returns a Database object that prefixes all keys with a given
  362. // string.
  363. func NewTable(db Database, prefix string) Database {
  364. return &table{
  365. db: db,
  366. prefix: prefix,
  367. }
  368. }
  369. func (dt *table) Put(key []byte, value []byte) error {
  370. return dt.db.Put(append([]byte(dt.prefix), key...), value)
  371. }
  372. func (dt *table) Has(key []byte) (bool, error) {
  373. return dt.db.Has(append([]byte(dt.prefix), key...))
  374. }
  375. func (dt *table) Get(key []byte) ([]byte, error) {
  376. return dt.db.Get(append([]byte(dt.prefix), key...))
  377. }
  378. func (dt *table) Delete(key []byte) error {
  379. return dt.db.Delete(append([]byte(dt.prefix), key...))
  380. }
  381. func (dt *table) Close() {
  382. // Do nothing; don't close the underlying DB.
  383. }
  384. type tableBatch struct {
  385. batch Batch
  386. prefix string
  387. }
  388. // NewTableBatch returns a Batch object which prefixes all keys with a given string.
  389. func NewTableBatch(db Database, prefix string) Batch {
  390. return &tableBatch{db.NewBatch(), prefix}
  391. }
  392. func (dt *table) NewBatch() Batch {
  393. return &tableBatch{dt.db.NewBatch(), dt.prefix}
  394. }
  395. func (tb *tableBatch) Put(key, value []byte) error {
  396. return tb.batch.Put(append([]byte(tb.prefix), key...), value)
  397. }
  398. func (tb *tableBatch) Write() error {
  399. return tb.batch.Write()
  400. }
  401. func (tb *tableBatch) ValueSize() int {
  402. return tb.batch.ValueSize()
  403. }
  404. func (tb *tableBatch) Reset() {
  405. tb.batch.Reset()
  406. }