tmpnet

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2024 License: BSD-3-Clause Imports: 44 Imported by: 0

README

tmpnet - temporary network orchestration

This package implements a simple orchestrator for the avalanchego nodes of a temporary network. Configuration is stored on disk, and nodes run as independent processes whose process details are also written to disk. Using the filesystem to store configuration and process details allows for the tmpnetctl cli and e2e test fixture to orchestrate the same temporary networks without the use of an rpc daemon.

What's in a name?

The name of this package was originally testnet and its cli was testnetctl. This name was chosen in ignorance that testnet commonly refers to a persistent blockchain network used for testing.

To avoid confusion, the name was changed to tmpnet and its cli tmpnetctl. tmpnet is short for temporary network since the networks it deploys are likely to live for a limited duration in support of the development and testing of avalanchego and its related repositories.

Package details

The functionality in this package is grouped by logical purpose into the following non-test files:

Filename Types Purpose
defaults.go Defines common default configuration
flags.go FlagsMap Simplifies configuration of avalanchego flags
genesis.go Creates test genesis
network.go Network Orchestrates and configures temporary networks
network_config.go Network Reads and writes network configuration
node.go Node Orchestrates and configures nodes
node_config.go Node Reads and writes node configuration
node_process.go NodeProcess Orchestrates node processes
subnet.go Subnet Orchestrates subnets
utils.go Defines shared utility functions

Usage

Via tmpnetctl

A temporary network can be managed by the tmpnetctl cli tool:

# From the root of the avalanchego repo

# Build the tmpnetctl binary
$ ./scripts/build_tmpnetctl.sh

# Start a new network
$ ./build/tmpnetctl start-network --avalanchego-path=/path/to/avalanchego
...
Started network /home/me/.tmpnet/networks/20240306-152305.924531 (UUID: abaab590-b375-44f6-9ca5-f8a6dc061725)

Configure tmpnetctl to target this network by default with one of the following statements:
 - source /home/me/.tmpnet/networks/20240306-152305.924531/network.env
 - export TMPNET_NETWORK_DIR=/home/me/.tmpnet/networks/20240306-152305.924531
 - export TMPNET_NETWORK_DIR=/home/me/.tmpnet/networks/latest

# Stop the network
$ ./build/tmpnetctl stop-network --network-dir=/path/to/network

Note the export of the path ending in latest. This is a symlink that is set to the last network created by tmpnetctl start-network. Setting the TMPNET_NETWORK_DIR env var to this symlink ensures that tmpnetctl commands and e2e execution with --use-existing-network will target the most recently deployed temporary network.

Via code

A temporary network can be managed in code:

network := &tmpnet.Network{                   // Configure non-default values for the new network
    DefaultFlags: tmpnet.FlagsMap{
        config.LogLevelKey: "INFO",           // Change one of the network's defaults
    },
    Subnets: []*tmpnet.Subnet{                // Subnets to create on the new network once it is running
        {
            Name: "xsvm-a",                   // User-defined name used to reference subnet in code and on disk
            Chains: []*tmpnet.Chain{
                {
                    VMName: "xsvm",           // Name of the VM the chain will run, will be used to derive the name of the VM binary
                    Genesis: <genesis bytes>, // Genesis bytes used to initialize the custom chain
                    PreFundedKey: <key>,      // (Optional) A private key that is funded in the genesis bytes
                },
            },
        },
    },
}

_ := tmpnet.StartNewNetwork(              // Start the network
    ctx,                                  // Context used to limit duration of waiting for network health
    ginkgo.GinkgoWriter,                  // Writer to report progress of initialization
    network,
    "",                                   // Empty string uses the default network path (~/tmpnet/networks)
    "/path/to/avalanchego",               // The path to the binary that nodes will execute
    "/path/to/plugins",                   // The path nodes will use for plugin binaries (suggested value ~/.avalanchego/plugins)
    5,                                    // Number of initial validating nodes
)

uris := network.GetNodeURIs()

// Use URIs to interact with the network

// Stop all nodes in the network
network.Stop(context.Background())

Networking configuration

By default, nodes in a temporary network will be started with staking and API ports set to 0 to ensure that ports will be dynamically chosen. The tmpnet fixture discovers the ports used by a given node by reading the [base-data-dir]/process.json file written by avalanchego on node start. The use of dynamic ports supports testing with many temporary networks without having to manually select compatible port ranges.

Configuration on disk

A temporary network relies on configuration written to disk in the following structure:

HOME
└── .tmpnet                                              // Root path for the temporary network fixture
    ├── prometheus                                       // Working directory for a metrics-scraping prometheus instance
    │   └── file_sd_configs                              // Directory containing file-based service discovery config for prometheus
    ├── promtail                                         // Working directory for a log-collecting promtail instance
    │   └── file_sd_configs                              // Directory containing file-based service discovery config for promtail
    └── networks                                         // Default parent directory for temporary networks
        └── 20240306-152305.924531                       // The timestamp of creation is the name of a network's directory
            ├── NodeID-37E8UK3x2YFsHE3RdALmfWcppcZ1eTuj9 // The ID of a node is the name of its data dir
            │   ├── chainData
            │   │   └── ...
            │   ├── config.json                          // Node runtime configuration
            │   ├── db
            │   │   └── ...
            │   ├── flags.json                           // Node flags
            │   ├── logs
            │   │   └── ...
            │   ├── plugins
            │   │   └── ...
            │   └── process.json                         // Node process details (PID, API URI, staking address)
            ├── chains
            │   ├── C
            │   │   └── config.json                      // C-Chain config for all nodes
            │   └── raZ51bwfepaSaZ1MNSRNYNs3ZPfj...U7pa3
            │       └── config.json                      // Custom chain configuration for all nodes
            ├── config.json                              // Common configuration (including defaults and pre-funded keys)
            ├── genesis.json                             // Genesis for all nodes
            ├── network.env                              // Sets network dir env var to simplify network usage
            └── subnets                                  // Parent directory for subnet definitions
                ├─ subnet-a.json                         // Configuration for subnet-a and its chain(s)
                └─ subnet-b.json                         // Configuration for subnet-b and its chain(s)
Common networking configuration

Network configuration such as default flags (e.g. --log-level=), runtime defaults (e.g. avalanchego path) and pre-funded private keys are stored at [network-dir]/config.json. A given default will only be applied to a new node on its addition to the network if the node does not explicitly set a given value.

Genesis

The genesis file is stored at [network-dir]/genesis.json and referenced by default by all nodes in the network. The genesis file content will be generated with reasonable defaults if not supplied. Each node in the network can override the default by setting an explicit value for --genesis-file or --genesis-file-content.

Chain configuration

The chain configuration for a temporary network is stored at [network-dir]/chains/[chain alias or ID]/config.json and referenced by all nodes in the network. The C-Chain config will be generated with reasonable defaults if not supplied. X-Chain and P-Chain will use implicit defaults. The configuration for custom chains can be provided with subnet configuration and will be writen to the appropriate path.

Each node in the network can override network-level chain configuration by setting --chain-config-dir to an explicit value and ensuring that configuration files for all chains exist at [custom-chain-config-dir]/[chain alias or ID]/config.json.

Network env

A shell script that sets the TMPNET_NETWORK_DIR env var to the path of the network is stored at [network-dir]/network.env. Sourcing this file (i.e. source network.env) in a shell will configure ginkgo e2e and the tmpnetctl cli to target the network path specified in the env var.

Set TMPNET_ROOT_DIR to specify the root directory in which to create the configuration directory of new networks (e.g. $TMPNET_ROOT_DIR/[network-dir]). The default root directory is ~/.tmpdir/networks. Configuring the root directory is only relevant when creating new networks as the path of existing networks will already have been set.

Node configuration

The data dir for a node is set by default to [network-path]/[node-id]. A node can be configured to use a non-default path by explicitly setting the --data-dir flag.

Runtime config

The details required to configure a node's execution are written to [network-path]/[node-id]/config.json. This file contains the runtime-specific details like the path of the avalanchego binary to start the node with.

Flags

All flags used to configure a node are written to [network-path]/[node-id]/flags.json so that a node can be configured with only a single argument: --config-file=/path/to/flags.json. This simplifies node launch and ensures all parameters used to launch a node can be modified by editing the config file.

Process details

The process details of a node are written by avalanchego to [base-data-dir]/process.json. The file contains the PID of the node process, the URI of the node's API, and the address other nodes can use to bootstrap themselves (aka staking address).

Metrics

Prometheus configuration

When nodes are started, prometheus configuration for each node is written to ~/.tmpnet/prometheus/file_sd_configs/ with a filename of [network uuid]-[node id].json. Prometheus can be configured to scrape the nodes as per the following example:

scrape_configs:
  - job_name: "avalanchego"
    metrics_path: "/ext/metrics"
    file_sd_configs:
      - files:
        - '/home/me/.tmpnet/prometheus/file_sd_configs/*.yaml'
Viewing metrics

When a network is started with tmpnet, a grafana link for the network's metrics will be emitted.

The metrics emitted by temporary networks configured with tmpnet will have the following labels applied:

  • network_uuid
  • node_id
  • is_ephemeral_node
  • network_owner

When a tmpnet network runs as part of github CI, the following additional labels will be applied:

  • gh_repo
  • gh_workflow
  • gh_run_id
  • gh_run_number
  • gh_run_attempt
  • gh_job_id

Documentation

Index

Constants

View Source
const (
	// Interval appropriate for network operations that should be
	// retried periodically but not too often.
	DefaultPollingInterval = 500 * time.Millisecond

	// Validator start time must be a minimum of SyncBound from the
	// current time for validator addition to succeed, and adding 20
	// seconds provides a buffer in case of any delay in processing.
	DefaultValidatorStartTimeDiff = executor.SyncBound + 20*time.Second

	DefaultNetworkTimeout = 2 * time.Minute

	// Minimum required to ensure connectivity-based health checks will pass
	DefaultNodeCount = 2

	// Arbitrary number of pre-funded keys to create by default
	DefaultPreFundedKeyCount = 50

	// A short minimum stake duration enables testing of staking logic.
	DefaultMinStakeDuration = time.Second
)
View Source
const (
	// Constants defining the names of shell variables whose value can
	// configure network orchestration.
	NetworkDirEnvName = "TMPNET_NETWORK_DIR"
	RootDirEnvName    = "TMPNET_ROOT_DIR"

	// eth address: 0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC
	HardHatKeyStr = "56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027"
)
View Source
const (
	AvalancheGoPathEnvName = "METALGO_PATH"
)
View Source
const (
	DefaultNodeTickerInterval = 50 * time.Millisecond
)

Variables

View Source
var ErrNotRunning = errors.New("not running")
View Source
var HardhatKey *secp256k1.PrivateKey

HardhatKey is a legacy used for hardhat testing in subnet-evm TODO(marun) Remove when no longer needed.

Functions

func DefaultChainConfigs

func DefaultChainConfigs() map[string]FlagsMap

A set of chain configurations appropriate for testing.

func DefaultJSONMarshal

func DefaultJSONMarshal(v interface{}) ([]byte, error)

Marshal to json with default prefix and indent.

func NewPrivateKeys

func NewPrivateKeys(keyCount int) ([]*secp256k1.PrivateKey, error)

Helper simplifying creation of a set of private keys

func NewTestGenesis

func NewTestGenesis(
	networkID uint32,
	nodes []*Node,
	keysToFund []*secp256k1.PrivateKey,
) (*genesis.UnparsedConfig, error)

Create a genesis struct valid for bootstrapping a test network. Note that many of the genesis fields (e.g. reward addresses) are randomly generated or hard-coded.

func RestartNetwork

func RestartNetwork(ctx context.Context, w io.Writer, dir string) error

Restarts the nodes of the network configured in the provided directory.

func StartNewNetwork

func StartNewNetwork(
	ctx context.Context,
	w io.Writer,
	network *Network,
	rootNetworkDir string,
	avalancheGoExecPath string,
	pluginDir string,
	nodeCount int,
) error

func StopNetwork

func StopNetwork(ctx context.Context, dir string) error

Stops the nodes of the network configured in the provided directory.

func WaitForHealthy

func WaitForHealthy(ctx context.Context, node *Node) error

WaitForHealthy blocks until Node.IsHealthy returns true or an error (including context timeout) is observed.

Types

type Chain

type Chain struct {
	// Set statically
	VMID    ids.ID
	Config  string
	Genesis []byte

	// Set at runtime
	ChainID      ids.ID
	PreFundedKey *secp256k1.PrivateKey
}

func (*Chain) WriteConfig

func (c *Chain) WriteConfig(chainDir string) error

Write the chain configuration to the specified directory.

type FlagsMap

type FlagsMap map[string]interface{}

Defines a mapping of flag keys to values intended to be supplied to an invocation of an AvalancheGo node.

func DefaultFlags

func DefaultFlags() FlagsMap

A set of flags appropriate for testing.

func ReadFlagsMap

func ReadFlagsMap(path string, description string) (*FlagsMap, error)

Utility function simplifying construction of a FlagsMap from a file.

func (FlagsMap) GetStringVal

func (f FlagsMap) GetStringVal(key string) (string, error)

GetStringVal simplifies retrieving a map value as a string.

func (FlagsMap) SetDefaults

func (f FlagsMap) SetDefaults(defaults FlagsMap)

SetDefaults ensures the effectiveness of flag overrides by only setting values supplied in the defaults map that are not already explicitly set.

func (FlagsMap) Write

func (f FlagsMap) Write(path string, description string) error

Write simplifies writing a FlagsMap to the provided path. The description is used in error messages.

type Network

type Network struct {
	// Uniquely identifies the temporary network for metrics
	// collection. Distinct from avalanchego's concept of network ID
	// since the utility of special network ID values (e.g. to trigger
	// specific fork behavior in a given network) precludes requiring
	// unique network ID values across all temporary networks.
	UUID string

	// A string identifying the entity that started or maintains this
	// network. Useful for differentiating between networks when a
	// given CI job uses multiple networks.
	Owner string

	// Path where network configuration and data is stored
	Dir string

	// Configuration common across nodes
	Genesis      *genesis.UnparsedConfig
	ChainConfigs map[string]FlagsMap

	// Default configuration to use when creating new nodes
	DefaultFlags         FlagsMap
	DefaultRuntimeConfig NodeRuntimeConfig

	// Keys pre-funded in the genesis on both the X-Chain and the C-Chain
	PreFundedKeys []*secp256k1.PrivateKey

	// Nodes that constitute the network
	Nodes []*Node

	// Subnets that have been enabled on the network
	Subnets []*Subnet
}

Collects the configuration for running a temporary avalanchego network

func ReadNetwork

func ReadNetwork(dir string) (*Network, error)

Reads a network from the provided directory.

func (*Network) AddEphemeralNode

func (n *Network) AddEphemeralNode(ctx context.Context, w io.Writer, flags FlagsMap) (*Node, error)

func (*Network) Create

func (n *Network) Create(rootDir string) error

Creates the network on disk, generating its genesis and configuring its nodes in the process.

func (*Network) CreateSubnets

func (n *Network) CreateSubnets(ctx context.Context, w io.Writer) error

Ensure that each subnet on the network is created and that it is validated by all non-ephemeral nodes.

func (*Network) EnsureDefaultConfig

func (n *Network) EnsureDefaultConfig(w io.Writer, avalancheGoPath string, pluginDir string, nodeCount int) error

Initializes a new network with default configuration.

func (*Network) EnsureNodeConfig

func (n *Network) EnsureNodeConfig(node *Node) error

Ensures the provided node has the configuration it needs to start. If the data dir is not set, it will be defaulted to [nodeParentDir]/[node ID]. For a not-yet-created network, no action will be taken. TODO(marun) Reword or refactor to account for the differing behavior pre- vs post-start

func (*Network) EnvFileContents

func (n *Network) EnvFileContents() string

func (*Network) EnvFilePath

func (n *Network) EnvFilePath() string

func (*Network) GetNodeURIs

func (n *Network) GetNodeURIs() []NodeURI

func (*Network) GetSubnet

func (n *Network) GetSubnet(name string) *Subnet

func (*Network) GetURIForNodeID

func (n *Network) GetURIForNodeID(nodeID ids.NodeID) (string, error)

func (*Network) Read

func (n *Network) Read() error

Read network and node configuration from disk.

func (*Network) Restart

func (n *Network) Restart(ctx context.Context, w io.Writer) error

Restarts all non-ephemeral nodes in the network.

func (*Network) Start

func (n *Network) Start(ctx context.Context, w io.Writer) error

Starts all nodes in the network

func (*Network) StartNode

func (n *Network) StartNode(ctx context.Context, w io.Writer, node *Node) error

Starts the provided node after configuring it for the network.

func (*Network) Stop

func (n *Network) Stop(ctx context.Context) error

Stops all nodes in the network.

func (*Network) WaitForHealthy

func (n *Network) WaitForHealthy(ctx context.Context, w io.Writer) error

Waits until all nodes in the network are healthy.

func (*Network) Write

func (n *Network) Write() error

Write network configuration to disk.

type Node

type Node struct {
	// Uniquely identifies the network the node is part of to enable monitoring.
	NetworkUUID string

	// Identify the entity associated with this network. This is
	// intended to be used to label metrics to enable filtering
	// results for a test run between the primary/shared network used
	// by the majority of tests and private networks used by
	// individual tests.
	NetworkOwner string

	// Set by EnsureNodeID which is also called when the node is read.
	NodeID ids.NodeID

	// Flags that will be supplied to the node at startup
	Flags FlagsMap

	// An ephemeral node is not expected to be a persistent member of the network and
	// should therefore not be used as for bootstrapping purposes.
	IsEphemeral bool

	// The configuration used to initialize the node runtime.
	RuntimeConfig *NodeRuntimeConfig

	// Runtime state, intended to be set by NodeRuntime
	URI            string
	StakingAddress string
	// contains filtered or unexported fields
}

Node supports configuring and running a node participating in a temporary network.

func NewNode

func NewNode(dataDir string) *Node

Initializes a new node with only the data dir set

func NewNodes

func NewNodes(count int) []*Node

Initializes the specified number of nodes.

func ReadNode

func ReadNode(dataDir string) (*Node, error)

Reads a node's configuration from the specified directory.

func ReadNodes

func ReadNodes(networkDir string, includeEphemeral bool) ([]*Node, error)

Reads nodes from the specified network directory.

func (*Node) EnsureBLSSigningKey

func (n *Node) EnsureBLSSigningKey() error

Ensures a BLS signing key is generated if not already present.

func (*Node) EnsureKeys

func (n *Node) EnsureKeys() error

Ensures staking and signing keys are generated if not already present and that the node ID (derived from the staking keypair) is set.

func (*Node) EnsureNodeID

func (n *Node) EnsureNodeID() error

Derives the node ID. Requires that a tls keypair is present.

func (*Node) EnsureStakingKeypair

func (n *Node) EnsureStakingKeypair() error

Ensures a staking keypair is generated if not already present.

func (*Node) GetProofOfPossession

func (n *Node) GetProofOfPossession() (*signer.ProofOfPossession, error)

Derives the nodes proof-of-possession. Requires the node to have a BLS signing key.

func (*Node) InitiateStop

func (n *Node) InitiateStop(ctx context.Context) error

func (*Node) IsHealthy

func (n *Node) IsHealthy(ctx context.Context) (bool, error)

func (*Node) Read

func (n *Node) Read() error

func (*Node) SaveAPIPort

func (n *Node) SaveAPIPort() error

Saves the currently allocated API port to the node's configuration for use across restarts. Reusing the port ensures consistent labeling of metrics.

func (*Node) SaveMetricsSnapshot

func (n *Node) SaveMetricsSnapshot(ctx context.Context) error

Writes the current state of the metrics endpoint to disk

func (*Node) SetNetworkingConfig

func (n *Node) SetNetworkingConfig(bootstrapIDs []string, bootstrapIPs []string)

Sets networking configuration for the node. Convenience method for setting networking flags.

func (*Node) Start

func (n *Node) Start(w io.Writer) error

func (*Node) Stop

func (n *Node) Stop(ctx context.Context) error

Initiates node shutdown and waits for the node to stop.

func (*Node) WaitForStopped

func (n *Node) WaitForStopped(ctx context.Context) error

func (*Node) Write

func (n *Node) Write() error

type NodeProcess

type NodeProcess struct {
	// contains filtered or unexported fields
}

Defines local-specific node configuration. Supports setting default and node-specific values.

func (*NodeProcess) InitiateStop

func (p *NodeProcess) InitiateStop() error

Signals the node process to stop.

func (*NodeProcess) IsHealthy

func (p *NodeProcess) IsHealthy(ctx context.Context) (bool, error)

func (*NodeProcess) Start

func (p *NodeProcess) Start(w io.Writer) error

Start waits for the process context to be written which indicates that the node will be accepting connections on its staking port. The network will start faster with this synchronization due to the avoidance of exponential backoff if a node tries to connect to a beacon that is not ready.

func (*NodeProcess) WaitForStopped

func (p *NodeProcess) WaitForStopped(ctx context.Context) error

Waits for the node process to stop.

type NodeRuntime

type NodeRuntime interface {
	Start(w io.Writer) error
	InitiateStop() error
	WaitForStopped(ctx context.Context) error
	IsHealthy(ctx context.Context) (bool, error)
	// contains filtered or unexported methods
}

NodeRuntime defines the methods required to support running a node.

type NodeRuntimeConfig

type NodeRuntimeConfig struct {
	AvalancheGoPath string
}

Configuration required to configure a node runtime.

type NodeURI

type NodeURI struct {
	NodeID ids.NodeID
	URI    string
}

NodeURI associates a node ID with its API URI.

func GetNodeURIs

func GetNodeURIs(nodes []*Node) []NodeURI

type Subnet

type Subnet struct {
	// A unique string that can be used to refer to the subnet across different temporary
	// networks (since the SubnetID will be different every time the subnet is created)
	Name string

	// The ID of the transaction that created the subnet
	SubnetID ids.ID

	// The private key that owns the subnet
	OwningKey *secp256k1.PrivateKey

	// IDs of the nodes responsible for validating the subnet
	ValidatorIDs []ids.NodeID

	Chains []*Chain
}

func (*Subnet) AddValidators

func (s *Subnet) AddValidators(ctx context.Context, w io.Writer, nodes []*Node) error

Add validators to the subnet

func (*Subnet) Create

func (s *Subnet) Create(ctx context.Context, uri string) error

Issues the subnet creation transaction and retains the result. The URI of a node is required to issue the transaction.

func (*Subnet) CreateChains

func (s *Subnet) CreateChains(ctx context.Context, w io.Writer, uri string) error

func (*Subnet) GetWallet

func (s *Subnet) GetWallet(ctx context.Context, uri string) (primary.Wallet, error)

Retrieves a wallet configured for use with the subnet

func (*Subnet) HasChainConfig

func (s *Subnet) HasChainConfig() bool

HasChainConfig indicates whether at least one of the subnet's chains have explicit configuration. This can be used to determine whether validator restart is required after chain creation to ensure that chains are configured correctly.

func (*Subnet) Write

func (s *Subnet) Write(subnetDir string, chainDir string) error

Write the subnet configuration to disk

type XChainBalanceMap

type XChainBalanceMap map[ids.ShortID]uint64

Helper type to simplify configuring X-Chain genesis balances

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL