gitee.com/liu-zhao234568/cntest@v1.0.0/core/rawdb/freezer.go (about)

     1  // Copyright 2019 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 rawdb
    18  
    19  import (
    20  	"errors"
    21  	"fmt"
    22  	"math"
    23  	"os"
    24  	"path/filepath"
    25  	"sync"
    26  	"sync/atomic"
    27  	"time"
    28  
    29  	"gitee.com/liu-zhao234568/cntest/common"
    30  	"gitee.com/liu-zhao234568/cntest/ethdb"
    31  	"gitee.com/liu-zhao234568/cntest/log"
    32  	"gitee.com/liu-zhao234568/cntest/metrics"
    33  	"gitee.com/liu-zhao234568/cntest/params"
    34  	"github.com/prometheus/tsdb/fileutil"
    35  )
    36  
    37  var (
    38  	// errReadOnly is returned if the freezer is opened in read only mode. All the
    39  	// mutations are disallowed.
    40  	errReadOnly = errors.New("read only")
    41  
    42  	// errUnknownTable is returned if the user attempts to read from a table that is
    43  	// not tracked by the freezer.
    44  	errUnknownTable = errors.New("unknown table")
    45  
    46  	// errOutOrderInsertion is returned if the user attempts to inject out-of-order
    47  	// binary blobs into the freezer.
    48  	errOutOrderInsertion = errors.New("the append operation is out-order")
    49  
    50  	// errSymlinkDatadir is returned if the ancient directory specified by user
    51  	// is a symbolic link.
    52  	errSymlinkDatadir = errors.New("symbolic link datadir is not supported")
    53  )
    54  
    55  const (
    56  	// freezerRecheckInterval is the frequency to check the key-value database for
    57  	// chain progression that might permit new blocks to be frozen into immutable
    58  	// storage.
    59  	freezerRecheckInterval = time.Minute
    60  
    61  	// freezerBatchLimit is the maximum number of blocks to freeze in one batch
    62  	// before doing an fsync and deleting it from the key-value store.
    63  	freezerBatchLimit = 30000
    64  )
    65  
    66  // freezer is an memory mapped append-only database to store immutable chain data
    67  // into flat files:
    68  //
    69  // - The append only nature ensures that disk writes are minimized.
    70  // - The memory mapping ensures we can max out system memory for caching without
    71  //   reserving it for go-ethereum. This would also reduce the memory requirements
    72  //   of Geth, and thus also GC overhead.
    73  type freezer struct {
    74  	// WARNING: The `frozen` field is accessed atomically. On 32 bit platforms, only
    75  	// 64-bit aligned fields can be atomic. The struct is guaranteed to be so aligned,
    76  	// so take advantage of that (https://golang.org/pkg/sync/atomic/#pkg-note-BUG).
    77  	frozen    uint64 // Number of blocks already frozen
    78  	threshold uint64 // Number of recent blocks not to freeze (params.FullImmutabilityThreshold apart from tests)
    79  
    80  	readonly     bool
    81  	tables       map[string]*freezerTable // Data tables for storing everything
    82  	instanceLock fileutil.Releaser        // File-system lock to prevent double opens
    83  
    84  	trigger chan chan struct{} // Manual blocking freeze trigger, test determinism
    85  
    86  	quit      chan struct{}
    87  	wg        sync.WaitGroup
    88  	closeOnce sync.Once
    89  }
    90  
    91  // newFreezer creates a chain freezer that moves ancient chain data into
    92  // append-only flat file containers.
    93  func newFreezer(datadir string, namespace string, readonly bool) (*freezer, error) {
    94  	// Create the initial freezer object
    95  	var (
    96  		readMeter  = metrics.NewRegisteredMeter(namespace+"ancient/read", nil)
    97  		writeMeter = metrics.NewRegisteredMeter(namespace+"ancient/write", nil)
    98  		sizeGauge  = metrics.NewRegisteredGauge(namespace+"ancient/size", nil)
    99  	)
   100  	// Ensure the datadir is not a symbolic link if it exists.
   101  	if info, err := os.Lstat(datadir); !os.IsNotExist(err) {
   102  		if info.Mode()&os.ModeSymlink != 0 {
   103  			log.Warn("Symbolic link ancient database is not supported", "path", datadir)
   104  			return nil, errSymlinkDatadir
   105  		}
   106  	}
   107  	// Leveldb uses LOCK as the filelock filename. To prevent the
   108  	// name collision, we use FLOCK as the lock name.
   109  	lock, _, err := fileutil.Flock(filepath.Join(datadir, "FLOCK"))
   110  	if err != nil {
   111  		return nil, err
   112  	}
   113  	// Open all the supported data tables
   114  	freezer := &freezer{
   115  		readonly:     readonly,
   116  		threshold:    params.FullImmutabilityThreshold,
   117  		tables:       make(map[string]*freezerTable),
   118  		instanceLock: lock,
   119  		trigger:      make(chan chan struct{}),
   120  		quit:         make(chan struct{}),
   121  	}
   122  	for name, disableSnappy := range FreezerNoSnappy {
   123  		table, err := newTable(datadir, name, readMeter, writeMeter, sizeGauge, disableSnappy)
   124  		if err != nil {
   125  			for _, table := range freezer.tables {
   126  				table.Close()
   127  			}
   128  			lock.Release()
   129  			return nil, err
   130  		}
   131  		freezer.tables[name] = table
   132  	}
   133  	if err := freezer.repair(); err != nil {
   134  		for _, table := range freezer.tables {
   135  			table.Close()
   136  		}
   137  		lock.Release()
   138  		return nil, err
   139  	}
   140  	log.Info("Opened ancient database", "database", datadir, "readonly", readonly)
   141  	return freezer, nil
   142  }
   143  
   144  // Close terminates the chain freezer, unmapping all the data files.
   145  func (f *freezer) Close() error {
   146  	var errs []error
   147  	f.closeOnce.Do(func() {
   148  		close(f.quit)
   149  		// Wait for any background freezing to stop
   150  		f.wg.Wait()
   151  		for _, table := range f.tables {
   152  			if err := table.Close(); err != nil {
   153  				errs = append(errs, err)
   154  			}
   155  		}
   156  		if err := f.instanceLock.Release(); err != nil {
   157  			errs = append(errs, err)
   158  		}
   159  	})
   160  	if errs != nil {
   161  		return fmt.Errorf("%v", errs)
   162  	}
   163  	return nil
   164  }
   165  
   166  // HasAncient returns an indicator whether the specified ancient data exists
   167  // in the freezer.
   168  func (f *freezer) HasAncient(kind string, number uint64) (bool, error) {
   169  	if table := f.tables[kind]; table != nil {
   170  		return table.has(number), nil
   171  	}
   172  	return false, nil
   173  }
   174  
   175  // Ancient retrieves an ancient binary blob from the append-only immutable files.
   176  func (f *freezer) Ancient(kind string, number uint64) ([]byte, error) {
   177  	if table := f.tables[kind]; table != nil {
   178  		return table.Retrieve(number)
   179  	}
   180  	return nil, errUnknownTable
   181  }
   182  
   183  // Ancients returns the length of the frozen items.
   184  func (f *freezer) Ancients() (uint64, error) {
   185  	return atomic.LoadUint64(&f.frozen), nil
   186  }
   187  
   188  // AncientSize returns the ancient size of the specified category.
   189  func (f *freezer) AncientSize(kind string) (uint64, error) {
   190  	if table := f.tables[kind]; table != nil {
   191  		return table.size()
   192  	}
   193  	return 0, errUnknownTable
   194  }
   195  
   196  // AppendAncient injects all binary blobs belong to block at the end of the
   197  // append-only immutable table files.
   198  //
   199  // Notably, this function is lock free but kind of thread-safe. All out-of-order
   200  // injection will be rejected. But if two injections with same number happen at
   201  // the same time, we can get into the trouble.
   202  func (f *freezer) AppendAncient(number uint64, hash, header, body, receipts, td []byte) (err error) {
   203  	if f.readonly {
   204  		return errReadOnly
   205  	}
   206  	// Ensure the binary blobs we are appending is continuous with freezer.
   207  	if atomic.LoadUint64(&f.frozen) != number {
   208  		return errOutOrderInsertion
   209  	}
   210  	// Rollback all inserted data if any insertion below failed to ensure
   211  	// the tables won't out of sync.
   212  	defer func() {
   213  		if err != nil {
   214  			rerr := f.repair()
   215  			if rerr != nil {
   216  				log.Crit("Failed to repair freezer", "err", rerr)
   217  			}
   218  			log.Info("Append ancient failed", "number", number, "err", err)
   219  		}
   220  	}()
   221  	// Inject all the components into the relevant data tables
   222  	if err := f.tables[freezerHashTable].Append(f.frozen, hash[:]); err != nil {
   223  		log.Error("Failed to append ancient hash", "number", f.frozen, "hash", hash, "err", err)
   224  		return err
   225  	}
   226  	if err := f.tables[freezerHeaderTable].Append(f.frozen, header); err != nil {
   227  		log.Error("Failed to append ancient header", "number", f.frozen, "hash", hash, "err", err)
   228  		return err
   229  	}
   230  	if err := f.tables[freezerBodiesTable].Append(f.frozen, body); err != nil {
   231  		log.Error("Failed to append ancient body", "number", f.frozen, "hash", hash, "err", err)
   232  		return err
   233  	}
   234  	if err := f.tables[freezerReceiptTable].Append(f.frozen, receipts); err != nil {
   235  		log.Error("Failed to append ancient receipts", "number", f.frozen, "hash", hash, "err", err)
   236  		return err
   237  	}
   238  	if err := f.tables[freezerDifficultyTable].Append(f.frozen, td); err != nil {
   239  		log.Error("Failed to append ancient difficulty", "number", f.frozen, "hash", hash, "err", err)
   240  		return err
   241  	}
   242  	atomic.AddUint64(&f.frozen, 1) // Only modify atomically
   243  	return nil
   244  }
   245  
   246  // TruncateAncients discards any recent data above the provided threshold number.
   247  func (f *freezer) TruncateAncients(items uint64) error {
   248  	if f.readonly {
   249  		return errReadOnly
   250  	}
   251  	if atomic.LoadUint64(&f.frozen) <= items {
   252  		return nil
   253  	}
   254  	for _, table := range f.tables {
   255  		if err := table.truncate(items); err != nil {
   256  			return err
   257  		}
   258  	}
   259  	atomic.StoreUint64(&f.frozen, items)
   260  	return nil
   261  }
   262  
   263  // Sync flushes all data tables to disk.
   264  func (f *freezer) Sync() error {
   265  	var errs []error
   266  	for _, table := range f.tables {
   267  		if err := table.Sync(); err != nil {
   268  			errs = append(errs, err)
   269  		}
   270  	}
   271  	if errs != nil {
   272  		return fmt.Errorf("%v", errs)
   273  	}
   274  	return nil
   275  }
   276  
   277  // freeze is a background thread that periodically checks the blockchain for any
   278  // import progress and moves ancient data from the fast database into the freezer.
   279  //
   280  // This functionality is deliberately broken off from block importing to avoid
   281  // incurring additional data shuffling delays on block propagation.
   282  func (f *freezer) freeze(db ethdb.KeyValueStore) {
   283  	nfdb := &nofreezedb{KeyValueStore: db}
   284  
   285  	var (
   286  		backoff   bool
   287  		triggered chan struct{} // Used in tests
   288  	)
   289  	for {
   290  		select {
   291  		case <-f.quit:
   292  			log.Info("Freezer shutting down")
   293  			return
   294  		default:
   295  		}
   296  		if backoff {
   297  			// If we were doing a manual trigger, notify it
   298  			if triggered != nil {
   299  				triggered <- struct{}{}
   300  				triggered = nil
   301  			}
   302  			select {
   303  			case <-time.NewTimer(freezerRecheckInterval).C:
   304  				backoff = false
   305  			case triggered = <-f.trigger:
   306  				backoff = false
   307  			case <-f.quit:
   308  				return
   309  			}
   310  		}
   311  		// Retrieve the freezing threshold.
   312  		hash := ReadHeadBlockHash(nfdb)
   313  		if hash == (common.Hash{}) {
   314  			log.Debug("Current full block hash unavailable") // new chain, empty database
   315  			backoff = true
   316  			continue
   317  		}
   318  		number := ReadHeaderNumber(nfdb, hash)
   319  		threshold := atomic.LoadUint64(&f.threshold)
   320  
   321  		switch {
   322  		case number == nil:
   323  			log.Error("Current full block number unavailable", "hash", hash)
   324  			backoff = true
   325  			continue
   326  
   327  		case *number < threshold:
   328  			log.Debug("Current full block not old enough", "number", *number, "hash", hash, "delay", threshold)
   329  			backoff = true
   330  			continue
   331  
   332  		case *number-threshold <= f.frozen:
   333  			log.Debug("Ancient blocks frozen already", "number", *number, "hash", hash, "frozen", f.frozen)
   334  			backoff = true
   335  			continue
   336  		}
   337  		head := ReadHeader(nfdb, hash, *number)
   338  		if head == nil {
   339  			log.Error("Current full block unavailable", "number", *number, "hash", hash)
   340  			backoff = true
   341  			continue
   342  		}
   343  		// Seems we have data ready to be frozen, process in usable batches
   344  		limit := *number - threshold
   345  		if limit-f.frozen > freezerBatchLimit {
   346  			limit = f.frozen + freezerBatchLimit
   347  		}
   348  		var (
   349  			start    = time.Now()
   350  			first    = f.frozen
   351  			ancients = make([]common.Hash, 0, limit-f.frozen)
   352  		)
   353  		for f.frozen <= limit {
   354  			// Retrieves all the components of the canonical block
   355  			hash := ReadCanonicalHash(nfdb, f.frozen)
   356  			if hash == (common.Hash{}) {
   357  				log.Error("Canonical hash missing, can't freeze", "number", f.frozen)
   358  				break
   359  			}
   360  			header := ReadHeaderRLP(nfdb, hash, f.frozen)
   361  			if len(header) == 0 {
   362  				log.Error("Block header missing, can't freeze", "number", f.frozen, "hash", hash)
   363  				break
   364  			}
   365  			body := ReadBodyRLP(nfdb, hash, f.frozen)
   366  			if len(body) == 0 {
   367  				log.Error("Block body missing, can't freeze", "number", f.frozen, "hash", hash)
   368  				break
   369  			}
   370  			receipts := ReadReceiptsRLP(nfdb, hash, f.frozen)
   371  			if len(receipts) == 0 {
   372  				log.Error("Block receipts missing, can't freeze", "number", f.frozen, "hash", hash)
   373  				break
   374  			}
   375  			td := ReadTdRLP(nfdb, hash, f.frozen)
   376  			if len(td) == 0 {
   377  				log.Error("Total difficulty missing, can't freeze", "number", f.frozen, "hash", hash)
   378  				break
   379  			}
   380  			log.Trace("Deep froze ancient block", "number", f.frozen, "hash", hash)
   381  			// Inject all the components into the relevant data tables
   382  			if err := f.AppendAncient(f.frozen, hash[:], header, body, receipts, td); err != nil {
   383  				break
   384  			}
   385  			ancients = append(ancients, hash)
   386  		}
   387  		// Batch of blocks have been frozen, flush them before wiping from leveldb
   388  		if err := f.Sync(); err != nil {
   389  			log.Crit("Failed to flush frozen tables", "err", err)
   390  		}
   391  		// Wipe out all data from the active database
   392  		batch := db.NewBatch()
   393  		for i := 0; i < len(ancients); i++ {
   394  			// Always keep the genesis block in active database
   395  			if first+uint64(i) != 0 {
   396  				DeleteBlockWithoutNumber(batch, ancients[i], first+uint64(i))
   397  				DeleteCanonicalHash(batch, first+uint64(i))
   398  			}
   399  		}
   400  		if err := batch.Write(); err != nil {
   401  			log.Crit("Failed to delete frozen canonical blocks", "err", err)
   402  		}
   403  		batch.Reset()
   404  
   405  		// Wipe out side chains also and track dangling side chians
   406  		var dangling []common.Hash
   407  		for number := first; number < f.frozen; number++ {
   408  			// Always keep the genesis block in active database
   409  			if number != 0 {
   410  				dangling = ReadAllHashes(db, number)
   411  				for _, hash := range dangling {
   412  					log.Trace("Deleting side chain", "number", number, "hash", hash)
   413  					DeleteBlock(batch, hash, number)
   414  				}
   415  			}
   416  		}
   417  		if err := batch.Write(); err != nil {
   418  			log.Crit("Failed to delete frozen side blocks", "err", err)
   419  		}
   420  		batch.Reset()
   421  
   422  		// Step into the future and delete and dangling side chains
   423  		if f.frozen > 0 {
   424  			tip := f.frozen
   425  			for len(dangling) > 0 {
   426  				drop := make(map[common.Hash]struct{})
   427  				for _, hash := range dangling {
   428  					log.Debug("Dangling parent from freezer", "number", tip-1, "hash", hash)
   429  					drop[hash] = struct{}{}
   430  				}
   431  				children := ReadAllHashes(db, tip)
   432  				for i := 0; i < len(children); i++ {
   433  					// Dig up the child and ensure it's dangling
   434  					child := ReadHeader(nfdb, children[i], tip)
   435  					if child == nil {
   436  						log.Error("Missing dangling header", "number", tip, "hash", children[i])
   437  						continue
   438  					}
   439  					if _, ok := drop[child.ParentHash]; !ok {
   440  						children = append(children[:i], children[i+1:]...)
   441  						i--
   442  						continue
   443  					}
   444  					// Delete all block data associated with the child
   445  					log.Debug("Deleting dangling block", "number", tip, "hash", children[i], "parent", child.ParentHash)
   446  					DeleteBlock(batch, children[i], tip)
   447  				}
   448  				dangling = children
   449  				tip++
   450  			}
   451  			if err := batch.Write(); err != nil {
   452  				log.Crit("Failed to delete dangling side blocks", "err", err)
   453  			}
   454  		}
   455  		// Log something friendly for the user
   456  		context := []interface{}{
   457  			"blocks", f.frozen - first, "elapsed", common.PrettyDuration(time.Since(start)), "number", f.frozen - 1,
   458  		}
   459  		if n := len(ancients); n > 0 {
   460  			context = append(context, []interface{}{"hash", ancients[n-1]}...)
   461  		}
   462  		log.Info("Deep froze chain segment", context...)
   463  
   464  		// Avoid database thrashing with tiny writes
   465  		if f.frozen-first < freezerBatchLimit {
   466  			backoff = true
   467  		}
   468  	}
   469  }
   470  
   471  // repair truncates all data tables to the same length.
   472  func (f *freezer) repair() error {
   473  	min := uint64(math.MaxUint64)
   474  	for _, table := range f.tables {
   475  		items := atomic.LoadUint64(&table.items)
   476  		if min > items {
   477  			min = items
   478  		}
   479  	}
   480  	for _, table := range f.tables {
   481  		if err := table.truncate(min); err != nil {
   482  			return err
   483  		}
   484  	}
   485  	atomic.StoreUint64(&f.frozen, min)
   486  	return nil
   487  }