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