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