github.com/bloxroute-labs/bor@v0.1.4/ethdb/leveldb/leveldb.go (about)

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