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