network

package
v0.29.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package network is vm-manager's rootless software-defined network. Every network is one gvisor-tap-vsock VirtualNetwork: a userspace Ethernet switch plus a gVisor TCP/IP stack that acts as the network's gateway, DHCP server, DNS forwarder and NAT. No tap devices, bridges, iptables or CAP_NET_ADMIN are involved, so the same code runs on a developer laptop, in a rootless container and on a GitHub Actions runner.

Network model

A Manager owns the networks of one vm-manager process. Each Network is a separate L2 segment; VMs on different networks cannot see each other even when their CIDRs overlap, because every network has its own switch and stack. QEMU attaches to a network through a unix socket under the state dir, <state>/networks/<name>/qemu.sock, speaking the QEMU "stream" netdev framing (each Ethernet frame prefixed by its 32-bit big-endian length). A goroutine accepts connections for the lifetime of the network, so any number of VMs can join and a VM whose vm-manager restarted simply reconnects (QEMU is started with reconnect-ms).

Addressing

For a network with CIDR a.b.c.0/24:

a.b.c.0     network address
a.b.c.1     gateway: default route, DHCP server, DNS forwarder (Spec.GatewayIP overrides)
a.b.c.2-253 pool handed to VMs by Attach, lowest free address first
a.b.c.254   host alias: with Spec.EnableHostAlias the VM reaches the host's loopback here
a.b.c.255   broadcast

The IMDS address 169.254.169.254 is a virtual IP of the gateway: the gateway answers ARP for it, and Network.ListenIMDS opens a TCP listener on 169.254.169.254:80 inside the stack, so the guest talks to the metadata service exactly as it would on a cloud. Connections to the IMDS address without a listener are refused rather than forwarded to the host.

MAC addresses are derived, not random: 02:xx:aa:bb:cc:dd where 02 marks a locally administered unicast address, xx hashes the network name and the remaining four bytes are the IPv4 address (the convention Docker uses). DHCP leases are therefore static by construction: the network pre-registers every pool address with its MAC in the gateway's DHCP server, Network.Attach picks a free slot and returns its MAC and IP, and the guest's DHCP DISCOVER gets exactly that IP back. This is also why vm-manager never lets the library allocate dynamically: gvisor-tap-vsock only accepts static leases when the stack is created, and a network must keep serving running VMs while new ones attach. A MAC the network does not know gets no lease.

Which VM holds which address is the only mutable state; Network.State exports it and Manager.Restore rebuilds networks from it after a restart, so a VM keeps its IP (and MAC) for its whole life. Persisting the state is the caller's job.

What the runtime passes to QEMU

Attachment.QEMUArgs yields the two arguments the QEMU runtime appends:

-netdev stream,id=net0,addr.type=unix,addr.path=<state>/networks/<name>/qemu.sock,reconnect-ms=1000
-device virtio-net-pci,netdev=net0,mac=02:xx:aa:bb:cc:dd

The guest sees a plain virtio NIC and configures it with DHCP; the reply carries the gateway as router and DNS server, the subnet mask, the MTU and Spec.DNSSearchDomain. DNS names are resolved by the host's resolver.

Host access

Outbound traffic from a VM is dialed from the host process, so the VM can reach whatever the host can reach (NAT). With Spec.EnableHostAlias the host alias address is translated to 127.0.0.1 so a VM can also use services bound to the host's loopback; it is off by default because that includes vm-manager's own API. In the other direction Network.Dial opens a TCP connection into the network from the host (ssh, kube-apiserver readiness) and Network.Forward exposes a VM port on a host address with a plain accept-and-proxy loop.

Limitations

Every packet is copied through userspace and terminated by a Go TCP stack; expect hundreds of Mbit/s rather than line rate, and no UDP or ICMP from the host into the network. gvisor-tap-vsock cannot stop a stack once created, so the goroutines of a deleted network's DHCP and DNS servers linger until the process exits, and the library logs through the global logrus logger, which the command wiring should redirect. Only IPv4 is supported.

A kernel-backed backend (tap devices on a bridge with systemd-networkd doing DHCP and masquerading) would implement the same Manager and Network API: Attach would return "-netdev tap,fd=N" style arguments instead of the stream socket, Dial and Forward would use the host's own stack, and ListenIMDS would bind 169.254.169.254 on the bridge. Nothing in internal/vm needs to know which backend is active.

Index

Constants

View Source
const (
	IMDSIP      = "169.254.169.254"
	IMDSPort    = 80
	IMDSAddress = "169.254.169.254:80"
)

IMDS addressing. The guest reaches the metadata service on IMDSAddress; the gateway answers ARP for IMDSIP so the guest's on-link route works.

View Source
const (
	// SocketName is the unix socket QEMU connects to, inside the network dir.
	SocketName = "qemu.sock"
)

QEMU attachment parameters.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	VMID string     `json:"vmID"`
	MAC  string     `json:"mac"`
	IP   netip.Addr `json:"ip"`
	// SocketPath is the network's QEMU unix socket.
	SocketPath string `json:"socketPath"`
}

Attachment is a VM's seat on a network: the MAC the runtime gives the NIC, the IP DHCP will lease to it and the QEMU arguments that connect them.

func (Attachment) QEMUArgs

func (a Attachment) QEMUArgs() []string

QEMUArgs returns the -netdev/-device pair the runtime appends to the QEMU command line. QEMU dials the socket as a client and re-dials it every reconnect-ms while it is gone, so a vm-manager restart does not unplug the NIC.

type Lease

type Lease struct {
	VMID string     `json:"vmID"`
	MAC  string     `json:"mac"`
	IP   netip.Addr `json:"ip"`
}

Lease is one VM's address on a network.

type Manager

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

Manager owns the networks of one vm-manager process.

func NewManager

func NewManager(stateDir string, log *slog.Logger) *Manager

NewManager returns a manager keeping network sockets under stateDir/networks/<name>/. A nil logger means slog.Default().

func (*Manager) Close

func (m *Manager) Close() error

Close shuts every network down without removing state on disk.

func (*Manager) Create

func (m *Manager) Create(ctx context.Context, spec Spec) (*Network, error)

Create brings up a new network. It fails with apierr.ErrInvalid for a bad spec and apierr.ErrConflict when the name is taken.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, name string) error

Delete tears a network down and removes its directory. A network with attached VMs is not deleted (apierr.ErrConflict); detach them first.

func (*Manager) Dir

func (m *Manager) Dir(name string) string

Dir is the directory of the named network.

func (*Manager) Get

func (m *Manager) Get(name string) (*Network, error)

Get returns the named network or apierr.ErrNotFound.

func (*Manager) List

func (m *Manager) List() []*Network

List returns all networks sorted by name.

func (*Manager) Restore

func (m *Manager) Restore(ctx context.Context, states []State) error

Restore rebuilds networks from persisted state, keeping their leases. It stops at the first failure and reports which network it could not restore; networks restored before it stay up.

func (*Manager) States

func (m *Manager) States() []State

States snapshots every network for persistence, sorted by name.

type Network

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

Network is one L2 segment with its gateway stack.

func (*Network) Attach

func (n *Network) Attach(ctx context.Context, vmID string) (*Attachment, error)

Attach gives vmID the lowest free pool address; a VM that already holds a lease gets it back. It fails with apierr.ErrConflict when the pool is exhausted or the network is closed.

func (*Network) Close

func (n *Network) Close() error

Close stops accepting QEMU connections, drops the existing ones and removes the socket. Leases are kept so State stays valid for persistence.

func (*Network) Detach

func (n *Network) Detach(vmID string) error

Detach releases vmID's address. The QEMU connection, if any, is unaffected; stop the VM first.

func (*Network) Dial

func (n *Network) Dial(ctx context.Context, addr string) (net.Conn, error)

Dial opens a TCP connection from the host into the network; addr is "ip:port" of a guest.

func (*Network) Forward

func (n *Network) Forward(ctx context.Context, hostAddr, vmIP string, port int) (*PortForward, error)

Forward listens on hostAddr ("ip:port", port 0 picks one) and proxies every accepted connection to vmIP:port inside the network. The forward lives until Close or until the network closes; ctx only bounds the listen call.

func (*Network) GatewayIP

func (n *Network) GatewayIP() netip.Addr

GatewayIP is the gateway, DHCP and DNS address of the network.

func (*Network) HostIP

func (n *Network) HostIP() netip.Addr

HostIP is the address on which guests reach the host's loopback services.

func (*Network) Leases

func (n *Network) Leases() []Lease

Leases lists the attached VMs ordered by address.

func (*Network) ListenIMDS

func (n *Network) ListenIMDS() (net.Listener, error)

ListenIMDS returns a TCP listener on 169.254.169.254:80 inside the network. Accepted connections report the guest's IP as RemoteAddr, which is how the metadata service identifies the VM. The listener is bound to the IMDS IP itself (not the unspecified address), so it never shadows other services on the gateway; the gateway stack accepts it because it runs with address spoofing enabled and answers ARP for the IMDS IP as a virtual address.

func (*Network) Name

func (n *Network) Name() string

Name is the network name.

func (*Network) Prefix

func (n *Network) Prefix() netip.Prefix

Prefix is the network's CIDR.

func (*Network) SocketPath

func (n *Network) SocketPath() string

SocketPath is the unix socket QEMU connects to.

func (*Network) Spec

func (n *Network) Spec() Spec

Spec is the network's specification.

func (*Network) State

func (n *Network) State() State

State is a snapshot for persistence.

func (*Network) Stats

func (n *Network) Stats() Stats

Stats returns the traffic counters.

type PortForward

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

PortForward exposes one guest TCP port on a host address. It is an io.Closer; Addr reports the bound host address, useful with port 0.

func (*PortForward) Addr

func (f *PortForward) Addr() net.Addr

Addr is the host address the forward listens on.

func (*PortForward) Close

func (f *PortForward) Close() error

Close stops the listener and every proxied connection.

type Spec

type Spec struct {
	// Name identifies the network; a DNS label of at most 63 characters.
	Name string `json:"name"`
	// CIDR is the IPv4 subnet, /16 to /29, outside 169.254.0.0/16.
	CIDR string `json:"cidr"`
	// GatewayIP overrides the gateway address (default: first host address).
	GatewayIP string `json:"gatewayIP,omitempty"`
	// DNSSearchDomain is handed to guests in the DHCP reply.
	DNSSearchDomain string `json:"dnsSearchDomain,omitempty"`
	// EnableIMDS makes 169.254.169.254 reachable from guests and allows
	// ListenIMDS; without it, connections to the IMDS address are refused.
	EnableIMDS bool `json:"enableIMDS"`
	// EnableHostAlias translates the host alias address (HostIP) to the
	// host's loopback, exposing every service bound to 127.0.0.1 on the host
	// to every guest, vm-manager's own API included. Off by default; the
	// address stays reserved either way.
	EnableHostAlias bool `json:"enableHostAlias"`
}

Spec describes a network. It is plain data and serializes as-is.

type State

type State struct {
	Spec Spec `json:"spec"`
	// Leases maps VM id to IP address.
	Leases map[string]string `json:"leases,omitempty"`
}

State is everything needed to rebuild a network after a restart.

type Stats

type Stats struct {
	// BytesSent is the byte count delivered to VMs over their QEMU sockets.
	BytesSent uint64 `json:"bytesSent"`
	// BytesReceived is the byte count received from VMs over their QEMU sockets.
	BytesReceived uint64 `json:"bytesReceived"`
	// Attachments is the number of VMs holding a lease.
	Attachments int `json:"attachments"`
}

Stats are the network's traffic counters.

Jump to

Keyboard shortcuts

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