tmpnet

package
v1.13.1-cache-cleanup Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2025 License: BSD-3-Clause Imports: 69 Imported by: 37

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.

Table of Contents

What's in a name?

Top

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

Top

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

Filename Types Purpose
flags/ Directory defining flags usable with both stdlib flags and spf13/pflag
flags/common.go Defines type definitions common across other files
flags/process_runtime.go Defines flags configuring the process node runtime
flags/runtime.go Defines flags configuring node runtime
flags/start_network.go Defines flags configuring network start
tmpnetctl/ Directory containing main entrypoint for tmpnetctl command
check_monitoring.go Enables checking if logs and metrics were collected
defaults.go Defines common default configuration
detached_process_default.go Configures detached processes for darwin and linux
detached_process_windows.go No-op detached process configuration for windows
flagsmap.go FlagsMap Simplifies configuration of avalanchego flags
genesis.go Creates test genesis
kube.go Library for Kubernetes interaction
local_network.go Defines configuration for the default local network
monitor_processes.go Enables collection of logs and metrics from local processes
network.go Network Orchestrates and configures temporary networks
network_config.go Network Reads and writes network configuration
network_test.go Simple test round-tripping Network serialization
node.go Node Orchestrates and configures nodes
node_config.go Node Reads and writes node configuration
process_runtime.go ProcessRuntime Orchestrates node processes
start_kind_cluster.go Starts a local kind cluster
subnet.go Subnet Orchestrates subnets
utils.go Defines shared utility functions

Usage

Via tmpnetctl

Top

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

# From the root of the avalanchego repo

# Start a new network. Possible to specify the number of nodes (> 1) with --node-count.
$ ./bin/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
$ ./bin/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 target the most recently deployed temporary network.

Deprecated usage with e2e suite

Top

tmpnetctl was previously used to create temporary networks for use across multiple e2e test runs. As the usage of temporary networks has expanded to require subnets, that usage has been supplanted by the --reuse-network flag defined for the e2e suite. It was easier to support defining subnet configuration in the e2e suite in code than to extend a cli tool like tmpnetctl to support similar capabilities.

Simplifying usage with direnv

Top

The repo includes a .envrc that can be applied by direnv when in a shell. This will enable tmpnetctl to be invoked directly (without a ./bin/ prefix ) and without having to specify the --avalanchego-path or --plugin-dir flags.

Via code

Top

A temporary network can be managed in code:

network := &tmpnet.Network{                         // Configure non-default values for the new network
    DefaultRuntimeConfig: tmpnet.NodeRuntimeConfig{
        Process: &tmpnet.ProcessRuntimeConfig{
            ReuseDynamicPorts: true,                // Configure process-based nodes to reuse a dynamically allocated API port when restarting
        },
    }
    DefaultFlags: tmpnet.FlagsMap{
        config.LogLevelKey: "INFO",                 // Change one of the network's defaults
    },
    Nodes: tmpnet.NewNodesOrPanic(5),               // Number of initial validating nodes
    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
                    VersionArgs: "version-json", // (Optional) Arguments that prompt the VM binary to output version details in json format.
                                                 // If one or more arguments are provided, the resulting json output should include a field
                                                 // named `rpcchainvm` of type uint64 containing the rpc version supported by the VM binary.
                                                 // The version will be checked against the version reported by the configured avalanchego
                                                 // binary before network and node start.
                },
            },
            ValidatorIDs: <node ids>,         // The IDs of nodes that validate the subnet
        },
    },
}

_ := tmpnet.BootstrapNewNetwork(          // Bootstrap 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)
)

uris := network.GetNodeURIs()

// Use URIs to interact with the network

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

Networking configuration

Top

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

Top

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)
            ├── config.json                              // tmpnet configuration for the network
            ├── genesis.json                             // Genesis for all nodes
            ├── metrics.txt                              // Link for metrics and logs collected from the network (see: Monitoring)
            ├── network.env                              // Sets network dir env var to simplify network usage
            └── subnets                                  // Directory containing tmpnet subnet configuration
                ├── subnet-a.json                        // tmpnet configuration for subnet-a and its chain(s)
                └── subnet-b.json                        // tmpnet configuration for subnet-b and its chain(s)
Common networking configuration

Top

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 default for a given flag will only be applied to a node if that node does not itself set a value for that flag.

Genesis

Top

The genesis file is stored at [network-dir]/genesis.json. The genesis file content will be generated with reasonable defaults if not supplied. The content of the file is provided to each node via the --genesis-file-content flag if a node does not set a value for the flag.

Subnet and chain configuration

Top

tmpnet configuration for a given subnet and its chain(s) is stored at [network-dir]/subnets/[subnet name].json. Subnet configuration for all subnets is provided to each node via the --subnet-config-content flag if a node does not set a value for the flag. Chain configuration for all chains is provided to each node via the --chain-config-content flag where a node does not set a value for the flag.

Network env

Top

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_NETWORK_DIR to specify the root network directory in which to create the configuration directory of new networks (e.g. TMPNET_ROOT_NETWORK_DIR/[network-dir]). The default network root directory is ~/.tmpdir/networks. Configuring the network root directory is only relevant when creating new networks as the path of existing networks will already have been set.

Node configuration

Top

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

Top

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

Top

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

Top

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).

Monitoring

Top

Monitoring is an essential part of understanding the workings of a distributed system such as avalanchego. The tmpnet fixture enables collection of logs and metrics from temporary networks to a monitoring stack (prometheus+loki+grafana) to enable results to be analyzed and shared.

Example usage

Top

# Start a nix shell to ensure the availability of promtail and prometheus.
nix develop

# Enable collection of logs and metrics
PROMETHEUS_USERNAME=<username> \
PROMETHEUS_PASSWORD=<password> \
LOKI_USERNAME=<username> \
LOKI_PASSWORD=<password> \
./bin/tmpnetctl start-collectors

# Network start emits link to grafana displaying collected logs and metrics
./bin/tmpnetctl start-network

# When done with the network, stop the collectors
./bin/tmpnetctl stop-collectors
Starting collectors

Top

Collectors for logs and metrics can be started by tmpnetctl start-collectors:

  • Requires that the following env vars be set
    • PROMETHEUS_USERNAME
    • PROMETHEUS_PASSWORD
    • LOKI_USERNAME
    • LOKI_PASSWORD
  • Requires that binaries for promtail and prometheus be available in the path
    • Starting a development shell with nix develop is one way to ensure this and requires the installation of nix.
  • Starts prometheus in agent mode configured to scrape metrics from configured nodes and forward them to https://prometheus-poc.avax-dev.network.
  • Starts promtail configured to collect logs from configured nodes and forward them to https://loki-poc.avax-dev.network.
Stopping collectors

Collectors for logs and metrics can be stopped by tmpnetctl stop-collectors:

Metrics collection

Top

When a node is started, configuration enabling collection of metrics from the node is written to ~/.tmpnet/prometheus/file_sd_configs/[network uuid]-[node id].json.

Log collection

Top

Nodes log are stored at ~/.tmpnet/networks/[network id]/[node id]/logs by default, and can optionally be forwarded to loki with promtail.

When a node is started, promtail configuration enabling collection of logs for the node is written to ~/.tmpnet/promtail/file_sd_configs/[network uuid]-[node id].json.

Labels

Top

The logs and metrics collected for temporary networks will have the following labels applied:

  • network_uuid
    • uniquely identifies a network across hosts
  • node_id
  • is_ephemeral_node
    • 'ephemeral' nodes are expected to run for only a fraction of the life of a network
  • network_owner
    • an arbitrary string that can be used to differentiate results when a CI job runs more than one network

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

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

These labels are sourced from Github Actions' github context as per https://docs.github.com/en/actions/learn-github-actions/contexts#github-context.

CI Collection

Top

A custom github action exists to simplify collection of logs and metrics from CI. The action takes care of invoking a nix shell to ensure the availability of binary dependencies, configures tmpnet to collect metrics and ensures that the tmpnet path is collected as a github artifact to aid in troubleshooting.

Example usage:

- name: Run e2e tests

  # A qualified path is required for use outside of avalanchego
  # e.g. `ava-labs/avalanchego/.github/actions/run-monitored-tmpnet-cmd@[sha or tag]`
  uses: ./.github/actions/run-monitored-tmpnet-cmd #

  with:
    # This needs to be the path to a bash script
    run: ./scripts/tests.e2e.sh

    # Env vars for the script need to be provided via run_env as a space-separated string
    # e.g. `MY_VAR1=foo MY_VAR2=bar`
    run_env: E2E_SERIAL=1

    # Sets the prefix of the artifact containing the tmpnet network dir for this job.
    # Only required if a workflow uses this action more than once so that each artifact
    # will have a unique name.
    artifact_prefix: e2e

    # These credentials are mandatory
    prometheus_username: ${{ secrets.PROMETHEUS_ID || '' }}
    prometheus_password: ${{ secrets.PROMETHEUS_PASSWORD || '' }}
    loki_username: ${{ secrets.LOKI_ID || '' }}
    loki_password: ${{ secrets.LOKI_PASSWORD || '' }}
Viewing
Local networks

Top

When a network is started with tmpnet, a link to the default grafana instance will be emitted. The dashboards will only be populated if prometheus and promtail are running locally (as per previous sections) to collect metrics and logs.

CI

Top

Collection of logs and metrics is enabled for CI jobs that use tmpnet. Each job will execute a step including the script notify-metrics-availability.sh that emits a link to grafana parameterized to show results for the job.

Additional links to grafana parameterized to show results for individual network will appear in the logs displaying the start of those networks.

In cases where a given job uses private networks in addition to the usual shared network, it may be useful to parameterize the run_monitored_tmpnet_action github action with filter_by_owner set to the owner string for the shared network. This ensures that the link emitted by the annotation displays results for only the shared network of the job rather than mixing results from all the networks started for the job.

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 = "1s"
)
View Source
const (
	// Constants defining the names of shell variables whose value can
	// configure network orchestration.
	RootNetworkDirEnvName = "TMPNET_ROOT_NETWORK_DIR"
	NetworkDirEnvName     = "TMPNET_NETWORK_DIR"

	// Message to log indicating where to look for metrics and logs for network
	MetricsAvailableMessage = "metrics and logs available via grafana (collectors must be running)"

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

	// Use a delay slightly longer than the scrape interval to ensure a final scrape before shutdown
	NetworkShutdownDelay = prometheusScrapeInterval + 2*time.Second
)

Variables

View Source
var (
	AvalancheGoPluginDirEnvName = config.EnvVarName(config.EnvPrefix, config.PluginDirKey)
)
View Source
var ErrUnrecoverableNodeHealthCheck = errors.New("failed to query node health")
View Source
var (
	// Key expected to be funded for subnet-evm hardhat testing
	// TODO(marun) Remove when subnet-evm configures the genesis with this key.
	HardhatKey *secp256k1.PrivateKey
)

Functions

func BootstrapNewNetwork added in v1.11.7

func BootstrapNewNetwork(
	ctx context.Context,
	log logging.Logger,
	network *Network,
	rootNetworkDir string,
) error

func CheckClusterRunning added in v1.13.0

func CheckClusterRunning(log logging.Logger, configPath string, configContext string) error

CheckClusterRunning checks if the configured cluster is accessible. TODO(marun) Maybe differentiate between configuration and endpoint errors

func CheckLogsExist added in v1.13.0

func CheckLogsExist(ctx context.Context, log logging.Logger, networkUUID string) error

CheckLogsExist checks if logs exist for the given network. If no network UUID is provided, an attempt will be made to derive selectors from env vars (GH_*) identifying a github actions run.

func CheckMetricsExist added in v1.13.0

func CheckMetricsExist(ctx context.Context, log logging.Logger, networkUUID string) error

CheckMetricsExist checks if metrics exist for the given network. Github labels are also used as filters if provided as env vars (GH_*).

func CheckMonitoring added in v1.13.0

func CheckMonitoring(ctx context.Context, log logging.Logger, networkUUID string) error

CheckMonitoring checks if logs and metrics exist for the given network. If no network UUID is provided, an attempt will be made to derive selectors from env vars (GH_*) identifying a github actions run.

func CheckNodeHealth added in v1.11.12

func CheckNodeHealth(ctx context.Context, uri string) (*health.APIReply, error)

func DefaultChainConfigs added in v1.10.18

func DefaultChainConfigs() map[string]ConfigMap

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 DefaultPodFlags added in v1.11.13

func DefaultPodFlags(networkName string, dataDir string) map[string]string

DefaultPodFlags defines common flags for avalanchego nodes running in a pod.

func GetClientConfig added in v1.13.0

func GetClientConfig(log logging.Logger, path string, context string) (*restclient.Config, error)

GetClientConfig replicates the behavior of clientcmd.BuildConfigFromFlags with zap logging and support for an optional config context. If path is not provided, use of in-cluster config will be attempted.

func GetClientset added in v1.13.0

func GetClientset(log logging.Logger, path string, context string) (*kubernetes.Clientset, error)

GetClientset returns a kubernetes clientset for the provided kubeconfig path and context.

func GetEnvWithDefault added in v1.13.0

func GetEnvWithDefault(envVar, defaultVal string) string

func GetReusableNetworkPathForOwner added in v1.11.5

func GetReusableNetworkPathForOwner(owner string) (string, error)

Retrieves the path to a reusable network path for the given owner.

func MetricsLinkForNetwork added in v1.11.12

func MetricsLinkForNetwork(networkUUID string, startTime string, endTime string) string

MetricsLinkForNetwork returns a link to the default metrics dashboard for the network with the given UUID. The start and end times are accepted as strings to support the use of Grafana's time range syntax (e.g. `now`, `now-1h`).

func NewNodeStatefulSet added in v1.11.13

func NewNodeStatefulSet(
	name string,
	imageName string,
	containerName string,
	volumeName string,
	volumeSize string,
	volumeMountPath string,
	flags map[string]string,
) *appsv1.StatefulSet

NewNodeStatefulSet returns a statefulset for an avalanchego node.

func NewPrivateKeys added in v1.10.18

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 NodesToIDs added in v1.11.4

func NodesToIDs(nodes ...*Node) []ids.NodeID

func RestartNetwork added in v1.10.18

func RestartNetwork(ctx context.Context, log logging.Logger, dir string) error

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

func StartCollectors added in v1.13.0

func StartCollectors(ctx context.Context, log logging.Logger) error

StartCollectors ensures collectors are running to collect logs and metrics from local nodes.

func StartKindCluster added in v1.13.0

func StartKindCluster(ctx context.Context, log logging.Logger, configPath string, configContext string) error

StartKindCluster starts a new kind cluster if one is not already running.

func StopCollectors added in v1.13.0

func StopCollectors(ctx context.Context, log logging.Logger) error

EnsureCollectorsStopped ensures collectors are not running.

func StopNetwork added in v1.10.18

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

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

func WaitForActiveValidators added in v1.11.10

func WaitForActiveValidators(
	ctx context.Context,
	log logging.Logger,
	pChainClient platformvm.Client,
	subnet *Subnet,
) error

func WaitForNodeHealthy added in v1.11.13

func WaitForNodeHealthy(
	ctx context.Context,
	log logging.Logger,
	kubeconfig *restclient.Config,
	namespace string,
	podName string,
	healthCheckInterval time.Duration,
	out io.Writer,
	outErr io.Writer,
) (ids.NodeID, error)

WaitForNodeHealthy waits for the node running in the specified pod to report healthy.

func WaitForPodCondition added in v1.11.13

func WaitForPodCondition(ctx context.Context, clientset *kubernetes.Clientset, namespace string, podName string, conditionType corev1.PodConditionType) error

WaitForPodCondition watches the specified pod until the status includes the specified condition.

func WaitForPodStatus added in v1.11.13

func WaitForPodStatus(
	ctx context.Context,
	clientset *kubernetes.Clientset,
	namespace string,
	name string,
	acceptable func(*corev1.PodStatus) bool,
) error

WaitForPodStatus watches the specified pod until the status is deemed acceptable by the provided test function.

func WaitForPromtailReadiness added in v1.13.0

func WaitForPromtailReadiness(ctx context.Context, log logging.Logger) error

WaitForPromtailReadiness waits until prometheus is ready. It can only succeed after one or more nodes have written their service discovery configuration.

Types

type Chain added in v1.10.18

type Chain struct {
	// Set statically
	VMID    ids.ID
	Config  string
	Genesis []byte
	// VersionArgs are the argument(s) to pass to the VM binary to receive
	// version details in json format (e.g. `--version-json`). This
	// supports checking that the rpcchainvm version of the VM binary
	// matches the version used by the configured avalanchego binary. If
	// empty, the version check will be skipped.
	VersionArgs []string

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

type ConfigMap added in v1.13.1

type ConfigMap map[string]any

ConfigMap enables defining configuration in a format appropriate for round-tripping through JSON back to golang structs.

type FlagsMap

type FlagsMap map[string]string

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

func DefaultE2EFlags added in v1.13.1

func DefaultE2EFlags() FlagsMap

Flags suggested for e2e testing

func DefaultTmpnetFlags added in v1.11.6

func DefaultTmpnetFlags() FlagsMap

Flags suggested for temporary networks. Applied by default.

func ReadFlagsMap

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

Utility function simplifying construction of a FlagsMap from a file.

func (FlagsMap) SetDefault added in v1.13.1

func (f FlagsMap) SetDefault(key string, value string)

SetDefault ensures the effectiveness of a flag override by only setting a value supplied whose key is not already explicitly set.

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

	// Id of the network. If zero, must be set in Genesis. Consider
	// using the GetNetworkID method if needing to retrieve the ID of
	// a running network.
	NetworkID uint32

	// Genesis for the network. If nil, NetworkID must be non-zero
	Genesis *genesis.UnparsedConfig

	// Configuration for primary subnets
	PrimarySubnetConfig ConfigMap

	// Configuration for primary network chains (P, X, C)
	PrimaryChainConfigs map[string]ConfigMap

	// 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
	// contains filtered or unexported fields
}

Collects the configuration for running a temporary avalanchego network

func LocalNetworkOrPanic added in v1.11.6

func LocalNetworkOrPanic() *Network

func NewDefaultNetwork added in v1.11.6

func NewDefaultNetwork(owner string) *Network

func ReadNetwork added in v1.10.18

func ReadNetwork(ctx context.Context, log logging.Logger, dir string) (*Network, error)

Reads a network from the provided directory.

func (*Network) Bootstrap added in v1.11.7

func (n *Network) Bootstrap(ctx context.Context, log logging.Logger) error

Start the network for the first time

func (*Network) Create added in v1.10.18

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 added in v1.10.18

func (n *Network) CreateSubnets(ctx context.Context, log logging.Logger, apiURI string, restartRequired bool) error

Ensure that each subnet on the network is created. If restartRequired is false, node restart to pick up configuration changes becomes the responsibility of the caller.

func (*Network) DefaultGenesis added in v1.11.11

func (n *Network) DefaultGenesis() (*genesis.UnparsedConfig, error)

func (*Network) EnsureDefaultConfig added in v1.10.18

func (n *Network) EnsureDefaultConfig(log logging.Logger) error

Initializes a new network with default configuration.

func (*Network) EnsureNodeConfig added in v1.10.18

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].

func (*Network) EnvFileContents added in v1.10.18

func (n *Network) EnvFileContents() string

func (*Network) EnvFilePath added in v1.10.18

func (n *Network) EnvFilePath() string

func (*Network) GetBootstrapIPsAndIDs added in v1.13.1

func (n *Network) GetBootstrapIPsAndIDs(skippedNode *Node) ([]string, []string)

Retrieves bootstrap IPs and IDs for all non-ephemeral nodes except the skipped one (this supports collecting the bootstrap details for restarting a node).

For consumption outside of avalanchego. Needs to be kept exported.

func (*Network) GetChainConfigContent added in v1.13.1

func (n *Network) GetChainConfigContent() (string, error)

GetChainConfigContent returns the base64-encoded and JSON-marshaled map of chain alias/ID to JSON-marshaled chain configuration for both primary and custom chains.

func (*Network) GetGenesisFileContent added in v1.13.1

func (n *Network) GetGenesisFileContent() (string, error)

GetGenesisFileContent returns the base64-encoded JSON-marshaled network genesis.

func (*Network) GetGenesisPath added in v1.13.1

func (n *Network) GetGenesisPath() string

For consumption outside of avalanchego. Needs to be kept exported.

func (*Network) GetNetworkID added in v1.11.11

func (n *Network) GetNetworkID() uint32

GetNetworkID returns the effective ID of the network. If the network defines a genesis, the network ID in the genesis will be returned. If a genesis is not present (i.e. a network with a genesis included in the avalanchego binary - mainnet, testnet and local), the value of the NetworkID field will be returned

func (*Network) GetNode added in v1.13.0

func (n *Network) GetNode(nodeID ids.NodeID) (*Node, error)

func (*Network) GetNodeURIs added in v1.10.18

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

func (*Network) GetSubnet added in v1.10.18

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

func (*Network) GetSubnetConfigContent added in v1.13.1

func (n *Network) GetSubnetConfigContent() (string, error)

GetSubnetConfigContent returns the base64-encoded and JSON-marshaled map of subnetID to subnet configuration.

func (*Network) GetSubnetDir added in v1.11.10

func (n *Network) GetSubnetDir() string

func (*Network) Read added in v1.10.18

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

Read network and node configuration from disk.

func (*Network) Restart added in v1.10.18

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

Restarts all nodes in the network.

func (*Network) RestartNode added in v1.11.4

func (n *Network) RestartNode(ctx context.Context, node *Node) error

Restart a single node.

func (*Network) StartNode added in v1.10.18

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

Starts the provided node after configuring it for the network.

func (*Network) StartNodes added in v1.11.7

func (n *Network) StartNodes(ctx context.Context, log logging.Logger, nodesToStart ...*Node) error

Starts the specified nodes

func (*Network) Stop added in v1.10.18

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

Stops all nodes in the network.

func (*Network) TrackedSubnetsForNode added in v1.11.4

func (n *Network) TrackedSubnetsForNode(nodeID ids.NodeID) string

TrackedSubnetsForNode returns the subnet IDs for the given node

func (*Network) Write added in v1.10.18

func (n *Network) Write() error

Write network configuration to disk.

type Node

type Node struct {
	// Set by EnsureNodeID which is also called when the node is read.
	NodeID ids.NodeID

	// The set of flags used to start whose values are intended to deviate from the
	// default set of flags configured for the network.
	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

	// Optional, the configuration used to initialize the node runtime.
	// If not set, the network default will be used.
	RuntimeConfig *NodeRuntimeConfig

	// Runtime state, intended to be set by NodeRuntime
	URI            string
	StakingAddress netip.AddrPort

	// Defaults to [network dir]/[node id] if not set
	DataDir string
	// contains filtered or unexported fields
}

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

func NewEphemeralNode added in v1.11.4

func NewEphemeralNode(flags FlagsMap) *Node

Initializes an ephemeral node using the provided config flags

func NewNode added in v1.10.18

func NewNode() *Node

Initializes a new node with only the data dir set

func NewNodesOrPanic added in v1.11.6

func NewNodesOrPanic(count int) []*Node

Initializes the specified number of nodes.

func (*Node) EnsureBLSSigningKey added in v1.10.18

func (n *Node) EnsureBLSSigningKey() error

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

func (*Node) EnsureKeys added in v1.10.18

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 added in v1.10.18

func (n *Node) EnsureNodeID() error

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

func (*Node) EnsureStakingKeypair added in v1.10.18

func (n *Node) EnsureStakingKeypair() error

Ensures a staking keypair is generated if not already present.

func (*Node) GetFlagsPath added in v1.13.1

func (n *Node) GetFlagsPath() string

For consumption outside of avalanchego. Needs to be kept exported.

func (*Node) GetLocalStakingAddress added in v1.13.0

func (n *Node) GetLocalStakingAddress(ctx context.Context) (netip.AddrPort, func(), error)

func (*Node) GetLocalURI added in v1.13.0

func (n *Node) GetLocalURI(ctx context.Context) (string, func(), error)

func (*Node) GetProofOfPossession added in v1.10.18

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

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

func (*Node) GetUniqueID added in v1.12.2

func (n *Node) GetUniqueID() string

GetUniqueID returns a globally unique identifier for the node.

func (*Node) InitiateStop added in v1.10.18

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

func (*Node) IsHealthy

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

func (*Node) Read added in v1.10.18

func (n *Node) Read(ctx context.Context, network *Network, dataDir string) error

func (*Node) SaveAPIPort added in v1.11.3

func (n *Node) SaveAPIPort() error

Saves the currently allocated API port to the node's configuration for use across restarts.

func (*Node) SaveMetricsSnapshot added in v1.10.18

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

Writes the current state of the metrics endpoint to disk

func (*Node) Start added in v1.10.18

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

func (*Node) Stop

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

Initiates node shutdown and waits for the node to stop.

func (*Node) WaitForHealthy added in v1.13.1

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

WaitForHealthy blocks until node health is true or an error (including context timeout) is observed.

func (*Node) WaitForStopped added in v1.10.18

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

func (*Node) Write added in v1.10.18

func (n *Node) Write() error

type NodeRuntime added in v1.10.18

type NodeRuntime interface {
	GetLocalURI(ctx context.Context) (string, func(), error)
	GetLocalStakingAddress(ctx context.Context) (netip.AddrPort, func(), error)
	Start(ctx context.Context) error
	InitiateStop(ctx context.Context) 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 added in v1.10.18

type NodeRuntimeConfig struct {
	Process *ProcessRuntimeConfig `json:"process,omitempty"`
}

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 added in v1.10.18

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

type ProcessRuntime added in v1.13.1

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

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

func (*ProcessRuntime) GetLocalStakingAddress added in v1.13.1

func (p *ProcessRuntime) GetLocalStakingAddress(_ context.Context) (netip.AddrPort, func(), error)

func (*ProcessRuntime) GetLocalURI added in v1.13.1

func (p *ProcessRuntime) GetLocalURI(_ context.Context) (string, func(), error)

func (*ProcessRuntime) InitiateStop added in v1.13.1

func (p *ProcessRuntime) InitiateStop(_ context.Context) error

Signals the node process to stop.

func (*ProcessRuntime) IsHealthy added in v1.13.1

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

func (*ProcessRuntime) Start added in v1.13.1

func (p *ProcessRuntime) Start(ctx context.Context) 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 (*ProcessRuntime) WaitForStopped added in v1.13.1

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

Waits for the node process to stop.

type ProcessRuntimeConfig added in v1.13.1

type ProcessRuntimeConfig struct {
	AvalancheGoPath   string `json:"avalancheGoPath,omitempty"`
	PluginDir         string `json:"pluginDir,omitempty"`
	ReuseDynamicPorts bool   `json:"reuseDynamicPorts,omitempty"`
}

type RPCChainVMVersion added in v1.11.11

type RPCChainVMVersion struct {
	RPCChainVM uint64 `json:"rpcchainvm"`
}

type Subnet added in v1.10.18

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

	Config ConfigMap

	// 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 added in v1.10.18

func (s *Subnet) AddValidators(ctx context.Context, log logging.Logger, apiURI string, nodes ...*Node) error

Add validators to the subnet

func (*Subnet) Create added in v1.10.18

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 added in v1.10.18

func (s *Subnet) CreateChains(ctx context.Context, log logging.Logger, uri string) error

func (*Subnet) GetWallet added in v1.10.18

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

Retrieves a wallet configured for use with the subnet

func (*Subnet) HasChainConfig added in v1.11.0

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 added in v1.10.18

func (s *Subnet) Write(subnetDir 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