SwarmKit Package Reference
pkg/swarmkit/— Executor, Controller, VMM Manager, and Task Translator.
Overview
Section titled “Overview”The pkg/swarmkit package implements the SwarmKit executor interface, transforming SwarmKit container tasks into Firecracker microVMs. It is the core integration point between SwarmKit’s orchestration and Firecracker’s VM execution.
Package Structure:
pkg/swarmkit/├── executor.go # Executor implementation (SwarmKit interface)├── vmm.go # VMM Manager (Firecracker process management)├── translator.go # Task → Firecracker config translation├── interfaces.go # Interface definitions├── mocks.go # Test mocks└── configs/ # SwarmKit configuration helpersExecutor
Section titled “Executor”File: executor.go
The Executor struct implements SwarmKit’s swarmkit_exec.Executor interface, providing the bridge between SwarmKit task scheduling and Firecracker VM execution.
Type Definition
Section titled “Type Definition”type Executor struct { config *Config imagePrep types.ImagePreparer networkMgr types.NetworkManager volumeMgr *storage.VolumeManager secretMgr *storage.SecretManager vmmMgr VMMManagerInterface controllers map[string]*Controller executorMu sync.RWMutex cleanupCancel context.CancelFunc cleanupDone chan struct{} networkKeys []*api.EncryptionKey cleanupMu sync.Mutex}Configuration
Section titled “Configuration”type Config struct { FirecrackerPath string `yaml:"firecracker_path"` KernelPath string `yaml:"kernel_path"` RootfsDir string `yaml:"rootfs_dir"` SocketDir string `yaml:"socket_dir"` DefaultVCPUs int `yaml:"default_vcpus"` DefaultMemoryMB int `yaml:"default_memory_mb"` BridgeName string `yaml:"bridge_name"` Subnet string `yaml:"subnet"` BridgeIP string `yaml:"bridge_ip"` IPMode string `yaml:"ip_mode"` NATEnabled bool `yaml:"nat_enabled"` VXLANEnabled bool `yaml:"vxlan_enabled"` VXLANPeers []string `yaml:"vxlan_peers"` Debug bool `yaml:"debug"` ReservedCPUs int `yaml:"reserved_cpus"` ReservedMemoryMB int `yaml:"reserved_memory_mb"` MaxImageAgeDays int `yaml:"max_image_age_days"` StateDir string `yaml:"state_dir"`
// Jailer configuration EnableJailer bool `yaml:"enable_jailer"` JailerPath string `yaml:"jailer_path"` JailerUID int `yaml:"jailer_uid"` JailerGID int `yaml:"jailer_gid"` JailerChrootDir string `yaml:"jailer_chroot_dir"` ParentCgroup string `yaml:"parent_cgroup"` CgroupVersion string `yaml:"cgroup_version"` EnableCgroups bool `yaml:"enable_cgroups"`
// Network identity Hostname string `yaml:"hostname"` JoinAddr string `yaml:"join_addr"` AdvertiseAddr string `yaml:"advertise_addr"`
// Consul service discovery ConsulEnabled bool `yaml:"consul_enabled"` ConsulAddress string `yaml:"consul_address"`}Constructor
Section titled “Constructor”func NewExecutor(config *Config) (*Executor, error)Parameters:
config— Executor configuration (required)
Defaults Applied:
| Field | Default Value |
|---|---|
FirecrackerPath |
"firecracker" |
KernelPath |
"/usr/share/firecracker/vmlinux" |
RootfsDir |
"/var/lib/firecracker/rootfs" |
SocketDir |
"/var/run/firecracker" |
DefaultVCPUs |
1 |
DefaultMemoryMB |
512 |
BridgeName |
"swarm-br0" |
Subnet |
"192.168.127.0/24" |
BridgeIP |
"192.168.127.1/24" |
IPMode |
"static" |
Example:
config := &swarmkit.Config{ KernelPath: "/usr/share/firecracker/vmlinux", RootfsDir: "/var/lib/firecracker/rootfs", DefaultVCPUs: 2, DefaultMemoryMB: 1024, BridgeName: "swarm-br0", ConsulEnabled: true, ConsulAddress: "127.0.0.1:8500",}
exec, err := swarmkit.NewExecutor(config)if err != nil { log.Fatal(err)}SwarmKit Interface Methods
Section titled “SwarmKit Interface Methods”The Executor implements these SwarmKit executor interface methods:
Configure
Section titled “Configure”func (e *Executor) Configure(ctx context.Context, driver swarmkit_exec.Driver) errorPurpose: Initialize executor with SwarmKit driver for task management.
Parameters:
ctx— Context for cancellationdriver— SwarmKit driver for task queue operations
Side Effects:
- Creates network infrastructure (bridge, VXLAN)
- Starts Consul peer discovery watcher (if enabled)
- Initializes cleanup goroutine
Create
Section titled “Create”func (e *Executor) Create(ctx context.Context, task *api.Task) (swarmkit_exec.Controller, error)Purpose: Create a controller for a new task.
Parameters:
ctx— Context for cancellationtask— SwarmKit task specification
Returns:
Controller— Task controller for lifecycle managementerror— Creation error (e.g., unsupported runtime)
Implementation:
func (e *Executor) Create(ctx context.Context, task *api.Task) (swarmkit_exec.Controller, error) { // Check task runtime type container := task.Spec.GetContainer() if container == nil { return nil, fmt.Errorf("unsupported runtime type") }
// Create controller ctrl := &Controller{ task: task, executor: e, vmm: e.vmmMgr, preparer: e.imagePrep, networkMgr: e.networkMgr, }
// Store controller e.executorMu.Lock() e.controllers[task.ID] = ctrl e.executorMu.Unlock()
return ctrl, nil}func (e *Executor) Close() errorPurpose: Shutdown executor and cleanup all resources.
Side Effects:
- Stops cleanup goroutine
- Removes all controllers
- Cleanup network infrastructure
Controller
Section titled “Controller”File: executor.go
The Controller manages the lifecycle of a single task/VM.
Type Definition
Section titled “Type Definition”type Controller struct { task *api.Task executor *Executor vmm VMMManagerInterface preparer types.ImagePreparer networkMgr types.NetworkManager
mu sync.RWMutex closed bool}Methods
Section titled “Methods”Prepare
Section titled “Prepare”func (c *Controller) Prepare(ctx context.Context) errorPurpose: Prepare task for execution (image prep, network setup).
Steps:
- Validate task runtime (must be container)
- Prepare rootfs image via
ImagePreparer.Prepare() - Setup TAP device and network via
NetworkManager.CreateTapDevice() - Allocate IP address
- Prepare volumes via
VolumeManager - Inject secrets/configs
func (c *Controller) Start(ctx context.Context) errorPurpose: Start the Firecracker VM.
Steps:
- Translate task to Firecracker config
- Start Firecracker process via
VMMManager.Start() - Configure VM (kernel, rootfs, network, machine config)
- Send InstanceStart action
- Wait for VM to reach running state
func (c *Controller) Wait(ctx context.Context) errorPurpose: Wait for task completion.
Returns:
nil— Task completed successfullyerror— Task failed or context canceled
func (c *Controller) Stop(ctx context.Context) errorPurpose: Gracefully stop the VM.
Steps:
- Send graceful shutdown signal
- Wait for init grace period
- Force kill if still running
Remove
Section titled “Remove”func (c *Controller) Remove(ctx context.Context) errorPurpose: Remove task and cleanup resources.
Cleanup Steps:
- Stop VM (if running)
- Remove TAP device
- Release IP allocation
- Cleanup jailer directory (if enabled)
- Remove controller from executor
func (c *Controller) Close() errorPurpose: Close controller without cleanup (for failed tasks).
VMMManager
Section titled “VMMManager”File: vmm.go
The VMMManager manages Firecracker VM processes and API communication.
Type Definition
Section titled “Type Definition”type VMMManager struct { config *VMMConfig vms map[string]*VMInstance mu sync.RWMutex socketDir string}
type VMInstance struct { ID string PID int Config interface{} state VMState CreatedAt time.Time SocketPath string InitSystem string GracePeriodSec int mu sync.RWMutex}VM States
Section titled “VM States”type VMState string
const ( VMStateNew VMState = "new" VMStateStarting VMState = "starting" VMStateRunning VMState = "running" VMStateStopping VMState = "stopping" VMStateStopped VMState = "stopped" VMStateCrashed VMState = "crashed")Constructor
Section titled “Constructor”func NewVMMManager(config interface{}) VMMManagerParameters:
config— VMMConfig or any config interface
Methods
Section titled “Methods”func (vm *VMMManager) Start(ctx context.Context, task *types.Task, config interface{}) errorPurpose: Start a Firecracker VM for the task.
Steps:
- Find Firecracker binary
- Start process with API socket
- Wait for API server ready (10s timeout)
- Configure VM via HTTP API
- Send InstanceStart action
- Track VM instance
func (vm *VMMManager) Stop(ctx context.Context, taskID string) errorPurpose: Stop a running VM.
func (vm *VMMManager) Pause(ctx context.Context, taskID string) errorPurpose: Pause VM (for snapshot).
Resume
Section titled “Resume”func (vm *VMMManager) Resume(ctx context.Context, taskID string) errorPurpose: Resume paused VM.
GetInfo
Section titled “GetInfo”func (vm *VMMManager) GetInfo(taskID string) (*VMInstance, error)Purpose: Get VM instance info.
func (vm *VMMManager) List() []stringPurpose: List all managed VM IDs.
Cleanup
Section titled “Cleanup”func (vm *VMMManager) Cleanup(ctx context.Context, taskID string) errorPurpose: Cleanup VM resources (socket, state).
Firecracker API Types
Section titled “Firecracker API Types”type BootSource struct { KernelImagePath string `json:"kernel_image_path"` BootArgs string `json:"boot_args,omitempty"`}
type Drive struct { DriveID string `json:"drive_id"` IsRootDevice bool `json:"is_root_device"` IsReadOnly bool `json:"is_read_only"` PathOnHost string `json:"path_on_host"`}
type MachineConfig struct { VCPUs int `json:"vcpu_count"` MemSizeMib int `json:"mem_size_mib"` HtEnabled bool `json:"ht_enabled"`}
type ActionsType struct { ActionType string `json:"action_type"`}Translator
Section titled “Translator”File: translator.go
The Translator converts SwarmKit task specifications into Firecracker VM configurations.
Type Definition
Section titled “Type Definition”type TaskTranslator struct { config *Config}
type Config struct { KernelPath string InitrdPath string DefaultVCPUs int DefaultMemMB int InitSystem string NetworkConfig types.NetworkConfig}Constructor
Section titled “Constructor”func NewTaskTranslator(config *Config) *TaskTranslatorMethods
Section titled “Methods”Translate
Section titled “Translate”func (t *TaskTranslator) Translate(task *api.Task) (*types.VMConfig, error)Purpose: Convert SwarmKit task to Firecracker VM config.
Translation Steps:
- Extract container spec from task
- Determine vCPUs and memory from task resources or defaults
- Build kernel boot args
- Configure drives (rootfs path)
- Setup network config
- Apply init system settings
Example Output:
vmConfig := &types.VMConfig{ KernelPath: "/usr/share/firecracker/vmlinux", BootArgs: "console=ttyS0 reboot=k panic=1 pci=off ip=dhcp", RootfsPath: "/var/lib/firecracker/rootfs/nginx-alpine.ext4", VCPUs: 2, MemoryMB: 1024, Network: &types.NetworkConfig{ TapDevice: "tap-abc123", IPAddress: "192.168.127.42", Gateway: "192.168.127.1", }, InitSystem: "tini", GracePeriodSec: 10,}Interfaces
Section titled “Interfaces”File: interfaces.go
VMMManagerInterface
Section titled “VMMManagerInterface”type VMMManagerInterface interface { Start(ctx context.Context, task *types.Task, config interface{}) error Stop(ctx context.Context, taskID string) error Pause(ctx context.Context, taskID string) error Resume(ctx context.Context, taskID string) error GetInfo(taskID string) (*VMInstance, error) List() []string Cleanup(ctx context.Context, taskID string) error}Consul Integration
Section titled “Consul Integration”When ConsulEnabled is true, the executor:
- Registers service in Consul catalog
- Starts peer watcher via
WatchPeers() - Updates VXLAN FDB on peer changes
// Consul client creationconsulClient, err := discovery.NewConsulClient(discovery.ConsulConfig{ Address: config.ConsulAddress, ServiceID: config.Hostname, LocalIP: localIP, LocalHostname: config.Hostname, VXLANPort: 4789,})
// Register and watchconsulClient.RegisterService(vxlanID, config.BridgeIP)networkMgr.SetNodeDiscovery(consulClient)
go consulClient.WatchPeers(ctx, func(peers []string) { networkMgr.UpdateVXLANPeers(peers)})Error Handling
Section titled “Error Handling”Common Errors
Section titled “Common Errors”| Error | Cause | Resolution |
|---|---|---|
"config cannot be nil" |
Nil config passed | Provide valid Config struct |
"unsupported runtime type" |
Task not container | Use container runtime tasks |
"VM already exists for task" |
Duplicate task ID | Wait for cleanup or force remove |
"firecracker binary not found" |
Firecracker not installed | Install Firecracker v1.15+ |
"firecracker API server not ready" |
Socket timeout | Check Firecracker process |
Testing
Section titled “Testing”The package includes comprehensive test coverage with mocks:
// Create mock executor for testingmockVMM := &MockVMMManager{}mockNetwork := &MockNetworkManager{}mockPreparer := &MockImagePreparer{}
exec := &Executor{ vmmMgr: mockVMM, networkMgr: mockNetwork, imagePrep: mockPreparer, controllers: make(map[string]*Controller),}Related Documentation
Section titled “Related Documentation”| Topic | Document |
|---|---|
| Network internals | Network Reference |
| VM lifecycle | Lifecycle Reference |
| Image preparation | Image Reference |
| Architecture overview | Architecture Overview |
See Also: SwarmKit Integration Guide | SwarmKit User Guide