github.com/badrootd/nibiru-cometbft@v0.37.5-0.20240307173500-2a75559eee9b/cmd/cometbft/commands/compact.go (about)

     1  package commands
     2  
     3  import (
     4  	"errors"
     5  	"path/filepath"
     6  	"sync"
     7  
     8  	"github.com/spf13/cobra"
     9  	"github.com/syndtr/goleveldb/leveldb"
    10  	"github.com/syndtr/goleveldb/leveldb/opt"
    11  	"github.com/syndtr/goleveldb/leveldb/util"
    12  
    13  	"github.com/badrootd/nibiru-cometbft/libs/log"
    14  )
    15  
    16  var CompactGoLevelDBCmd = &cobra.Command{
    17  	Use:     "experimental-compact-goleveldb",
    18  	Aliases: []string{"experimental_compact_goleveldb"},
    19  	Short:   "force compacts the CometBFT storage engine (only GoLevelDB supported)",
    20  	Long: `
    21  This is a temporary utility command that performs a force compaction on the state
    22  and blockstores to reduce disk space for a pruning node. This should only be run
    23  once the node has stopped. This command will likely be omitted in the future after
    24  the planned refactor to the storage engine.
    25  
    26  Currently, only GoLevelDB is supported.
    27  	`,
    28  	RunE: func(cmd *cobra.Command, args []string) error {
    29  		if config.DBBackend != "goleveldb" {
    30  			return errors.New("compaction is currently only supported with goleveldb")
    31  		}
    32  
    33  		compactGoLevelDBs(config.RootDir, logger)
    34  		return nil
    35  	},
    36  }
    37  
    38  func compactGoLevelDBs(rootDir string, logger log.Logger) {
    39  	dbNames := []string{"state", "blockstore"}
    40  	o := &opt.Options{
    41  		DisableSeeksCompaction: true,
    42  	}
    43  	wg := sync.WaitGroup{}
    44  
    45  	for _, dbName := range dbNames {
    46  		dbName := dbName
    47  		wg.Add(1)
    48  		go func() {
    49  			defer wg.Done()
    50  			dbPath := filepath.Join(rootDir, "data", dbName+".db")
    51  			store, err := leveldb.OpenFile(dbPath, o)
    52  			if err != nil {
    53  				logger.Error("failed to initialize cometbft db", "path", dbPath, "err", err)
    54  				return
    55  			}
    56  			defer store.Close()
    57  
    58  			logger.Info("starting compaction...", "db", dbPath)
    59  
    60  			err = store.CompactRange(util.Range{Start: nil, Limit: nil})
    61  			if err != nil {
    62  				logger.Error("failed to compact cometbft db", "path", dbPath, "err", err)
    63  			}
    64  		}()
    65  	}
    66  	wg.Wait()
    67  }