github.com/MetalBlockchain/metalgo@v1.11.9/tests/antithesis/init_db.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package antithesis
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"os"
    10  	"os/exec"
    11  	"path/filepath"
    12  	"time"
    13  
    14  	"github.com/MetalBlockchain/metalgo/tests/fixture/tmpnet"
    15  	"github.com/MetalBlockchain/metalgo/utils/perms"
    16  )
    17  
    18  // Given a path, compose the expected path of the bootstrap node's docker compose db volume.
    19  func GetBootstrapVolumePath(targetPath string) (string, error) {
    20  	absPath, err := filepath.Abs(targetPath)
    21  	if err != nil {
    22  		return "", fmt.Errorf("failed to convert target path to absolute path: %w", err)
    23  	}
    24  	return filepath.Join(absPath, "volumes", getServiceName(bootstrapIndex)), nil
    25  }
    26  
    27  // Bootstraps a local process-based network, creates its subnets and chains, and copies
    28  // the resulting db state from one of the nodes to the provided path. The path will be
    29  // created if it does not already exist.
    30  func InitBootstrapDB(network *tmpnet.Network, avalancheGoPath string, pluginDir string, destPath string) error {
    31  	ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2)
    32  	defer cancel()
    33  	if err := tmpnet.BootstrapNewNetwork(
    34  		ctx,
    35  		os.Stdout,
    36  		network,
    37  		"",
    38  		avalancheGoPath,
    39  		pluginDir,
    40  	); err != nil {
    41  		return fmt.Errorf("failed to bootstrap network: %w", err)
    42  	}
    43  	// Since the goal is to initialize the DB, we can stop the network after it has been started successfully
    44  	if err := network.Stop(ctx); err != nil {
    45  		return fmt.Errorf("failed to stop network: %w", err)
    46  	}
    47  
    48  	// Copy the db state from the bootstrap node to the compose volume path.
    49  	sourcePath := filepath.Join(network.Nodes[0].GetDataDir(), "db")
    50  	if err := os.MkdirAll(destPath, perms.ReadWriteExecute); err != nil {
    51  		return fmt.Errorf("failed to create db path %q: %w", destPath, err)
    52  	}
    53  	// TODO(marun) Replace with os.CopyFS once we upgrade to Go 1.23
    54  	cmd := exec.Command("cp", "-r", sourcePath, destPath)
    55  	if err := cmd.Run(); err != nil {
    56  		return fmt.Errorf("failed to copy bootstrap db from %q to %q: %w", sourcePath, destPath, err)
    57  	}
    58  
    59  	return nil
    60  }