github.com/dominant-strategies/go-quai@v0.28.2/ethdb/pebble/pebble.go (about) 1 // Copyright 2023 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 (arm64 || amd64) && !openbsd 18 19 // Package pebble implements the key-value database layer based on pebble. 20 package pebble 21 22 import ( 23 "bytes" 24 "fmt" 25 "runtime" 26 "sync" 27 "sync/atomic" 28 "time" 29 30 "github.com/cockroachdb/pebble" 31 "github.com/cockroachdb/pebble/bloom" 32 "github.com/dominant-strategies/go-quai/common" 33 "github.com/dominant-strategies/go-quai/ethdb" 34 "github.com/dominant-strategies/go-quai/log" 35 "github.com/dominant-strategies/go-quai/metrics" 36 ) 37 38 const ( 39 // minCache is the minimum amount of memory in megabytes to allocate to pebble 40 // read and write caching, split half and half. 41 minCache = 16 42 43 // minHandles is the minimum number of files handles to allocate to the open 44 // database files. 45 minHandles = 16 46 47 // metricsGatheringInterval specifies the interval to retrieve pebble database 48 // compaction, io and pause stats to report to the user. 49 metricsGatheringInterval = 3 * time.Second 50 ) 51 52 // Database is a persistent key-value store based on the pebble storage engine. 53 // Apart from basic data storage functionality it also supports batch writes and 54 // iterating over the keyspace in binary-alphabetical order. 55 type Database struct { 56 fn string // filename for reporting 57 db *pebble.DB // Underlying pebble storage engine 58 59 compTimeMeter metrics.Meter // Meter for measuring the total time spent in database compaction 60 compReadMeter metrics.Meter // Meter for measuring the data read during compaction 61 compWriteMeter metrics.Meter // Meter for measuring the data written during compaction 62 writeDelayNMeter metrics.Meter // Meter for measuring the write delay number due to database compaction 63 writeDelayMeter metrics.Meter // Meter for measuring the write delay duration due to database compaction 64 diskSizeGauge metrics.Gauge // Gauge for tracking the size of all the levels in the database 65 diskReadMeter metrics.Meter // Meter for measuring the effective amount of data read 66 diskWriteMeter metrics.Meter // Meter for measuring the effective amount of data written 67 memCompGauge metrics.Gauge // Gauge for tracking the number of memory compaction 68 level0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in level0 69 nonlevel0CompGauge metrics.Gauge // Gauge for tracking the number of table compaction in non0 level 70 seekCompGauge metrics.Gauge // Gauge for tracking the number of table compaction caused by read opt 71 manualMemAllocGauge metrics.Gauge // Gauge for tracking amount of non-managed memory currently allocated 72 73 quitLock sync.RWMutex // Mutex protecting the quit channel and the closed flag 74 quitChan chan chan error // Quit channel to stop the metrics collection before closing the database 75 closed bool // keep track of whether we're Closed 76 77 log log.Logger // Contextual logger tracking the database path 78 79 activeComp int // Current number of active compactions 80 compStartTime time.Time // The start time of the earliest currently-active compaction 81 compTime atomic.Int64 // Total time spent in compaction in ns 82 level0Comp atomic.Uint32 // Total number of level-zero compactions 83 nonLevel0Comp atomic.Uint32 // Total number of non level-zero compactions 84 writeDelayStartTime time.Time // The start time of the latest write stall 85 writeDelayCount atomic.Int64 // Total number of write stall counts 86 writeDelayTime atomic.Int64 // Total time spent in write stalls 87 } 88 89 func (d *Database) onCompactionBegin(info pebble.CompactionInfo) { 90 if d.activeComp == 0 { 91 d.compStartTime = time.Now() 92 } 93 l0 := info.Input[0] 94 if l0.Level == 0 { 95 d.level0Comp.Add(1) 96 } else { 97 d.nonLevel0Comp.Add(1) 98 } 99 d.activeComp++ 100 } 101 102 func (d *Database) onCompactionEnd(info pebble.CompactionInfo) { 103 if d.activeComp == 1 { 104 d.compTime.Add(int64(time.Since(d.compStartTime))) 105 } else if d.activeComp == 0 { 106 panic("should not happen") 107 } 108 d.activeComp-- 109 } 110 111 func (d *Database) onWriteStallBegin(b pebble.WriteStallBeginInfo) { 112 d.writeDelayStartTime = time.Now() 113 } 114 115 func (d *Database) onWriteStallEnd() { 116 d.writeDelayTime.Add(int64(time.Since(d.writeDelayStartTime))) 117 } 118 119 // New returns a wrapped pebble DB object. The namespace is the prefix that the 120 // metrics reporting should use for surfacing internal stats. 121 func New(file string, cache int, handles int, namespace string, readonly bool) (*Database, error) { 122 // Ensure we have some minimal caching and file guarantees 123 if cache < minCache { 124 cache = minCache 125 } 126 if handles < minHandles { 127 handles = minHandles 128 } 129 log.Info("Allocated cache and file handles", "cache", common.StorageSize(cache*1024*1024), "handles", handles) 130 131 // The max memtable size is limited by the uint32 offsets stored in 132 // internal/arenaskl.node, DeferredBatchOp, and flushableBatchEntry. 133 // Taken from https://github.com/cockroachdb/pebble/blob/master/open.go#L38 134 maxMemTableSize := 4<<30 - 1 // Capped by 4 GB 135 136 // Two memory tables is configured which is identical to leveldb, 137 // including a frozen memory table and another live one. 138 memTableLimit := 2 139 memTableSize := cache * 1024 * 1024 / 2 / memTableLimit 140 if memTableSize > maxMemTableSize { 141 memTableSize = maxMemTableSize 142 } 143 db := &Database{ 144 fn: file, 145 log: log.Log, 146 quitChan: make(chan chan error), 147 } 148 opt := &pebble.Options{ 149 // Pebble has a single combined cache area and the write 150 // buffers are taken from this too. Assign all available 151 // memory allowance for cache. 152 Cache: pebble.NewCache(int64(cache * 1024 * 1024)), 153 MaxOpenFiles: handles, 154 155 // The size of memory table(as well as the write buffer). 156 // Note, there may have more than two memory tables in the system. 157 MemTableSize: memTableSize, 158 159 // MemTableStopWritesThreshold places a hard limit on the size 160 // of the existent MemTables(including the frozen one). 161 // Note, this must be the number of tables not the size of all memtables 162 // according to https://github.com/cockroachdb/pebble/blob/master/options.go#L738-L742 163 // and to https://github.com/cockroachdb/pebble/blob/master/db.go#L1892-L1903. 164 MemTableStopWritesThreshold: memTableLimit, 165 166 // The default compaction concurrency(1 thread), 167 // Here use all available CPUs for faster compaction. 168 MaxConcurrentCompactions: func() int { return runtime.NumCPU() }, 169 170 // Per-level options. Options for at least one level must be specified. The 171 // options for the last level are used for all subsequent levels. 172 Levels: []pebble.LevelOptions{ 173 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 174 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 175 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 176 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 177 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 178 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 179 {TargetFileSize: 2 * 1024 * 1024, FilterPolicy: bloom.FilterPolicy(10)}, 180 }, 181 ReadOnly: readonly, 182 EventListener: &pebble.EventListener{ 183 CompactionBegin: db.onCompactionBegin, 184 CompactionEnd: db.onCompactionEnd, 185 WriteStallBegin: db.onWriteStallBegin, 186 WriteStallEnd: db.onWriteStallEnd, 187 }, 188 } 189 // Disable seek compaction explicitly. Check https://github.com/ethereum/go-ethereum/pull/20130 190 // for more details. 191 opt.Experimental.ReadSamplingMultiplier = -1 192 193 // Open the db and recover any potential corruptions 194 innerDB, err := pebble.Open(file, opt) 195 if err != nil { 196 return nil, err 197 } 198 db.db = innerDB 199 200 db.compTimeMeter = metrics.NewRegisteredMeter(namespace+"compact/time", nil) 201 db.compReadMeter = metrics.NewRegisteredMeter(namespace+"compact/input", nil) 202 db.compWriteMeter = metrics.NewRegisteredMeter(namespace+"compact/output", nil) 203 db.diskSizeGauge = metrics.NewRegisteredGauge(namespace+"disk/size", nil) 204 db.diskReadMeter = metrics.NewRegisteredMeter(namespace+"disk/read", nil) 205 db.diskWriteMeter = metrics.NewRegisteredMeter(namespace+"disk/write", nil) 206 db.writeDelayMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/duration", nil) 207 db.writeDelayNMeter = metrics.NewRegisteredMeter(namespace+"compact/writedelay/counter", nil) 208 db.memCompGauge = metrics.NewRegisteredGauge(namespace+"compact/memory", nil) 209 db.level0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/level0", nil) 210 db.nonlevel0CompGauge = metrics.NewRegisteredGauge(namespace+"compact/nonlevel0", nil) 211 db.seekCompGauge = metrics.NewRegisteredGauge(namespace+"compact/seek", nil) 212 db.manualMemAllocGauge = metrics.NewRegisteredGauge(namespace+"memory/manualalloc", nil) 213 214 // Start up the metrics gathering and return 215 go db.meter(metricsGatheringInterval) 216 return db, nil 217 } 218 219 // Close stops the metrics collection, flushes any pending data to disk and closes 220 // all io accesses to the underlying key-value store. 221 func (d *Database) Close() error { 222 d.quitLock.Lock() 223 defer d.quitLock.Unlock() 224 // Allow double closing, simplifies things 225 if d.closed { 226 return nil 227 } 228 d.closed = true 229 if d.quitChan != nil { 230 errc := make(chan error) 231 d.quitChan <- errc 232 if err := <-errc; err != nil { 233 d.log.Error("Metrics collection failed", "err", err) 234 } 235 d.quitChan = nil 236 } 237 return d.db.Close() 238 } 239 240 // Has retrieves if a key is present in the key-value store. 241 func (d *Database) Has(key []byte) (bool, error) { 242 d.quitLock.RLock() 243 defer d.quitLock.RUnlock() 244 if d.closed { 245 return false, pebble.ErrClosed 246 } 247 _, closer, err := d.db.Get(key) 248 if err == pebble.ErrNotFound { 249 return false, nil 250 } else if err != nil { 251 return false, err 252 } 253 closer.Close() 254 return true, nil 255 } 256 257 // Get retrieves the given key if it's present in the key-value store. 258 func (d *Database) Get(key []byte) ([]byte, error) { 259 d.quitLock.RLock() 260 defer d.quitLock.RUnlock() 261 if d.closed { 262 return nil, pebble.ErrClosed 263 } 264 dat, closer, err := d.db.Get(key) 265 if err != nil { 266 return nil, err 267 } 268 ret := make([]byte, len(dat)) 269 copy(ret, dat) 270 closer.Close() 271 return ret, nil 272 } 273 274 // Put inserts the given value into the key-value store. 275 func (d *Database) Put(key []byte, value []byte) error { 276 d.quitLock.RLock() 277 defer d.quitLock.RUnlock() 278 if d.closed { 279 return pebble.ErrClosed 280 } 281 return d.db.Set(key, value, pebble.Sync) 282 } 283 284 // Delete removes the key from the key-value store. 285 func (d *Database) Delete(key []byte) error { 286 d.quitLock.RLock() 287 defer d.quitLock.RUnlock() 288 if d.closed { 289 return pebble.ErrClosed 290 } 291 return d.db.Delete(key, nil) 292 } 293 294 // NewBatch creates a write-only key-value store that buffers changes to its host 295 // database until a final write is called. 296 func (d *Database) NewBatch() ethdb.Batch { 297 return &batch{ 298 b: d.db.NewBatch(), 299 db: d, 300 } 301 } 302 303 // NewBatchWithSize creates a write-only database batch with pre-allocated buffer. 304 // TODO can't do this with pebble. Batches are allocated in a pool so maybe this doesn't matter? 305 func (d *Database) NewBatchWithSize(_ int) ethdb.Batch { 306 return &batch{ 307 b: d.db.NewBatch(), 308 db: d, 309 } 310 } 311 312 // upperBound returns the upper bound for the given prefix 313 func upperBound(prefix []byte) (limit []byte) { 314 for i := len(prefix) - 1; i >= 0; i-- { 315 c := prefix[i] 316 if c == 0xff { 317 continue 318 } 319 limit = make([]byte, i+1) 320 copy(limit, prefix) 321 limit[i] = c + 1 322 break 323 } 324 return limit 325 } 326 327 // Stat returns a particular internal stat of the database. 328 func (d *Database) Stat(property string) (string, error) { 329 return "", nil 330 } 331 332 // Compact flattens the underlying data store for the given key range. In essence, 333 // deleted and overwritten versions are discarded, and the data is rearranged to 334 // reduce the cost of operations needed to access them. 335 // 336 // A nil start is treated as a key before all keys in the data store; a nil limit 337 // is treated as a key after all keys in the data store. If both is nil then it 338 // will compact entire data store. 339 func (d *Database) Compact(start []byte, limit []byte) error { 340 // There is no special flag to represent the end of key range 341 // in pebble(nil in leveldb). Use an ugly hack to construct a 342 // large key to represent it. 343 // Note any prefixed database entry will be smaller than this 344 // flag, as for trie nodes we need the 32 byte 0xff because 345 // there might be a shared prefix starting with a number of 346 // 0xff-s, so 32 ensures than only a hash collision could touch it. 347 // https://github.com/cockroachdb/pebble/issues/2359#issuecomment-1443995833 348 if limit == nil { 349 limit = bytes.Repeat([]byte{0xff}, 32) 350 } 351 return d.db.Compact(start, limit, true) // Parallelization is preferred 352 } 353 354 // Path returns the path to the database directory. 355 func (d *Database) Path() string { 356 return d.fn 357 } 358 359 // meter periodically retrieves internal pebble counters and reports them to 360 // the metrics subsystem. 361 func (d *Database) meter(refresh time.Duration) { 362 var errc chan error 363 timer := time.NewTimer(refresh) 364 defer timer.Stop() 365 366 // Create storage and warning log tracer for write delay. 367 var ( 368 compTimes [2]int64 369 writeDelayTimes [2]int64 370 writeDelayCounts [2]int64 371 compWrites [2]int64 372 compReads [2]int64 373 374 nWrites [2]int64 375 ) 376 377 // Iterate ad infinitum and collect the stats 378 for i := 1; errc == nil; i++ { 379 var ( 380 compWrite int64 381 compRead int64 382 nWrite int64 383 384 metrics = d.db.Metrics() 385 compTime = d.compTime.Load() 386 writeDelayCount = d.writeDelayCount.Load() 387 writeDelayTime = d.writeDelayTime.Load() 388 nonLevel0CompCount = int64(d.nonLevel0Comp.Load()) 389 level0CompCount = int64(d.level0Comp.Load()) 390 ) 391 writeDelayTimes[i%2] = writeDelayTime 392 writeDelayCounts[i%2] = writeDelayCount 393 compTimes[i%2] = compTime 394 395 for _, levelMetrics := range metrics.Levels { 396 nWrite += int64(levelMetrics.BytesCompacted) 397 nWrite += int64(levelMetrics.BytesFlushed) 398 compWrite += int64(levelMetrics.BytesCompacted) 399 compRead += int64(levelMetrics.BytesRead) 400 } 401 402 nWrite += int64(metrics.WAL.BytesWritten) 403 404 compWrites[i%2] = compWrite 405 compReads[i%2] = compRead 406 nWrites[i%2] = nWrite 407 408 if d.writeDelayNMeter != nil { 409 d.writeDelayNMeter.Mark(writeDelayCounts[i%2] - writeDelayCounts[(i-1)%2]) 410 } 411 if d.writeDelayMeter != nil { 412 d.writeDelayMeter.Mark(writeDelayTimes[i%2] - writeDelayTimes[(i-1)%2]) 413 } 414 if d.compTimeMeter != nil { 415 d.compTimeMeter.Mark(compTimes[i%2] - compTimes[(i-1)%2]) 416 } 417 if d.compReadMeter != nil { 418 d.compReadMeter.Mark(compReads[i%2] - compReads[(i-1)%2]) 419 } 420 if d.compWriteMeter != nil { 421 d.compWriteMeter.Mark(compWrites[i%2] - compWrites[(i-1)%2]) 422 } 423 if d.diskSizeGauge != nil { 424 d.diskSizeGauge.Update(int64(metrics.DiskSpaceUsage())) 425 } 426 if d.diskReadMeter != nil { 427 d.diskReadMeter.Mark(0) // pebble doesn't track non-compaction reads 428 } 429 if d.diskWriteMeter != nil { 430 d.diskWriteMeter.Mark(nWrites[i%2] - nWrites[(i-1)%2]) 431 } 432 // See https://github.com/cockroachdb/pebble/pull/1628#pullrequestreview-1026664054 433 manuallyAllocated := metrics.BlockCache.Size + int64(metrics.MemTable.Size) + int64(metrics.MemTable.ZombieSize) 434 d.manualMemAllocGauge.Update(manuallyAllocated) 435 d.memCompGauge.Update(metrics.Flush.Count) 436 d.nonlevel0CompGauge.Update(nonLevel0CompCount) 437 d.level0CompGauge.Update(level0CompCount) 438 d.seekCompGauge.Update(metrics.Compact.ReadCount) 439 440 // Sleep a bit, then repeat the stats collection 441 select { 442 case errc = <-d.quitChan: 443 // Quit requesting, stop hammering the database 444 case <-timer.C: 445 timer.Reset(refresh) 446 // Timeout, gather a new set of stats 447 } 448 } 449 errc <- nil 450 } 451 452 // batch is a write-only batch that commits changes to its host database 453 // when Write is called. A batch cannot be used concurrently. 454 type batch struct { 455 b *pebble.Batch 456 db *Database 457 size int 458 } 459 460 // Put inserts the given value into the batch for later committing. 461 func (b *batch) Put(key, value []byte) error { 462 b.b.Set(key, value, nil) 463 b.size += len(key) + len(value) 464 return nil 465 } 466 467 // Delete inserts the a key removal into the batch for later committing. 468 func (b *batch) Delete(key []byte) error { 469 b.b.Delete(key, nil) 470 b.size += len(key) 471 return nil 472 } 473 474 // ValueSize retrieves the amount of data queued up for writing. 475 func (b *batch) ValueSize() int { 476 return b.size 477 } 478 479 // Write flushes any accumulated data to disk. 480 func (b *batch) Write() error { 481 b.db.quitLock.RLock() 482 defer b.db.quitLock.RUnlock() 483 if b.db.closed { 484 return pebble.ErrClosed 485 } 486 return b.b.Commit(pebble.Sync) 487 } 488 489 // Reset resets the batch for reuse. 490 func (b *batch) Reset() { 491 b.b.Reset() 492 b.size = 0 493 } 494 495 // Replay replays the batch contents. 496 func (b *batch) Replay(w ethdb.KeyValueWriter) error { 497 reader := b.b.Reader() 498 for { 499 kind, k, v, ok := reader.Next() 500 if !ok { 501 break 502 } 503 // The (k,v) slices might be overwritten if the batch is reset/reused, 504 // and the receiver should copy them if they are to be retained long-term. 505 if kind == pebble.InternalKeyKindSet { 506 w.Put(k, v) 507 } else if kind == pebble.InternalKeyKindDelete { 508 w.Delete(k) 509 } else { 510 return fmt.Errorf("unhandled operation, keytype: %v", kind) 511 } 512 } 513 return nil 514 } 515 516 // pebbleIterator is a wrapper of underlying iterator in storage engine. 517 // The purpose of this structure is to implement the missing APIs. 518 type pebbleIterator struct { 519 iter *pebble.Iterator 520 moved bool 521 } 522 523 // NewIterator creates a binary-alphabetical iterator over a subset 524 // of database content with a particular key prefix, starting at a particular 525 // initial key (or after, if it does not exist). 526 func (d *Database) NewIterator(prefix []byte, start []byte) ethdb.Iterator { 527 iter := d.db.NewIter(&pebble.IterOptions{ 528 LowerBound: append(prefix, start...), 529 UpperBound: upperBound(prefix), 530 }) 531 iter.First() 532 return &pebbleIterator{iter: iter, moved: true} 533 } 534 535 // Next moves the iterator to the next key/value pair. It returns whether the 536 // iterator is exhausted. 537 func (iter *pebbleIterator) Next() bool { 538 if iter.moved { 539 iter.moved = false 540 return iter.iter.Valid() 541 } 542 return iter.iter.Next() 543 } 544 545 // Error returns any accumulated error. Exhausting all the key/value pairs 546 // is not considered to be an error. 547 func (iter *pebbleIterator) Error() error { 548 return iter.iter.Error() 549 } 550 551 // Key returns the key of the current key/value pair, or nil if done. The caller 552 // should not modify the contents of the returned slice, and its contents may 553 // change on the next call to Next. 554 func (iter *pebbleIterator) Key() []byte { 555 return iter.iter.Key() 556 } 557 558 // Value returns the value of the current key/value pair, or nil if done. The 559 // caller should not modify the contents of the returned slice, and its contents 560 // may change on the next call to Next. 561 func (iter *pebbleIterator) Value() []byte { 562 return iter.iter.Value() 563 } 564 565 // Release releases associated resources. Release should always succeed and can 566 // be called multiple times without causing error. 567 func (iter *pebbleIterator) Release() { iter.iter.Close() }