Network Package Reference
pkg/network/— NetworkManager, CNI, VXLAN, IPAM, and Discovery.
Overview
Section titled “Overview”The pkg/network package manages networking for Firecracker VMs, including bridge creation, TAP device setup, VXLAN overlay networks, and IP allocation.
Package Structure:
pkg/network/├── manager.go # NetworkManager (orchestration)├── vxlan.go # VXLAN overlay (cross-node)├── cni.go # CNI plugin integration├── cni_client.go # CNI client wrapper├── netlink.go # Netlink operations└── tap_executor.go # TAP device creationTest utilities live in
test/testhelpers/(they were moved out of thepkg/networkpackage).
NetworkManager
Section titled “NetworkManager”File: manager.go
The NetworkManager orchestrates all network operations for VMs.
Type Definition
Section titled “Type Definition”type NetworkManager struct { config types.NetworkConfig bridges map[string]bool mu sync.RWMutex tapDevices map[string]*TapDevice ipAllocator *IPAllocator natSetup bool vxlanMgr *VXLANManager peerDiscovery bool peerCancel context.CancelFunc nodeDiscovery types.NodeDiscovery cniClient *CNIClient pendingPeers []string}Configuration
Section titled “Configuration”type NetworkConfig struct { BridgeName string // e.g., "swarm-br0" Subnet string // e.g., "192.168.127.0/24" BridgeIP string // e.g., "192.168.127.1/24" IPMode string // "static" or "dhcp" NATEnabled bool // Enable masquerading VXLANEnabled bool // Enable cross-node overlay VXLANPeers []string // Initial peer IPs EnableRateLimit bool // Packet rate limiting MaxPacketsPerSec int // Rate limit threshold}Constructor
Section titled “Constructor”func NewNetworkManager(config types.NetworkConfig) *NetworkManagerExample:
config := types.NetworkConfig{ BridgeName: "swarm-br0", Subnet: "192.168.127.0/24", BridgeIP: "192.168.127.1/24", IPMode: "static", NATEnabled: true, VXLANEnabled: true,}
nm := network.NewNetworkManager(config)Methods
Section titled “Methods”func (nm *NetworkManager) Init(ctx context.Context) errorPurpose: Initialize network infrastructure.
Steps:
- Create Linux bridge (
swarm-br0) - Assign bridge IP address
- Enable IP forwarding
- Setup NAT/masquerading (if enabled)
- Create VXLAN device (if enabled)
Example:
if err := nm.Init(ctx); err != nil { log.Fatal(err)}CreateTapDevice
Section titled “CreateTapDevice”func (nm *NetworkManager) CreateTapDevice(ctx context.Context, taskID string) (*TapDevice, error)Purpose: Create TAP device for VM and connect to bridge.
Parameters:
ctx— Context for cancellationtaskID— Unique task identifier
Returns:
TapDevice— TAP device info with allocated IP
Example:
tap, err := nm.CreateTapDevice(ctx, "task-abc123")if err != nil { return err}
fmt.Printf("TAP: %s, IP: %s\n", tap.Name, tap.IP)// Output: TAP: tap-abc123, IP: 192.168.127.42RemoveTapDevice
Section titled “RemoveTapDevice”func (nm *NetworkManager) RemoveTapDevice(ctx context.Context, taskID string) errorPurpose: Remove TAP device and release IP.
AllocateIP
Section titled “AllocateIP”func (nm *NetworkManager) AllocateIP(taskID string) (string, error)Purpose: Allocate IP address for task.
Algorithm:
- SHA-256 hash of task ID
- Convert hash to IP offset in subnet
- Linear probing for collision resolution
- Skip gateway, network, and broadcast addresses
ReleaseIP
Section titled “ReleaseIP”func (nm *NetworkManager) ReleaseIP(ip string) errorPurpose: Release IP back to pool.
UpdateVXLANPeers
Section titled “UpdateVXLANPeers”func (nm *NetworkManager) UpdateVXLANPeers(peers []string) errorPurpose: Update VXLAN forwarding database with new peers.
Implementation:
# For each peer IP:bridge fdb append dev swarm-br0-vxlan dst <peer-ip> vni 100 port 4789SetNodeDiscovery
Section titled “SetNodeDiscovery”func (nm *NetworkManager) SetNodeDiscovery(discovery types.NodeDiscovery)Purpose: Set discovery provider (Consul) for dynamic peer updates.
IPAllocator
Section titled “IPAllocator”File: manager.go
Type Definition
Section titled “Type Definition”type IPAllocator struct { subnet *net.IPNet gateway net.IP allocated map[string]string // IP → VM ID mapping mu sync.Mutex}Constructor
Section titled “Constructor”func NewIPAllocator(subnetStr, gatewayStr string) (*IPAllocator, error)Methods
Section titled “Methods”Allocate
Section titled “Allocate”func (a *IPAllocator) Allocate(vmID string) (string, error)Purpose: Allocate deterministic IP for VM.
Algorithm:
func (a *IPAllocator) hashToIP(vmID string) net.IP { h := sha256.New() h.Write([]byte(vmID)) hash := h.Sum(nil)
// IPv4: use first 4 bytes of hash n := binary.BigEndian.Uint32(hash[:4]) % (size - 2) ipInt := subnetBase + n + 1
return net.IP(ipInt)}Collision Resolution:
// Linear probing - try next IP if collisionfor i := 0; i < 256; i++ { if !isGateway && !isAllocated { allocated[ipStr] = vmID return ipStr, nil } ip = incIP(ip)}VXLANManager
Section titled “VXLANManager”File: vxlan.go
The VXLANManager handles VXLAN overlay network setup and peer management.
Type Definition
Section titled “Type Definition”type VXLANManager struct { vxlanDevice string // e.g., "swarm-br0-vxlan" vni int // VXLAN Network Identifier (100) bridge string // Bridge to attach (swarm-br0) port int // UDP port (4789) localIP string // Local underlay IP peers []string // Remote peer IPs mu sync.RWMutex}Constructor
Section titled “Constructor”func NewVXLANManager(config VXLANConfig) (*VXLANManager, error)Methods
Section titled “Methods”Create
Section titled “Create”func (vx *VXLANManager) Create(ctx context.Context) errorPurpose: Create VXLAN device and attach to bridge.
Implementation:
# Create VXLAN deviceip link add swarm-br0-vxlan type vxlan id 100 dstport 4789 local <local-ip>
# Attach to bridgeip link set swarm-br0-vxlan master swarm-br0
# Bring upip link set swarm-br0-vxlan upAddPeer
Section titled “AddPeer”func (vx *VXLANManager) AddPeer(peerIP string) errorPurpose: Add remote peer to forwarding database.
Implementation:
bridge fdb append dev swarm-br0-vxlan dst <peer-ip> vni 100 port 4789Note: Uses fdb append to allow multiple peers per VNI.
RemovePeer
Section titled “RemovePeer”func (vx *VXLANManager) RemovePeer(peerIP string) errorPurpose: Remove peer from forwarding database.
UpdatePeers
Section titled “UpdatePeers”func (vx *VXLANManager) UpdatePeers(peers []string) errorPurpose: Batch update all peers.
CNIClient
Section titled “CNIClient”File: cni.go, cni_client.go
CNI integration for SwarmKit network attachments.
Type Definition
Section titled “Type Definition”type CNIClient struct { pluginDir string configDir string cacheDir string}
type CNIConfig struct { Name string Type string Bridge string IPAM IPAMConfig IsDefaultGateway bool}Constructor
Section titled “Constructor”func NewCNIClient(pluginDir, configDir string) *CNIClientMethods
Section titled “Methods”func (c *CNIClient) Add(ctx context.Context, netName, ifaceName, containerID string, config *CNIConfig) (*CNIResult, error)Purpose: Add network interface for container.
Returns:
type CNIResult struct { Interfaces []CNIIface IPs []CNIIP Routes []CNIRoute}func (c *CNIClient) Del(ctx context.Context, netName, ifaceName, containerID string) errorPurpose: Remove network interface.
Discovery
Section titled “Discovery”Consul-based peer discovery for VXLAN lives in the separate pkg/discovery
package (consul.go), not in pkg/network. NetworkManager.SetNodeDiscovery
accepts a types.NodeDiscovery provider, which the SwarmKit integration wires
to the Consul client so that peer updates are programmed into the VXLAN
forwarding database.
Netlink Operations
Section titled “Netlink Operations”File: netlink.go
Low-level network operations using netlink.
Functions
Section titled “Functions”CreateBridge
Section titled “CreateBridge”func CreateBridge(name string) errorImplementation:
ip link add <name> type bridgeip link set <name> upSetBridgeIP
Section titled “SetBridgeIP”func SetBridgeIP(name, ipCIDR string) errorImplementation:
ip addr add <ipCIDR> dev <name>CreateTap
Section titled “CreateTap”func CreateTap(name string) errorImplementation:
ip tuntap add dev <name> mode tapip link set <name> upConnectTapToBridge
Section titled “ConnectTapToBridge”func ConnectTapToBridge(tapName, bridgeName string) errorImplementation:
ip link set <tapName> master <bridgeName>TAP Device
Section titled “TAP Device”File: tap_executor.go
Type Definition
Section titled “Type Definition”type TapDevice struct { Name string // e.g., "tap-abc123" Bridge string // e.g., "swarm-br0" IP string // e.g., "192.168.127.42" Netmask string // e.g., "255.255.255.0" Gateway string // e.g., "192.168.127.1" Subnet string // e.g., "192.168.127.0/24"}NAT/Masquerading
Section titled “NAT/Masquerading”Enabled by default for VM internet access.
Implementation:
# Enable IP forwardingsysctl -w net.ipv4.ip_forward=1
# Setup masqueradingiptables -t nat -A POSTROUTING -s 192.168.127.0/24 ! -o swarm-br0 -j MASQUERADEConfiguration:
network: nat_enabled: trueRate Limiting
Section titled “Rate Limiting”Optional packet rate limiting on TAP devices.
Configuration:
network: enable_rate_limit: true max_packets_per_sec: 10000Implementation:
# Using tc (traffic control)tc qdisc add dev <tap> root handle 1: htbtc class add dev <tap> parent 1: classid 1:1 htb rate <rate>tc filter add dev <tap> parent 1: protocol ip prio 1 u32 match u32 0 0 flowid 1:1Testing
Section titled “Testing”Mock NetworkManager
Section titled “Mock NetworkManager”type MockNetworkManager struct { TapDevices map[string]*TapDevice IPs map[string]string}
func (m *MockNetworkManager) CreateTapDevice(ctx context.Context, taskID string) (*TapDevice, error) { tap := &TapDevice{ Name: "tap-" + taskID, IP: "192.168.127.42", Gateway: "192.168.127.1", } m.TapDevices[taskID] = tap return tap, nil}Error Handling
Section titled “Error Handling”Common Errors
Section titled “Common Errors”| Error | Cause | Resolution |
|---|---|---|
"invalid subnet" |
Bad CIDR notation | Use valid format (e.g., 192.168.127.0/24) |
"bridge creation failed" |
Permission denied | Run with root/capabilities |
"failed to allocate IP" |
Subnet exhausted | Increase subnet size or cleanup VMs |
"vxlan device creation failed" |
VXLAN module missing | Load vxlan kernel module |
Related Documentation
Section titled “Related Documentation”| Topic | Document |
|---|---|
| SwarmKit executor | SwarmKit Reference |
| User networking guide | Networking Guide |
| Architecture | Architecture Overview |