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