github.com/theQRL/go-zond@v0.1.1/zonddb/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  	"sync"
    26  	"time"
    27  
    28  	"github.com/syndtr/goleveldb/leveldb"
    29  	"github.com/syndtr/goleveldb/leveldb/errors"
    30  	"github.com/syndtr/goleveldb/leveldb/filter"
    31  	"github.com/syndtr/goleveldb/leveldb/opt"
    32  	"github.com/syndtr/goleveldb/leveldb/util"
    33  	"github.com/theQRL/go-zond/common"
    34  	"github.com/theQRL/go-zond/log"
    35  	"github.com/theQRL/go-zond/metrics"
    36  	"github.com/theQRL/go-zond/zonddb"
    37  )
    38  
    39  const (
    40  	// degradationWarnInterval specifies how often warning should be printed if the
    41  	// leveldb database cannot keep up with requested writes.
    42  	degradationWarnInterval = time.Minute
    43  
    44  	// minCache is the minimum amount of memory in megabytes to allocate to leveldb
    45  	// read and write caching, split half and half.
    46  	minCache = 16
    47  
    48  	// minHandles is the minimum number of files handles to allocate to the open
    49  	// database files.
    50  	minHandles = 16
    51  
    52  	// metricsGatheringInterval specifies the interval to retrieve leveldb database
    53  	// compaction, io and pause stats to report to the user.
    54  	metricsGatheringInterval = 3 * time.Second
    55  )
    56  
    57  // Database is a persistent key-value store. Apart from basic data storage
    58  // functionality it also supports batch writes and iterating over the keyspace in
    59  // binary-alphabetical order.
    60  type Database struct {
    61  	fn string      // filename for reporting
    62  	db *leveldb.DB // LevelDB instance
    63  
    64  	compTimeMeter       metrics.Meter // Meter for measuring the total time spent in database compaction
    65  	compReadMeter       metrics.Meter // Meter for measuring the data read during compaction
    66  	compWriteMeter      metrics.Meter // Meter for measuring the data written during compaction
    67  	writeDelayNMeter    metrics.Meter // Meter for measuring the write delay number due to database compaction
    68  	writeDelayMeter     metrics.Meter // Meter for measuring the write delay duration due to database compaction
    69  	diskSizeGauge       metrics.Gauge // Gauge for tracking the size of all the levels in the database
    70  	diskReadMeter       metrics.Meter // Meter for measuring the effective amount of data read
    71  	diskWriteMeter      metrics.Meter // Meter for measuring the effective amount of data written
    72  	memCompGauge        metrics.Gauge // Gauge for tracking the number of memory compaction
    73  	level0CompGauge     metrics.Gauge // Gauge for tracking the number of table compaction in level0
    74  	nonlevel0CompGauge  metrics.Gauge // Gauge for tracking the number of table compaction in non0 level
    75  	seekCompGauge       metrics.Gauge // Gauge for tracking the number of table compaction caused by read opt
    76  	manualMemAllocGauge metrics.Gauge // Gauge to track the amount of memory that has been manually allocated (not a part of runtime/GC)
    77  
    78  	levelsGauge []metrics.Gauge // Gauge for tracking the number of tables in levels
    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  	ldb.manualMemAllocGauge = metrics.NewRegisteredGauge(namespace+"memory/manualalloc", nil)
   148  
   149  	// Start up the metrics gathering and return
   150  	go ldb.meter(metricsGatheringInterval, namespace)
   151  	return ldb, nil
   152  }
   153  
   154  // configureOptions sets some default options, then runs the provided setter.
   155  func configureOptions(customizeFn func(*opt.Options)) *opt.Options {
   156  	// Set default options
   157  	options := &opt.Options{
   158  		Filter:                 filter.NewBloomFilter(10),
   159  		DisableSeeksCompaction: true,
   160  	}
   161  	// Allow caller to make custom modifications to the options
   162  	if customizeFn != nil {
   163  		customizeFn(options)
   164  	}
   165  	return options
   166  }
   167  
   168  // Close stops the metrics collection, flushes any pending data to disk and closes
   169  // all io accesses to the underlying key-value store.
   170  func (db *Database) Close() error {
   171  	db.quitLock.Lock()
   172  	defer db.quitLock.Unlock()
   173  
   174  	if db.quitChan != nil {
   175  		errc := make(chan error)
   176  		db.quitChan <- errc
   177  		if err := <-errc; err != nil {
   178  			db.log.Error("Metrics collection failed", "err", err)
   179  		}
   180  		db.quitChan = nil
   181  	}
   182  	return db.db.Close()
   183  }
   184  
   185  // Has retrieves if a key is present in the key-value store.
   186  func (db *Database) Has(key []byte) (bool, error) {
   187  	return db.db.Has(key, nil)
   188  }
   189  
   190  // Get retrieves the given key if it's present in the key-value store.
   191  func (db *Database) Get(key []byte) ([]byte, error) {
   192  	dat, err := db.db.Get(key, nil)
   193  	if err != nil {
   194  		return nil, err
   195  	}
   196  	return dat, nil
   197  }
   198  
   199  // Put inserts the given value into the key-value store.
   200  func (db *Database) Put(key []byte, value []byte) error {
   201  	return db.db.Put(key, value, nil)
   202  }
   203  
   204  // Delete removes the key from the key-value store.
   205  func (db *Database) Delete(key []byte) error {
   206  	return db.db.Delete(key, nil)
   207  }
   208  
   209  // NewBatch creates a write-only key-value store that buffers changes to its host
   210  // database until a final write is called.
   211  func (db *Database) NewBatch() zonddb.Batch {
   212  	return &batch{
   213  		db: db.db,
   214  		b:  new(leveldb.Batch),
   215  	}
   216  }
   217  
   218  // NewBatchWithSize creates a write-only database batch with pre-allocated buffer.
   219  func (db *Database) NewBatchWithSize(size int) zonddb.Batch {
   220  	return &batch{
   221  		db: db.db,
   222  		b:  leveldb.MakeBatch(size),
   223  	}
   224  }
   225  
   226  // NewIterator creates a binary-alphabetical iterator over a subset
   227  // of database content with a particular key prefix, starting at a particular
   228  // initial key (or after, if it does not exist).
   229  func (db *Database) NewIterator(prefix []byte, start []byte) zonddb.Iterator {
   230  	return db.db.NewIterator(bytesPrefixRange(prefix, start), nil)
   231  }
   232  
   233  // NewSnapshot creates a database snapshot based on the current state.
   234  // The created snapshot will not be affected by all following mutations
   235  // happened on the database.
   236  // Note don't forget to release the snapshot once it's used up, otherwise
   237  // the stale data will never be cleaned up by the underlying compactor.
   238  func (db *Database) NewSnapshot() (zonddb.Snapshot, error) {
   239  	snap, err := db.db.GetSnapshot()
   240  	if err != nil {
   241  		return nil, err
   242  	}
   243  	return &snapshot{db: snap}, nil
   244  }
   245  
   246  // Stat returns a particular internal stat of the database.
   247  func (db *Database) Stat(property string) (string, error) {
   248  	return db.db.GetProperty(property)
   249  }
   250  
   251  // Compact flattens the underlying data store for the given key range. In essence,
   252  // deleted and overwritten versions are discarded, and the data is rearranged to
   253  // reduce the cost of operations needed to access them.
   254  //
   255  // A nil start is treated as a key before all keys in the data store; a nil limit
   256  // is treated as a key after all keys in the data store. If both is nil then it
   257  // will compact entire data store.
   258  func (db *Database) Compact(start []byte, limit []byte) error {
   259  	return db.db.CompactRange(util.Range{Start: start, Limit: limit})
   260  }
   261  
   262  // Path returns the path to the database directory.
   263  func (db *Database) Path() string {
   264  	return db.fn
   265  }
   266  
   267  // meter periodically retrieves internal leveldb counters and reports them to
   268  // the metrics subsystem.
   269  func (db *Database) meter(refresh time.Duration, namespace string) {
   270  	// Create the counters to store current and previous compaction values
   271  	compactions := make([][]int64, 2)
   272  	for i := 0; i < 2; i++ {
   273  		compactions[i] = make([]int64, 4)
   274  	}
   275  	// Create storages for states and warning log tracer.
   276  	var (
   277  		errc chan error
   278  		merr error
   279  
   280  		stats           leveldb.DBStats
   281  		iostats         [2]int64
   282  		delaystats      [2]int64
   283  		lastWritePaused time.Time
   284  	)
   285  	timer := time.NewTimer(refresh)
   286  	defer timer.Stop()
   287  
   288  	// Iterate ad infinitum and collect the stats
   289  	for i := 1; errc == nil && merr == nil; i++ {
   290  		// Retrieve the database stats
   291  		// Stats method resets buffers inside therefore it's okay to just pass the struct.
   292  		err := db.db.Stats(&stats)
   293  		if err != nil {
   294  			db.log.Error("Failed to read database stats", "err", err)
   295  			merr = err
   296  			continue
   297  		}
   298  		// Iterate over all the leveldbTable rows, and accumulate the entries
   299  		for j := 0; j < len(compactions[i%2]); j++ {
   300  			compactions[i%2][j] = 0
   301  		}
   302  		compactions[i%2][0] = stats.LevelSizes.Sum()
   303  		for _, t := range stats.LevelDurations {
   304  			compactions[i%2][1] += t.Nanoseconds()
   305  		}
   306  		compactions[i%2][2] = stats.LevelRead.Sum()
   307  		compactions[i%2][3] = stats.LevelWrite.Sum()
   308  		// Update all the requested meters
   309  		if db.diskSizeGauge != nil {
   310  			db.diskSizeGauge.Update(compactions[i%2][0])
   311  		}
   312  		if db.compTimeMeter != nil {
   313  			db.compTimeMeter.Mark(compactions[i%2][1] - compactions[(i-1)%2][1])
   314  		}
   315  		if db.compReadMeter != nil {
   316  			db.compReadMeter.Mark(compactions[i%2][2] - compactions[(i-1)%2][2])
   317  		}
   318  		if db.compWriteMeter != nil {
   319  			db.compWriteMeter.Mark(compactions[i%2][3] - compactions[(i-1)%2][3])
   320  		}
   321  		var (
   322  			delayN   = int64(stats.WriteDelayCount)
   323  			duration = stats.WriteDelayDuration
   324  			paused   = stats.WritePaused
   325  		)
   326  		if db.writeDelayNMeter != nil {
   327  			db.writeDelayNMeter.Mark(delayN - delaystats[0])
   328  		}
   329  		if db.writeDelayMeter != nil {
   330  			db.writeDelayMeter.Mark(duration.Nanoseconds() - delaystats[1])
   331  		}
   332  		// If a warning that db is performing compaction has been displayed, any subsequent
   333  		// warnings will be withheld for one minute not to overwhelm the user.
   334  		if paused && delayN-delaystats[0] == 0 && duration.Nanoseconds()-delaystats[1] == 0 &&
   335  			time.Now().After(lastWritePaused.Add(degradationWarnInterval)) {
   336  			db.log.Warn("Database compacting, degraded performance")
   337  			lastWritePaused = time.Now()
   338  		}
   339  		delaystats[0], delaystats[1] = delayN, duration.Nanoseconds()
   340  
   341  		var (
   342  			nRead  = int64(stats.IORead)
   343  			nWrite = int64(stats.IOWrite)
   344  		)
   345  		if db.diskReadMeter != nil {
   346  			db.diskReadMeter.Mark(nRead - iostats[0])
   347  		}
   348  		if db.diskWriteMeter != nil {
   349  			db.diskWriteMeter.Mark(nWrite - iostats[1])
   350  		}
   351  		iostats[0], iostats[1] = nRead, nWrite
   352  
   353  		db.memCompGauge.Update(int64(stats.MemComp))
   354  		db.level0CompGauge.Update(int64(stats.Level0Comp))
   355  		db.nonlevel0CompGauge.Update(int64(stats.NonLevel0Comp))
   356  		db.seekCompGauge.Update(int64(stats.SeekComp))
   357  
   358  		for i, tables := range stats.LevelTablesCounts {
   359  			// Append metrics for additional layers
   360  			if i >= len(db.levelsGauge) {
   361  				db.levelsGauge = append(db.levelsGauge, metrics.NewRegisteredGauge(namespace+fmt.Sprintf("tables/level%v", i), nil))
   362  			}
   363  			db.levelsGauge[i].Update(int64(tables))
   364  		}
   365  
   366  		// Sleep a bit, then repeat the stats collection
   367  		select {
   368  		case errc = <-db.quitChan:
   369  			// Quit requesting, stop hammering the database
   370  		case <-timer.C:
   371  			timer.Reset(refresh)
   372  			// Timeout, gather a new set of stats
   373  		}
   374  	}
   375  
   376  	if errc == nil {
   377  		errc = <-db.quitChan
   378  	}
   379  	errc <- merr
   380  }
   381  
   382  // batch is a write-only leveldb batch that commits changes to its host database
   383  // when Write is called. A batch cannot be used concurrently.
   384  type batch struct {
   385  	db   *leveldb.DB
   386  	b    *leveldb.Batch
   387  	size int
   388  }
   389  
   390  // Put inserts the given value into the batch for later committing.
   391  func (b *batch) Put(key, value []byte) error {
   392  	b.b.Put(key, value)
   393  	b.size += len(key) + len(value)
   394  	return nil
   395  }
   396  
   397  // Delete inserts the a key removal into the batch for later committing.
   398  func (b *batch) Delete(key []byte) error {
   399  	b.b.Delete(key)
   400  	b.size += len(key)
   401  	return nil
   402  }
   403  
   404  // ValueSize retrieves the amount of data queued up for writing.
   405  func (b *batch) ValueSize() int {
   406  	return b.size
   407  }
   408  
   409  // Write flushes any accumulated data to disk.
   410  func (b *batch) Write() error {
   411  	return b.db.Write(b.b, nil)
   412  }
   413  
   414  // Reset resets the batch for reuse.
   415  func (b *batch) Reset() {
   416  	b.b.Reset()
   417  	b.size = 0
   418  }
   419  
   420  // Replay replays the batch contents.
   421  func (b *batch) Replay(w zonddb.KeyValueWriter) error {
   422  	return b.b.Replay(&replayer{writer: w})
   423  }
   424  
   425  // replayer is a small wrapper to implement the correct replay methods.
   426  type replayer struct {
   427  	writer  zonddb.KeyValueWriter
   428  	failure error
   429  }
   430  
   431  // Put inserts the given value into the key-value data store.
   432  func (r *replayer) Put(key, value []byte) {
   433  	// If the replay already failed, stop executing ops
   434  	if r.failure != nil {
   435  		return
   436  	}
   437  	r.failure = r.writer.Put(key, value)
   438  }
   439  
   440  // Delete removes the key from the key-value data store.
   441  func (r *replayer) Delete(key []byte) {
   442  	// If the replay already failed, stop executing ops
   443  	if r.failure != nil {
   444  		return
   445  	}
   446  	r.failure = r.writer.Delete(key)
   447  }
   448  
   449  // bytesPrefixRange returns key range that satisfy
   450  // - the given prefix, and
   451  // - the given seek position
   452  func bytesPrefixRange(prefix, start []byte) *util.Range {
   453  	r := util.BytesPrefix(prefix)
   454  	r.Start = append(r.Start, start...)
   455  	return r
   456  }
   457  
   458  // snapshot wraps a leveldb snapshot for implementing the Snapshot interface.
   459  type snapshot struct {
   460  	db *leveldb.Snapshot
   461  }
   462  
   463  // Has retrieves if a key is present in the snapshot backing by a key-value
   464  // data store.
   465  func (snap *snapshot) Has(key []byte) (bool, error) {
   466  	return snap.db.Has(key, nil)
   467  }
   468  
   469  // Get retrieves the given key if it's present in the snapshot backing by
   470  // key-value data store.
   471  func (snap *snapshot) Get(key []byte) ([]byte, error) {
   472  	return snap.db.Get(key, nil)
   473  }
   474  
   475  // Release releases associated resources. Release should always succeed and can
   476  // be called multiple times without causing error.
   477  func (snap *snapshot) Release() {
   478  	snap.db.Release()
   479  }