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
- type Attachment
- type Lease
- type Manager
- func (m *Manager) Close() error
- func (m *Manager) Create(ctx context.Context, spec Spec) (*Network, error)
- func (m *Manager) Delete(ctx context.Context, name string) error
- func (m *Manager) Dir(name string) string
- func (m *Manager) Get(name string) (*Network, error)
- func (m *Manager) List() []*Network
- func (m *Manager) Restore(ctx context.Context, states []State) error
- func (m *Manager) States() []State
- type Network
- func (n *Network) Attach(ctx context.Context, vmID string) (*Attachment, error)
- func (n *Network) Close() error
- func (n *Network) Detach(vmID string) error
- func (n *Network) Dial(ctx context.Context, addr string) (net.Conn, error)
- func (n *Network) Forward(ctx context.Context, hostAddr, vmIP string, port int) (*PortForward, error)
- func (n *Network) GatewayIP() netip.Addr
- func (n *Network) HostIP() netip.Addr
- func (n *Network) Leases() []Lease
- func (n *Network) ListenIMDS() (net.Listener, error)
- func (n *Network) Name() string
- func (n *Network) Prefix() netip.Prefix
- func (n *Network) SocketPath() string
- func (n *Network) Spec() Spec
- func (n *Network) State() State
- func (n *Network) Stats() Stats
- type PortForward
- type Spec
- type State
- type Stats
Constants ¶
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.
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 Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager owns the networks of one vm-manager process.
func NewManager ¶
NewManager returns a manager keeping network sockets under stateDir/networks/<name>/. A nil logger means slog.Default().
func (*Manager) Create ¶
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 ¶
Delete tears a network down and removes its directory. A network with attached VMs is not deleted (apierr.ErrConflict); detach them first.
type Network ¶
type Network struct {
// contains filtered or unexported fields
}
Network is one L2 segment with its gateway stack.
func (*Network) Attach ¶
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 ¶
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 ¶
Detach releases vmID's address. The QEMU connection, if any, is unaffected; stop the VM first.
func (*Network) Dial ¶
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) ListenIMDS ¶
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) SocketPath ¶
SocketPath is the unix socket QEMU connects to.
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.