github.com/unicornultrafoundation/go-u2u@v1.0.0-rc1.0.20240205080301-e74a83d3fadc/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 "sync" 25 "time" 26 27 "github.com/syndtr/goleveldb/leveldb" 28 "github.com/syndtr/goleveldb/leveldb/errors" 29 "github.com/syndtr/goleveldb/leveldb/filter" 30 "github.com/syndtr/goleveldb/leveldb/opt" 31 "github.com/syndtr/goleveldb/leveldb/util" 32 "github.com/unicornultrafoundation/go-u2u/common" 33 "github.com/unicornultrafoundation/go-u2u/ethdb" 34 "github.com/unicornultrafoundation/go-u2u/log" 35 "github.com/unicornultrafoundation/go-u2u/metrics" 36 ) 37 38 const ( 39 // degradationWarnInterval specifies how often warning should be printed if the 40 // leveldb database cannot keep up with requested writes. 41 degradationWarnInterval = time.Minute 42 43 // minCache is the minimum amount of memory in megabytes to allocate to leveldb 44 // read and write caching, split half and half. 45 minCache = 16 46 47 // minHandles is the minimum number of files handles to allocate to the open 48 // database files. 49 minHandles = 16 50 51 // metricsGatheringInterval specifies the interval to retrieve leveldb database 52 // compaction, io and pause stats to report to the user. 53 metricsGatheringInterval = 3 * time.Second 54 ) 55 56 // Database is a persistent key-value store. Apart from basic data storage 57 // functionality it also supports batch writes and iterating over the keyspace in 58 // binary-alphabetical order. 59 type Database struct { 60 fn string // filename for reporting 61 db *leveldb.DB // LevelDB instance 62 63 compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction 64 compReadMeter metrics.Meter // Meter for measuring the data read during compaction 65 compWriteMeter metrics.Meter // Meter for measuring the data written during compaction 66 writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction 67 writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction 68 diskSizeGauge metrics.Gauge // Gauge for tracking the size of all the levels in the database 69 diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read 70 diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written 71 memCompGauge metrics.Gauge // Gauge for tracking the number of memory compaction 72 level0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in level0 73 nonlevel0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in non0 level 74 seekCompGauge metrics.Gauge // Gauge for tracking the number of table compaction caused by read opt 75 76 quitLock sync.Mutex // Mutex protecting the quit channel access 77 quitChan chan chan error // Quit channel to stop the metrics collection before closing the database 78 79 log log.Logger // Contextual logger tracking the database path 80 } 81 82 // New returns a wrapped LevelDB object. The namespace is the prefix that the 83 // metrics reporting should use for surfacing internal stats. 84 func New(file string, cache int, handles int, namespace string, readonly bool) (*Database, error) { 85 return NewCustom(file, namespace, func(options *opt.Options) { 86 // Ensure we have some minimal caching and file guarantees 87 if cache < minCache { 88 cache = minCache 89 } 90 if handles < minHandles { 91 handles = minHandles 92 } 93 // Set default options 94 options.OpenFilesCacheCapacity = handles 95 options.BlockCacheCapacity = cache / 2 * opt.MiB 96 options.WriteBuffer = cache / 4 * opt.MiB // Two of these are used internally 97 if readonly { 98 options.ReadOnly = true 99 } 100 }) 101 } 102 103 // NewCustom returns a wrapped LevelDB object. The namespace is the prefix that the 104 // metrics reporting should use for surfacing internal stats. 105 // The customize function allows the caller to modify the leveldb options. 106 func NewCustom(file string, namespace string, customize func(options *opt.Options)) (*Database, error) { 107 options := configureOptions(customize) 108 logger := log.New("database", file) 109 usedCache := options.GetBlockCacheCapacity() + options.GetWriteBuffer()*2 110 logCtx := []interface{}{"cache", common.StorageSize(usedCache), "handles", options.GetOpenFilesCacheCapacity()} 111 if options.ReadOnly { 112 logCtx = append(logCtx, "readonly", "true") 113 } 114 logger.Info("Allocated cache and file handles", logCtx...) 115 116 // Open the db and recover any potential corruptions 117 db, err := leveldb.OpenFile(file, options) 118 if _, corrupted := err.(*errors.ErrCorrupted); corrupted { 119 db, err = leveldb.RecoverFile(file, nil) 120 } 121 if err != nil { 122 return nil, err 123 } 124 // Assemble the wrapper with all the registered metrics 125 ldb := &Database{ 126 fn: file, 127 db: db, 128 log: logger, 129 quitChan: make(chan chan error), 130 } 131 ldb.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil) 132 ldb.compReadMeter = metrics.NewRegisteredMeter(namespace+"compact/input", nil) 133 ldb.compWriteMeter = metrics.NewRegisteredMeter(namespace+"compact/output", nil) 134 ldb.diskSizeGauge = metrics.NewRegisteredGauge(namespace+"disk/size", nil) 135 ldb.diskReadMeter = metrics.NewRegisteredMeter(namespace+"disk/read", nil) 136 ldb.diskWriteMeter = metrics.NewRegisteredMeter(namespace+"disk/write", nil) 137 ldb.writeDelayMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/duration", nil) 138 ldb.writeDelayNMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/counter", nil) 139 ldb.memCompGauge = metrics.NewRegisteredGauge(namespace+"compact/memory", nil) 140 ldb.level0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/level0", nil) 141 ldb.nonlevel0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/nonlevel0", nil) 142 ldb.seekCompGauge = metrics.NewRegisteredGauge(namespace+"compact/seek", nil) 143 144 // Start up the metrics gathering and return 145 go ldb.meter(metricsGatheringInterval) 146 return ldb, nil 147 } 148 149 // configureOptions sets some default options, then runs the provided setter. 150 func configureOptions(customizeFn func(*opt.Options)) *opt.Options { 151 // Set default options 152 options := &opt.Options{ 153 Filter: filter.NewBloomFilter(10), 154 DisableSeeksCompaction: true, 155 } 156 // Allow caller to make custom modifications to the options 157 if customizeFn != nil { 158 customizeFn(options) 159 } 160 return options 161 } 162 163 // Close stops the metrics collection, flushes any pending data to disk and closes 164 // all io accesses to the underlying key-value store. 165 func (db *Database) Close() error { 166 db.quitLock.Lock() 167 defer db.quitLock.Unlock() 168 169 if db.quitChan != nil { 170 errc := make(chan error) 171 db.quitChan <- errc 172 if err := <-errc; err != nil { 173 db.log.Error("Metrics collection failed", "err", err) 174 } 175 db.quitChan = nil 176 } 177 return db.db.Close() 178 } 179 180 // Has retrieves if a key is present in the key-value store. 181 func (db *Database) Has(key []byte) (bool, error) { 182 return db.db.Has(key, nil) 183 } 184 185 // Get retrieves the given key if it's present in the key-value store. 186 func (db *Database) Get(key []byte) ([]byte, error) { 187 dat, err := db.db.Get(key, nil) 188 if err != nil { 189 return nil, err 190 } 191 return dat, nil 192 } 193 194 // Put inserts the given value into the key-value store. 195 func (db *Database) Put(key []byte, value []byte) error { 196 return db.db.Put(key, value, nil) 197 } 198 199 // Delete removes the key from the key-value store. 200 func (db *Database) Delete(key []byte) error { 201 return db.db.Delete(key, nil) 202 } 203 204 // NewBatch creates a write-only key-value store that buffers changes to its host 205 // database until a final write is called. 206 func (db *Database) NewBatch() ethdb.Batch { 207 return &batch{ 208 db: db.db, 209 b: new(leveldb.Batch), 210 } 211 } 212 213 // NewIterator creates a binary-alphabetical iterator over a subset 214 // of database content with a particular key prefix, starting at a particular 215 // initial key (or after, if it does not exist). 216 func (db *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { 217 return db.db.NewIterator(bytesPrefixRange(prefix, start), nil) 218 } 219 220 // Stat returns a particular internal stat of the database. 221 func (db *Database) Stat(property string) (string, error) { 222 return db.db.GetProperty(property) 223 } 224 225 // Compact flattens the underlying data store for the given key range. In essence, 226 // deleted and overwritten versions are discarded, and the data is rearranged to 227 // reduce the cost of operations needed to access them. 228 // 229 // A nil start is treated as a key before all keys in the data store; a nil limit 230 // is treated as a key after all keys in the data store. If both is nil then it 231 // will compact entire data store. 232 func (db *Database) Compact(start []byte, limit []byte) error { 233 return db.db.CompactRange(util.Range{Start: start, Limit: limit}) 234 } 235 236 // Path returns the path to the database directory. 237 func (db *Database) Path() string { 238 return db.fn 239 } 240 241 // meter periodically retrieves internal leveldb counters and reports them to 242 // the metrics subsystem. 243 func (db *Database) meter(refresh time.Duration) { 244 // Create the counters to store current and previous compaction values 245 compactions := make([][]int64, 2) 246 for i := 0; i < 2; i++ { 247 compactions[i] = make([]int64, 4) 248 } 249 // Create storage for iostats. 250 var iostats [2]uint64 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 timer := time.NewTimer(refresh) 264 defer timer.Stop() 265 266 // Iterate ad infinitum and collect the stats 267 for i := 1; errc == nil && merr == nil; i++ { 268 // Retrieve the database stats 269 var stats = &leveldb.DBStats{} 270 err := db.db.Stats(stats) 271 if err != nil { 272 db.log.Error("Failed to read database stats", "err", err) 273 merr = err 274 continue 275 } 276 compactions[i%2][0] = stats.LevelSizes.Sum() 277 compactions[i%2][2] = stats.LevelRead.Sum() 278 compactions[i%2][3] = stats.LevelWrite.Sum() 279 280 compactions[i%2][1] = 0 281 for _, s := range stats.LevelDurations { 282 compactions[i%2][1] += int64(s.Seconds()) 283 } 284 285 // Update all the requested meters 286 if db.diskSizeGauge != nil { 287 db.diskSizeGauge.Update(compactions[i%2][0] * 1024 * 1024) 288 } 289 if db.compTimeMeter != nil { 290 db.compTimeMeter.Mark((compactions[i%2][1] - compactions[(i-1)%2][1]) * 1000 * 1000 * 1000) 291 } 292 if db.compReadMeter != nil { 293 db.compReadMeter.Mark((compactions[i%2][2] - compactions[(i-1)%2][2]) * 1024 * 1024) 294 } 295 if db.compWriteMeter != nil { 296 db.compWriteMeter.Mark((compactions[i%2][3] - compactions[(i-1)%2][3]) * 1024 * 1024) 297 } 298 // Retrieve the write delay statistic 299 var ( 300 delayN int64 301 duration time.Duration 302 ) 303 delayN = int64(stats.WriteDelayCount) 304 duration = stats.WriteDelayDuration 305 if db.writeDelayNMeter != nil { 306 db.writeDelayNMeter.Mark(delayN - delaystats[0]) 307 } 308 if db.writeDelayMeter != nil { 309 db.writeDelayMeter.Mark(duration.Nanoseconds() - delaystats[1]) 310 } 311 // If a warning that db is performing compaction has been displayed, any subsequent 312 // warnings will be withheld for one minute not to overwhelm the user. 313 if stats.WritePaused && delayN-delaystats[0] == 0 && duration.Nanoseconds()-delaystats[1] == 0 && 314 time.Now().After(lastWritePaused.Add(degradationWarnInterval)) { 315 db.log.Warn("Database compacting, degraded performance") 316 lastWritePaused = time.Now() 317 } 318 delaystats[0], delaystats[1] = delayN, duration.Nanoseconds() 319 320 // Retrieve the database iostats. 321 nRead := stats.IORead 322 nWrite := stats.IOWrite 323 if db.diskReadMeter != nil { 324 db.diskReadMeter.Mark(int64((nRead - iostats[0]) * 1024 * 1024)) 325 } 326 if db.diskWriteMeter != nil { 327 db.diskWriteMeter.Mark(int64((nWrite - iostats[1]) * 1024 * 1024)) 328 } 329 iostats[0], iostats[1] = nRead, nWrite 330 331 db.memCompGauge.Update(int64(stats.MemComp)) 332 db.level0CompGauge.Update(int64(stats.Level0Comp)) 333 db.nonlevel0CompGauge.Update(int64(stats.NonLevel0Comp)) 334 db.seekCompGauge.Update(int64(stats.SeekComp)) 335 336 // Sleep a bit, then repeat the stats collection 337 select { 338 case errc = <-db.quitChan: 339 // Quit requesting, stop hammering the database 340 case <-timer.C: 341 timer.Reset(refresh) 342 // Timeout, gather a new set of stats 343 } 344 } 345 346 if errc == nil { 347 errc = <-db.quitChan 348 } 349 errc <- merr 350 } 351 352 // batch is a write-only leveldb batch that commits changes to its host database 353 // when Write is called. A batch cannot be used concurrently. 354 type batch struct { 355 db *leveldb.DB 356 b *leveldb.Batch 357 size int 358 } 359 360 // Put inserts the given value into the batch for later committing. 361 func (b *batch) Put(key, value []byte) error { 362 b.b.Put(key, value) 363 b.size += len(value) 364 return nil 365 } 366 367 // Delete inserts the a key removal into the batch for later committing. 368 func (b *batch) Delete(key []byte) error { 369 b.b.Delete(key) 370 b.size += len(key) 371 return nil 372 } 373 374 // ValueSize retrieves the amount of data queued up for writing. 375 func (b *batch) ValueSize() int { 376 return b.size 377 } 378 379 // Write flushes any accumulated data to disk. 380 func (b *batch) Write() error { 381 return b.db.Write(b.b, nil) 382 } 383 384 // Reset resets the batch for reuse. 385 func (b *batch) Reset() { 386 b.b.Reset() 387 b.size = 0 388 } 389 390 // Replay replays the batch contents. 391 func (b *batch) Replay(w ethdb.KeyValueWriter) error { 392 return b.b.Replay(&replayer{writer: w}) 393 } 394 395 // replayer is a small wrapper to implement the correct replay methods. 396 type replayer struct { 397 writer ethdb.KeyValueWriter 398 failure error 399 } 400 401 // Put inserts the given value into the key-value data store. 402 func (r *replayer) Put(key, value []byte) { 403 // If the replay already failed, stop executing ops 404 if r.failure != nil { 405 return 406 } 407 r.failure = r.writer.Put(key, value) 408 } 409 410 // Delete removes the key from the key-value data store. 411 func (r *replayer) Delete(key []byte) { 412 // If the replay already failed, stop executing ops 413 if r.failure != nil { 414 return 415 } 416 r.failure = r.writer.Delete(key) 417 } 418 419 // bytesPrefixRange returns key range that satisfy 420 // - the given prefix, and 421 // - the given seek position 422 func bytesPrefixRange(prefix, start []byte) *util.Range { 423 r := util.BytesPrefix(prefix) 424 r.Start = append(r.Start, start...) 425 return r 426 }