diff --git a/AGENTS.md b/AGENTS.md index 9c7f319e9..a8b9b0c22 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,8 +16,8 @@ The project is built via `make`, not directly with `swift build`. Two Swift pack - `make linux-integration` — runs the cross-platform integration suite against a real cloud-hypervisor VM inside the dev container (nested virt via apple/container's `--virtualization`). Requires a KVM-capable kernel at `kernel/vmlinux-arm64` (or `kernel/vmlinuz-x86_64` on x86_64 hosts) — build via `make -C kernel`; the kata-fetched kernel doesn't include KVM. Also requires `make fetch-cloud-hypervisor` and `make linux-build` to have been run first. Linux runs only the cross-platform subset (`process true`/`false`/`echo hi`); the macOS suite is unchanged. - `make fetch-cloud-hypervisor` — downloads the static `cloud-hypervisor` v52.0 (aarch64) binary into `bin/cloud-hypervisor` for the Linux integration tests. - `make fetch-runc` — downloads the pinned static `runc` v1.5.1 release binary for the host arch into `bin/runc-`, verifying its sha256 against the release's PGP-signed `runc.sha256sum` manifest. **Opt-in**: when that file is present, `make init` stages it into the initfs at `/sbin/runc`, and a container can select the runc-backed launch path with `ociRuntimePath = "/sbin/runc"` (`cctl run --oci-runtime-path /sbin/runc`). Without it the initfs is byte-identical to before and `vmexec` is the only runtime, so `make all` performs no new network access. The `runc *` integration tests skip themselves when it hasn't been fetched. Unlike `fetch-cloud-hypervisor`, this downloads to a `.tmp` path and only moves it into place after the checksum passes — the staging decision downstream is presence-only, so a truncated binary from a failed download would otherwise be baked into the guest image silently. -- `make build-cloud-hypervisor` / `make build-virtiofsd` — build patched `cloud-hypervisor` / `virtiofsd` from sources you have cloned into `.local/cloud-hypervisor` and `.local/virtiofsd` respectively. There is no fetch target — clone the upstream repos at the revision you want pinned. `build-virtiofsd` applies `scripts/patches/virtiofsd-skip-cap-drop-with-sandbox-none.patch` and is idempotent. Both run inside the same Linux dev container as `linux-integration` so the resulting binaries are aarch64-linux-gnu. -- `make dist-x86_64` — assembles `bin/containerization-x86_64-.tar.gz` (cctl + cloud-hypervisor + virtiofsd + initfs.ext4 + kernel) for x86_64 Linux deployment, cross-compiled inside the aarch64 dev container via the Static Linux SDK (Swift) and `cargo zigbuild` (Rust). Prereqs: `.local/cloud-hypervisor` and `.local/virtiofsd` source checkouts (clone deliberately — no fetch target), and an x86_64 kernel built via `make -C kernel TARGET_ARCH=x86_64`. Per-stage rebuild env vars: `REBUILD_VMINITD=1`, `REBUILD_INITFS=1`, `REBUILD_CH=1`, `REBUILD_VIRTIOFSD=1`; cctl x86 always rebuilds. **Full pipeline, toolchain rationale, and troubleshooting in `docs/x86_64-build.md`.** The orchestrator is `scripts/build-dist-x86_64.sh`. +- `make build-cloud-hypervisor` / `make build-virtiofsd` — build patched `cloud-hypervisor` / `virtiofsd` from sources in `.local/cloud-hypervisor` and `.local/virtiofsd`. Each target depends on `make fetch-cloud-hypervisor-source` / `make fetch-virtiofsd`, which do a full-history clone at the pinned tag (`CLOUD_HYPERVISOR_VERSION`, `VIRTIOFSD_VERSION` in the Makefile) when the directory is absent, and leave an existing checkout untouched — check out a different revision yourself to build it. `build-virtiofsd` applies `scripts/patches/virtiofsd-skip-cap-drop-with-sandbox-none.patch` and is idempotent. Both run inside the same Linux dev container as `linux-integration` so the resulting binaries are aarch64-linux-gnu. +- `make dist-x86_64` — assembles `bin/containerization-x86_64-.tar.gz` (cctl + cloud-hypervisor + virtiofsd + initfs.ext4 + kernel) for x86_64 Linux deployment, cross-compiled inside the aarch64 dev container via the Static Linux SDK (Swift) and `cargo zigbuild` (Rust). Prereqs: `.local/cloud-hypervisor` and `.local/virtiofsd` source checkouts (fetched automatically, as above), and an x86_64 kernel built via `make -C kernel TARGET_ARCH=x86_64`. Per-stage rebuild env vars: `REBUILD_VMINITD=1`, `REBUILD_INITFS=1`, `REBUILD_CH=1`, `REBUILD_VIRTIOFSD=1`; cctl x86 always rebuilds. **Full pipeline, toolchain rationale, and troubleshooting in `docs/x86_64-build.md`.** The orchestrator is `scripts/build-dist-x86_64.sh`. - `make fmt` — applies `.swift-format` and refreshes license headers via hawkeye. - `make check` — formatting + license-header lint (this is what the pre-commit hook runs). Uses `.swift-format-nolint` for stricter linting. - `make pre-commit` — installs `scripts/pre-commit.fmt` as a git pre-commit hook. diff --git a/Makefile b/Makefile index 44d1c803e..1041e7ec4 100644 --- a/Makefile +++ b/Makefile @@ -76,11 +76,19 @@ LIBARCHIVE_UPSTREAM_VERSION := v3.7.7 LIBARCHIVE_LOCAL_DIR := workdir/libarchive KATA_BINARY_PACKAGE := https://github.com/kata-containers/kata-containers/releases/download/3.17.0/kata-static-3.17.0-arm64.tar.xz -CLOUD_HYPERVISOR_URL := https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/v52.0/cloud-hypervisor-static-aarch64 +CLOUD_HYPERVISOR_VERSION := v52.0 +CLOUD_HYPERVISOR_REPO := https://github.com/cloud-hypervisor/cloud-hypervisor.git +CLOUD_HYPERVISOR_URL := https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/$(CLOUD_HYPERVISOR_VERSION)/cloud-hypervisor-static-aarch64 # SHA256 of the v52.0 aarch64 static binary (verified locally from the -# upstream release artifact). Bump alongside CLOUD_HYPERVISOR_URL. +# upstream release artifact). Bump alongside CLOUD_HYPERVISOR_VERSION. CLOUD_HYPERVISOR_SHA256 := bf004ddc1a148f47caa87ac49a783b8dbd6bf9bc27abe522ed197df7b982d3b1 +# virtiofsd source pin. v1.13.3 is the revision +# scripts/patches/virtiofsd-skip-cap-drop-with-sandbox-none.patch targets; +# `make build-virtiofsd` fails loudly if the patch stops applying. +VIRTIOFSD_VERSION := v1.13.3 +VIRTIOFSD_REPO := https://gitlab.com/virtio-fs/virtiofsd.git + RUNC_VERSION := v1.5.1 RUNC_ASSET_ARCH := $(if $(filter $(KERNEL_ARCH),arm64),arm64,amd64) RUNC_URL := https://github.com/opencontainers/runc/releases/download/$(RUNC_VERSION)/runc.$(RUNC_ASSET_ARCH) @@ -187,6 +195,39 @@ endif linux-test: $(call linux_run,swift test $(SWIFT_CONFIGURATION) --scratch-path $(LINUX_SCRATCH_ROOT)/build-containerization $(linux_test_filter)) +.PHONY: fetch-cloud-hypervisor-source +# Clone cloud-hypervisor at $(CLOUD_HYPERVISOR_VERSION) into +# .local/cloud-hypervisor. Full history on purpose — `git log -p` and +# `git blame` on the upstream source are the primary tools for working out +# why the REST surface behaves the way it does, and they need the history +# locally to work offline. No-op when a checkout is already there, so an +# existing clone keeps whatever revision you moved it to. +fetch-cloud-hypervisor-source: +ifeq (,$(wildcard .local/cloud-hypervisor/Cargo.toml)) + @mkdir -p .local + @if [ -e .local/cloud-hypervisor ]; then \ + echo "ERROR: .local/cloud-hypervisor exists but has no Cargo.toml (interrupted clone?)." >&2; \ + echo " inspect it, then 'rm -rf .local/cloud-hypervisor' and re-run" >&2; \ + exit 1; \ + fi + git clone --branch $(CLOUD_HYPERVISOR_VERSION) $(CLOUD_HYPERVISOR_REPO) .local/cloud-hypervisor +endif + +.PHONY: fetch-virtiofsd +# Clone virtiofsd at $(VIRTIOFSD_VERSION) into .local/virtiofsd. Same +# full-history rationale as fetch-cloud-hypervisor-source, and likewise a +# no-op when the checkout already exists. +fetch-virtiofsd: +ifeq (,$(wildcard .local/virtiofsd/Cargo.toml)) + @mkdir -p .local + @if [ -e .local/virtiofsd ]; then \ + echo "ERROR: .local/virtiofsd exists but has no Cargo.toml (interrupted clone?)." >&2; \ + echo " inspect it, then 'rm -rf .local/virtiofsd' and re-run" >&2; \ + exit 1; \ + fi + git clone --branch $(VIRTIOFSD_VERSION) $(VIRTIOFSD_REPO) .local/virtiofsd +endif + .PHONY: build-cloud-hypervisor # Build cloud-hypervisor from the patched source at .local/cloud-hypervisor and # install it to bin/cloud-hypervisor. Runs inside the Linux dev container so the @@ -195,18 +236,10 @@ linux-test: # time. Forces HOME=/root since the container inherits the host HOME otherwise, # which breaks rustup's $HOME/.cargo path. # -# Prerequisite: clone cloud-hypervisor into .local/cloud-hypervisor (any -# revision compatible with the v52.0 REST surface this repo targets). There -# is no fetch target — pin the revision deliberately. Example: -# git clone -b v52.0 https://github.com/cloud-hypervisor/cloud-hypervisor \ -# .local/cloud-hypervisor -build-cloud-hypervisor: -ifeq (,$(wildcard .local/cloud-hypervisor/Cargo.toml)) - @echo "missing .local/cloud-hypervisor source checkout." >&2 - @echo "clone the cloud-hypervisor repo into .local/cloud-hypervisor before running this target, e.g.:" >&2 - @echo " git clone -b v52.0 https://github.com/cloud-hypervisor/cloud-hypervisor .local/cloud-hypervisor" >&2 - @exit 1 -endif +# Clones the source via fetch-cloud-hypervisor-source when .local/cloud-hypervisor +# is absent. To build a different revision, check one out there yourself — the +# fetch leaves an existing clone alone. +build-cloud-hypervisor: fetch-cloud-hypervisor-source $(call linux_run,export HOME=/root && if ! command -v curl >/dev/null 2>&1; then apt-get update && apt-get install -y --no-install-recommends curl ca-certificates build-essential pkg-config libssl-dev; fi && if [ ! -x /root/.cargo/bin/cargo ]; then curl --proto =https --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable --profile minimal; fi && . /root/.cargo/env && cd .local/cloud-hypervisor && cargo build --release --bin cloud-hypervisor && cp target/release/cloud-hypervisor /workspace/bin/cloud-hypervisor && chmod +x /workspace/bin/cloud-hypervisor) .PHONY: build-virtiofsd @@ -215,10 +248,9 @@ endif # binary is aarch64-linux-gnu and matches the cloud-hypervisor binary # built by `make build-cloud-hypervisor`. # -# Prerequisite: clone virtiofsd into .local/virtiofsd (any revision the -# scripts/patches/virtiofsd-skip-cap-drop-with-sandbox-none.patch applies -# cleanly to). There is no fetch target — pin the revision deliberately: -# git clone https://gitlab.com/virtio-fs/virtiofsd .local/virtiofsd +# Clones the source via fetch-virtiofsd when .local/virtiofsd is absent, at +# the revision the patch below targets. To build a different revision, check +# one out there yourself — the fetch leaves an existing clone alone. # # virtiofsd has two hard build deps that aren't in the base dev image: # * libcap-ng-dev — capng crate is unconditional in [dependencies]. @@ -237,13 +269,7 @@ endif # (not `command -v curl`) so this target works correctly even after # `build-cloud-hypervisor` has already installed curl in the same dev # container. -build-virtiofsd: -ifeq (,$(wildcard .local/virtiofsd/Cargo.toml)) - @echo "missing .local/virtiofsd source checkout." >&2 - @echo "clone the virtiofsd repo into .local/virtiofsd before running this target, e.g.:" >&2 - @echo " git clone https://gitlab.com/virtio-fs/virtiofsd .local/virtiofsd" >&2 - @exit 1 -endif +build-virtiofsd: fetch-virtiofsd $(call linux_run,export HOME=/root && \ if ! pkg-config --exists libcap-ng libseccomp 2>/dev/null; then \ apt-get update && apt-get install -y --no-install-recommends \ @@ -305,13 +331,13 @@ endif # layers are cached, so the no-change path is a few seconds of overhead. # # Prereqs: -# * .local/cloud-hypervisor and .local/virtiofsd source checkouts -# (see build-cloud-hypervisor / build-virtiofsd for clone URLs). +# * .local/cloud-hypervisor and .local/virtiofsd source checkouts, cloned +# by fetch-cloud-hypervisor-source / fetch-virtiofsd if not already there. # * kernel/vmlinuz-x86_64 (preferred) or kernel/vmlinux-x86_64 present. # Build via `make -C kernel TARGET_ARCH=x86_64` (or `make -C kernel x86_64`). # The script fails hard if neither is present. .PHONY: dist-x86_64 -dist-x86_64: linux-image +dist-x86_64: linux-image fetch-cloud-hypervisor-source fetch-virtiofsd $(call linux_run,./scripts/build-dist-x86_64.sh) endif diff --git a/Sources/Containerization/ContainerManager.swift b/Sources/Containerization/ContainerManager.swift index dac0dabf3..dfad2ca67 100644 --- a/Sources/Containerization/ContainerManager.swift +++ b/Sources/Containerization/ContainerManager.swift @@ -14,20 +14,21 @@ // limitations under the License. //===----------------------------------------------------------------------===// -#if os(macOS) - -import ContainerizationError import ContainerizationEXT4 +import ContainerizationError +import ContainerizationExtras import ContainerizationOCI import ContainerizationOS import Foundation import Logging -import ContainerizationExtras import SystemPackage -import Virtualization /// A manager for creating and running containers. /// Supports container networking options. +/// +/// The VMM-agnostic surface is cross-platform; the convenience initializers +/// that build a VMM for you are per-platform (`Virtualization.framework` on +/// macOS, `cloud-hypervisor` on Linux). public struct ContainerManager: Sendable { public let imageStore: ImageStore private let vmm: VirtualMachineManager @@ -41,179 +42,73 @@ public struct ContainerManager: Sendable { self.imageStore.path.appendingPathComponent("containers") } - /// Create a new manager with the provided kernel, initfs mount, image store - /// and optional network implementation. This will use a Virtualization.framework - /// backed VMM implicitly. + /// Create a new manager with the provided vmm, image store and network. public init( - kernel: Kernel, - initfs: Mount, + vmm: any VirtualMachineManager, imageStore: ImageStore, network: Network? = nil, - rosetta: Bool = false, - nestedVirtualization: Bool = false, snapshots: SnapshotManager? = nil, logger: Logger? = nil ) throws { self.imageStore = imageStore self.network = network + self.vmm = vmm self.snapshots = snapshots self.logger = logger - try Self.createRootDirectory(path: self.imageStore.path) - self.vmm = VZVirtualMachineManager( - kernel: kernel, - initialFilesystem: initfs, - rosetta: rosetta, - nestedVirtualization: nestedVirtualization, - logger: logger - ) + try Self.createRootDirectory(path: imageStore.path) } - /// Create a new manager with the provided kernel, initfs mount, root state - /// directory and optional network implementation. This will use a Virtualization.framework - /// backed VMM implicitly. + /// Create a new manager with the provided vmm and network, using the image + /// store rooted at `root`, or the default store when `root` is nil. public init( - kernel: Kernel, - initfs: Mount, + vmm: any VirtualMachineManager, root: URL? = nil, network: Network? = nil, - rosetta: Bool = false, - nestedVirtualization: Bool = false, snapshots: SnapshotManager? = nil, logger: Logger? = nil ) throws { - if let root { - self.imageStore = try ImageStore(path: root) - } else { - self.imageStore = ImageStore.default - } - self.network = network - self.snapshots = snapshots - self.logger = logger - try Self.createRootDirectory(path: self.imageStore.path) - self.vmm = VZVirtualMachineManager( - kernel: kernel, - initialFilesystem: initfs, - rosetta: rosetta, - nestedVirtualization: nestedVirtualization, + try self.init( + vmm: vmm, + imageStore: Self.resolveImageStore(at: root), + network: network, + snapshots: snapshots, logger: logger ) } - /// Create a new manager with the provided kernel, initfs reference, image store - /// and optional network implementation. This will use a Virtualization.framework - /// backed VMM implicitly. - public init( - kernel: Kernel, - initfsReference: String, - imageStore: ImageStore, - network: Network? = nil, - rosetta: Bool = false, - nestedVirtualization: Bool = false, - snapshots: SnapshotManager? = nil, - logger: Logger? = nil - ) async throws { - self.imageStore = imageStore - self.network = network - self.snapshots = snapshots - self.logger = logger - try Self.createRootDirectory(path: self.imageStore.path) - - let initPath = self.imageStore.path.appendingPathComponent("initfs.ext4") - let initImage = try await self.imageStore.getInitImage(reference: initfsReference) - let initfs = try await { - do { - return try await initImage.initBlock(at: initPath, for: .linuxArm) - } catch let err as ContainerizationError { - guard err.code == .exists else { - throw err - } - return .block( - format: "ext4", - source: initPath.absolutePath(), - destination: "/", - options: ["ro"] - ) - } - }() - - self.vmm = VZVirtualMachineManager( - kernel: kernel, - initialFilesystem: initfs, - rosetta: rosetta, - nestedVirtualization: nestedVirtualization, - logger: logger + private static func createRootDirectory(path: URL) throws { + try FileManager.default.createDirectory( + at: path.appendingPathComponent("containers"), + withIntermediateDirectories: true ) } - /// Create a new manager with the provided kernel and image reference for the initfs. - /// This will use a Virtualization.framework backed VMM implicitly. - public init( - kernel: Kernel, - initfsReference: String, - root: URL? = nil, - network: Network? = nil, - rosetta: Bool = false, - nestedVirtualization: Bool = false, - snapshots: SnapshotManager? = nil, - logger: Logger? = nil - ) async throws { - if let root { - self.imageStore = try ImageStore(path: root) - } else { - self.imageStore = ImageStore.default + /// Returns the image store at `root`, or the default store when nil. + fileprivate static func resolveImageStore(at root: URL?) throws -> ImageStore { + guard let root else { + return ImageStore.default } - self.network = network - self.snapshots = snapshots - self.logger = logger - try Self.createRootDirectory(path: self.imageStore.path) - - let initPath = self.imageStore.path.appendingPathComponent("initfs.ext4") - let initImage = try await self.imageStore.getInitImage(reference: initfsReference) - let initfs = try await { - do { - return try await initImage.initBlock(at: initPath, for: .linuxArm) - } catch let err as ContainerizationError { - guard err.code == .exists else { - throw err - } - return .block( - format: "ext4", - source: initPath.absolutePath(), - destination: "/", - options: ["ro"] - ) - } - }() - - self.vmm = VZVirtualMachineManager( - kernel: kernel, - initialFilesystem: initfs, - rosetta: rosetta, - nestedVirtualization: nestedVirtualization, - logger: logger - ) - } - - /// Create a new manager with the provided vmm and network. - public init( - vmm: any VirtualMachineManager, - network: Network? = nil, - snapshots: SnapshotManager? = nil, - logger: Logger? = nil - ) throws { - self.imageStore = ImageStore.default - try Self.createRootDirectory(path: self.imageStore.path) - self.network = network - self.vmm = vmm - self.snapshots = snapshots - self.logger = logger + return try ImageStore(path: root) } - private static func createRootDirectory(path: URL) throws { - try FileManager.default.createDirectory( - at: path.appendingPathComponent("containers"), - withIntermediateDirectories: true - ) + /// Unpacks the init image for the host architecture into the image store, + /// reusing the existing block if one is already present. + fileprivate static func initfsBlock(reference: String, imageStore: ImageStore) async throws -> Mount { + let initPath = imageStore.path.appendingPathComponent("initfs.ext4") + let initImage = try await imageStore.getInitImage(reference: reference) + do { + return try await initImage.initBlock(at: initPath, for: .linuxHost) + } catch let err as ContainerizationError { + guard err.code == .exists else { + throw err + } + return .block( + format: "ext4", + source: initPath.absolutePath(), + destination: "/", + options: ["ro"] + ) + } } /// Returns a new container from the provided image reference. @@ -256,8 +151,9 @@ public struct ContainerManager: Sendable { /// Returns a new container from the provided image. /// /// If the manager has `snapshots`, the root filesystem is a clone of the image's snapshot, and - /// the image is unpacked into `snapshots` first if it has no snapshot. The snapshots' `path` - /// must be on the same APFS volume as the image store, or creation fails. + /// the image is unpacked into `snapshots` first if it has no snapshot. On macOS, the snapshots' + /// `path` must be on the same APFS volume as the image store, or creation fails. On Linux, the + /// clone falls back to a copy. /// - Parameters: /// - id: The container ID. /// - image: The image. @@ -394,31 +290,47 @@ public struct ContainerManager: Sendable { configuration: (inout LinuxContainer.Configuration) throws -> Void ) async throws -> LinuxContainer { let imageConfig = try await image.config(for: .current).config - return try LinuxContainer( - id, - rootfs: rootfs, - writableLayer: writableLayer, - vmm: self.vmm, - vm: vm, - logger: self.logger - ) { config in - if let imageConfig { - config.process = .init(from: imageConfig) - } - if networking { - if let interface = try self.network?.createInterface(id) { - config.interfaces = [interface] - guard let gateway = interface.ipv4Gateway else { - throw ContainerizationError( - .invalidState, - message: "missing ipv4 gateway for container \(id)" - ) + // The default boot log lives under the container root. The image-based + // overloads create that directory; a caller-supplied rootfs reaches + // here without it, and both backends fail to open the log if it is + // missing. Only a directory created here is removed on failure. + let stateDirectory = containerRoot.appendingPathComponent(id) + let createdStateDirectory = !FileManager.default.fileExists(atPath: stateDirectory.path) + if createdStateDirectory { + try FileManager.default.createDirectory(at: stateDirectory, withIntermediateDirectories: true) + } + do { + return try LinuxContainer( + id, + rootfs: rootfs, + writableLayer: writableLayer, + vmm: self.vmm, + vm: vm, + logger: self.logger + ) { config in + if let imageConfig { + config.process = .init(from: imageConfig) + } + if networking { + if let interface = try self.network?.createInterface(id) { + config.interfaces = [interface] + guard let gateway = interface.ipv4Gateway else { + throw ContainerizationError( + .invalidState, + message: "missing ipv4 gateway for container \(id)" + ) + } + config.dns = .init(nameservers: [gateway.description]) } - config.dns = .init(nameservers: [gateway.description]) } + config.bootLog = BootLog.file(path: stateDirectory.appendingPathComponent("bootlog.log")) + try configuration(&config) + } + } catch { + if createdStateDirectory { + try? FileManager.default.removeItem(at: stateDirectory) } - config.bootLog = BootLog.file(path: self.containerRoot.appendingPathComponent(id).appendingPathComponent("bootlog.log")) - try configuration(&config) + throw error } } @@ -437,6 +349,8 @@ public struct ContainerManager: Sendable { try FileManager.default.removeItem(at: path) } + /// Creates the per-container state directory. Fails if one already exists, + /// so a duplicate container ID is an error rather than a silent reuse. private func createContainerRoot(_ id: String) throws -> URL { let path = containerRoot.appendingPathComponent(id) try FileManager.default.createDirectory(at: path, withIntermediateDirectories: false) @@ -444,20 +358,8 @@ public struct ContainerManager: Sendable { } private func unpack(image: Image, destination: URL, size: UInt64, progress: ProgressHandler? = nil) async throws -> Mount { - do { - let unpacker = EXT4Unpacker(capacityInBytes: size) - return try await unpacker.unpack(image, for: .current, at: destination, progress: progress) - } catch let err as ContainerizationError { - if err.code == .exists { - return .block( - format: "ext4", - source: destination.absolutePath(), - destination: "/", - options: [] - ) - } - throw err - } + let unpacker = EXT4Unpacker(capacityInBytes: size) + return try await unpacker.unpack(image, for: .current, at: destination, progress: progress) } private func createEmptyFilesystem(at destination: URL, size: UInt64) throws -> Mount { @@ -476,10 +378,228 @@ public struct ContainerManager: Sendable { } } -extension CIDRv6 { - /// The gateway address of the network. - public var gateway: IPv6Address { - IPv6Address(self.lower.value + 1) +#if os(macOS) + +extension ContainerManager { + /// Create a new manager with the provided kernel, initfs mount, image store + /// and optional network implementation. This will use a Virtualization.framework + /// backed VMM implicitly. + public init( + kernel: Kernel, + initfs: Mount, + imageStore: ImageStore, + network: Network? = nil, + rosetta: Bool = false, + nestedVirtualization: Bool = false, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) throws { + try self.init( + vmm: VZVirtualMachineManager( + kernel: kernel, + initialFilesystem: initfs, + rosetta: rosetta, + nestedVirtualization: nestedVirtualization, + logger: logger + ), + imageStore: imageStore, + network: network, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel, initfs mount, root state + /// directory and optional network implementation. This will use a Virtualization.framework + /// backed VMM implicitly. + public init( + kernel: Kernel, + initfs: Mount, + root: URL? = nil, + network: Network? = nil, + rosetta: Bool = false, + nestedVirtualization: Bool = false, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) throws { + try self.init( + kernel: kernel, + initfs: initfs, + imageStore: Self.resolveImageStore(at: root), + network: network, + rosetta: rosetta, + nestedVirtualization: nestedVirtualization, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel, initfs reference, image store + /// and optional network implementation. This will use a Virtualization.framework + /// backed VMM implicitly. + public init( + kernel: Kernel, + initfsReference: String, + imageStore: ImageStore, + network: Network? = nil, + rosetta: Bool = false, + nestedVirtualization: Bool = false, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) async throws { + try self.init( + kernel: kernel, + initfs: await Self.initfsBlock(reference: initfsReference, imageStore: imageStore), + imageStore: imageStore, + network: network, + rosetta: rosetta, + nestedVirtualization: nestedVirtualization, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel and image reference for the initfs. + /// This will use a Virtualization.framework backed VMM implicitly. + public init( + kernel: Kernel, + initfsReference: String, + root: URL? = nil, + network: Network? = nil, + rosetta: Bool = false, + nestedVirtualization: Bool = false, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) async throws { + try await self.init( + kernel: kernel, + initfsReference: initfsReference, + imageStore: Self.resolveImageStore(at: root), + network: network, + rosetta: rosetta, + nestedVirtualization: nestedVirtualization, + snapshots: snapshots, + logger: logger + ) + } +} + +#endif + +#if os(Linux) + +extension ContainerManager { + /// Create a new manager with the provided kernel, initfs mount, image store + /// and optional network implementation. This will use a cloud-hypervisor + /// backed VMM implicitly. + /// + /// `chBinary` and `virtiofsdBinary` default to a `PATH` lookup, and + /// `runtimeRoot` to `/run/containerization/ch`. + public init( + kernel: Kernel, + initfs: Mount, + imageStore: ImageStore, + network: Network? = nil, + chBinary: URL? = nil, + virtiofsdBinary: URL? = nil, + runtimeRoot: URL? = nil, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) throws { + try self.init( + vmm: CHVirtualMachineManager( + kernel: kernel, + initialFilesystem: initfs, + chBinary: chBinary, + virtiofsdBinary: virtiofsdBinary, + runtimeRoot: runtimeRoot, + logger: logger + ), + imageStore: imageStore, + network: network, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel, initfs mount, root state + /// directory and optional network implementation. This will use a + /// cloud-hypervisor backed VMM implicitly. + public init( + kernel: Kernel, + initfs: Mount, + root: URL? = nil, + network: Network? = nil, + chBinary: URL? = nil, + virtiofsdBinary: URL? = nil, + runtimeRoot: URL? = nil, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) throws { + try self.init( + kernel: kernel, + initfs: initfs, + imageStore: Self.resolveImageStore(at: root), + network: network, + chBinary: chBinary, + virtiofsdBinary: virtiofsdBinary, + runtimeRoot: runtimeRoot, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel, initfs reference, image store + /// and optional network implementation. This will use a cloud-hypervisor + /// backed VMM implicitly. + public init( + kernel: Kernel, + initfsReference: String, + imageStore: ImageStore, + network: Network? = nil, + chBinary: URL? = nil, + virtiofsdBinary: URL? = nil, + runtimeRoot: URL? = nil, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) async throws { + try self.init( + kernel: kernel, + initfs: await Self.initfsBlock(reference: initfsReference, imageStore: imageStore), + imageStore: imageStore, + network: network, + chBinary: chBinary, + virtiofsdBinary: virtiofsdBinary, + runtimeRoot: runtimeRoot, + snapshots: snapshots, + logger: logger + ) + } + + /// Create a new manager with the provided kernel and image reference for the initfs. + /// This will use a cloud-hypervisor backed VMM implicitly. + public init( + kernel: Kernel, + initfsReference: String, + root: URL? = nil, + network: Network? = nil, + chBinary: URL? = nil, + virtiofsdBinary: URL? = nil, + runtimeRoot: URL? = nil, + snapshots: SnapshotManager? = nil, + logger: Logger? = nil + ) async throws { + try await self.init( + kernel: kernel, + initfsReference: initfsReference, + imageStore: Self.resolveImageStore(at: root), + network: network, + chBinary: chBinary, + virtiofsdBinary: virtiofsdBinary, + runtimeRoot: runtimeRoot, + snapshots: snapshots, + logger: logger + ) } } diff --git a/Sources/Containerization/SystemPlatform.swift b/Sources/Containerization/SystemPlatform.swift index 341ba50ce..3e96b5689 100644 --- a/Sources/Containerization/SystemPlatform.swift +++ b/Sources/Containerization/SystemPlatform.swift @@ -38,4 +38,16 @@ public struct SystemPlatform: Sendable, Codable { public static var linuxArm: SystemPlatform { .init(os: .linux, architecture: .arm64) } public static var linuxAmd: SystemPlatform { .init(os: .linux, architecture: .amd64) } + + /// The Linux platform matching the host architecture. Guests run the host + /// architecture; there is no cross-architecture emulation. + public static var linuxHost: SystemPlatform { + #if arch(arm64) + return .linuxArm + #elseif arch(x86_64) + return .linuxAmd + #else + #error("unsupported host architecture (expected arm64 or x86_64)") + #endif + } } diff --git a/Sources/ContainerizationExtras/CIDRv6.swift b/Sources/ContainerizationExtras/CIDRv6.swift index 3734af81b..d1e725c50 100644 --- a/Sources/ContainerizationExtras/CIDRv6.swift +++ b/Sources/ContainerizationExtras/CIDRv6.swift @@ -113,3 +113,11 @@ extension CIDRv6: Codable { try container.encode(description) } } + +extension CIDRv6 { + /// The gateway address of the network. Conventionally the first usable + /// address in the subnet (`lower + 1`). + public var gateway: IPv6Address { + IPv6Address(self.lower.value + 1) + } +} diff --git a/Sources/Integration/ContainerTests.swift b/Sources/Integration/ContainerTests.swift index 1f2491c5c..976df41c8 100644 --- a/Sources/Integration/ContainerTests.swift +++ b/Sources/Integration/ContainerTests.swift @@ -677,6 +677,7 @@ extension IntegrationSuite { throw IntegrationError.assert(msg: "process status \(status) != 0") } } + #endif func testContainerManagerCreate() async throws { let id = "test-container-manager" @@ -939,8 +940,6 @@ extension IntegrationSuite { return "inode=\(inode) modified=\(modified.timeIntervalSince1970) size=\(size)" } - #endif - func testContainerStatistics() async throws { let id = "test-container-statistics" diff --git a/Sources/Integration/Suite.swift b/Sources/Integration/Suite.swift index f0e9a1f1e..b78f2a407 100644 --- a/Sources/Integration/Suite.swift +++ b/Sources/Integration/Suite.swift @@ -509,6 +509,13 @@ struct IntegrationSuite: AsyncParsableCommand { Test("multiple execs without delete", testMultipleExecsWithoutDelete), Test("sequential execs reuse stdio ports", testSequentialExecsReuseStdioPorts), + // ContainerManager (VZ on macOS, cloud-hypervisor on Linux) + Test("container stop idempotency", testContainerStopIdempotency), + Test("container manager", testContainerManagerCreate), + Test("container manager snapshot", testContainerManagerCreateFromSnapshot), + Test("container reuse", testContainerReuse), + Test("container /dev/console", testContainerDevConsole), + // Capabilities Test("container capabilities sys admin", testCapabilitiesSysAdmin), Test("container capabilities net admin", testCapabilitiesNetAdmin), @@ -682,13 +689,6 @@ struct IntegrationSuite: AsyncParsableCommand { #if os(macOS) let macOSOnlyTests: [Test] = [ - // ContainerManager-based tests (ContainerManager is macOS-only) - Test("container stop idempotency", testContainerStopIdempotency), - Test("container manager", testContainerManagerCreate), - Test("container manager snapshot", testContainerManagerCreateFromSnapshot), - Test("container reuse", testContainerReuse), - Test("container /dev/console", testContainerDevConsole), - // Nested virtualization (VZ-only feature) Test("nested virt", testNestedVirtualizationEnabled), diff --git a/Sources/cctl/RunCommand.swift b/Sources/cctl/RunCommand.swift index 13ec44833..4d2553f3e 100644 --- a/Sources/cctl/RunCommand.swift +++ b/Sources/cctl/RunCommand.swift @@ -553,18 +553,9 @@ extension Application { // trip first. let seccompSelection = try SeccompFlags.resolve(seccomp: seccomp, profilePath: seccompProfile) - #if arch(arm64) - let kernelPlatform = SystemPlatform.linuxArm - #elseif arch(x86_64) - let kernelPlatform = SystemPlatform.linuxAmd - #else - #error("unsupported host architecture for `cctl run` (expected arm64 or x86_64)") - #endif - let imagePlatform = Platform.current - let kernelObj = Kernel( path: URL(fileURLWithPath: kernel), - platform: kernelPlatform + platform: .linuxHost ) // Wire up the host TTY when there is one. `Terminal.current` walks @@ -578,9 +569,6 @@ extension Application { defer { hostTerminal?.tryReset() } let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH]) - // Pull the container image and unpack to a per-container ext4 (same - // shape as ContainerManager.unpack on macOS: reuse the existing - // rootfs.ext4 if it's already there, fresh-unpack otherwise). let imageStore = Application.imageStore let reference = try Reference.parse(imageReference) reference.normalize() @@ -590,28 +578,6 @@ extension Application { } let image = try await imageStore.get(reference: normalizedRef, pull: true) - let containersRoot = Application.appRoot - .appendingPathComponent("containers") - .appendingPathComponent(id) - try FileManager.default.createDirectory(at: containersRoot, withIntermediateDirectories: true) - let rootfsPath = containersRoot.appendingPathComponent("rootfs.ext4") - - var rootfsMount: Containerization.Mount - do { - let unpacker = EXT4Unpacker(capacityInBytes: fsSizeInMB.mib()) - rootfsMount = try await unpacker.unpack(image, for: imagePlatform, at: rootfsPath) - } catch let err as ContainerizationError where err.code == .exists { - rootfsMount = .block( - format: "ext4", - source: rootfsPath.absolutePath(), - destination: "/", - options: [] - ) - } - if readOnly { - rootfsMount.options.append("ro") - } - let initfsMount = Mount.block( format: "ext4", source: initfs, @@ -619,42 +585,15 @@ extension Application { options: ["ro"] ) - let manager = try CHVirtualMachineManager( - kernel: kernelObj, - initialFilesystem: initfsMount, - chBinary: chBinary.map { URL(fileURLWithPath: $0) }, - virtiofsdBinary: virtiofsdBinary.map { URL(fileURLWithPath: $0) }, - logger: log - ) - - // Seed process config from the image (entrypoint, env, cwd, user), - // then layer user-provided overrides on top — same precedence as - // ContainerManager + macOS Run. - let imageConfig = try await image.config(for: imagePlatform).config - var processConfig = LinuxProcessConfiguration() - if let imageConfig { - processConfig = .init(from: imageConfig) - } - processConfig.arguments = try Application.resolveProcessArguments( - arguments: arguments, - entrypointOverride: entrypointOverride, - imageConfig: imageConfig, - imageReference: imageReference - ) - processConfig.workingDirectory = cwd - if let hostTerminal { - processConfig.setTerminalIO(terminal: hostTerminal) - } - - var interfaces: [any Interface] = [] - var dnsConfig: DNS? = nil - var hostsConfig: Hosts? = nil - + // Creates the bridge and its NAT rules if missing; `cctl bridge delete` + // tears them down. LinuxBridgedNetwork only owns the per-container TAP, + // which ContainerManager allocates and releases with the container. + var network: (any Network)? = nil if !noNetwork { let subnetCIDR = try CIDRv4(subnet) let gw = try bridgeGateway.map { try IPv4Address($0) } - let mgr = BridgeManager( + let bridgeManager = BridgeManager( name: bridge, subnet: subnetCIDR, gateway: gw, @@ -663,61 +602,76 @@ extension Application { enableNAT: enableNAT, logger: log ) - try mgr.create() + try bridgeManager.create() - var network = try LinuxBridgedNetwork( + network = try LinuxBridgedNetwork( subnet: subnetCIDR, gateway: gw, bridge: bridge, mtu: 1500 ) - if let iface = try network.createInterface(id) { - interfaces.append(iface) + } + + var manager = try ContainerManager( + kernel: kernelObj, + initfs: initfsMount, + imageStore: imageStore, + network: network, + chBinary: chBinary.map { URL(fileURLWithPath: $0) }, + virtiofsdBinary: virtiofsdBinary.map { URL(fileURLWithPath: $0) }, + logger: log + ) + + let imageConfig = try await image.config(for: Platform.current).config + let processArguments = try Application.resolveProcessArguments( + arguments: arguments, + entrypointOverride: entrypointOverride, + imageConfig: imageConfig, + imageReference: imageReference + ) + + let container = try await manager.create( + id, + image: image, + rootfsSizeInBytes: fsSizeInMB.mib(), + readOnly: readOnly, + networking: !noNetwork, + // Give the VM memory headroom for the guest kernel and vminitd. + vm: VMResources(cpus: cpus, memoryInBytes: memory.mib() + VMResources.guestMemoryOverhead) + ) { config in + config.cpus = self.cpus + config.memoryInBytes = self.memory.mib() + config.process.arguments = processArguments + config.process.workingDirectory = self.cwd + if let hostTerminal { + config.process.setTerminalIO(terminal: hostTerminal) + } + config.useInit = self.`init` - var h = Hosts.default - h.entries.append( + if let interface = config.interfaces.first { + var hosts = Hosts.default + hosts.entries.append( .init( - ipAddress: iface.ipv4Address.address.description, - hostnames: [id] + ipAddress: interface.ipv4Address.address.description, + hostnames: [self.id] )) - hostsConfig = h + config.hosts = hosts + // ContainerManager points DNS at the gateway; cctl prefers + // --ns, falling back to the host resolver. let resolved = - nameservers.isEmpty + self.nameservers.isEmpty ? Self.readHostNameservers() - : nameservers - dnsConfig = DNS(nameservers: resolved) + : self.nameservers + config.dns = DNS(nameservers: resolved) } - } - let cpusCount = cpus - let memoryBytes = memory.mib() - let networkInterfaces = interfaces - let useInit = self.`init` - let extraMounts = self.mounts - let extraBlocks = self.blocks - let extraCaps = self.capAdd - let runtimePath = self.ociRuntimePath - let dns = dnsConfig - let hosts = hostsConfig - - let container = try LinuxContainer( - id, - rootfs: rootfsMount, - vmm: manager, - // Give the VM memory headroom for the guest kernel and vminitd. - vm: VMResources(cpus: cpusCount, memoryInBytes: memoryBytes + VMResources.guestMemoryOverhead), - logger: log - ) { config in - config.process = processConfig - config.cpus = cpusCount - config.memoryInBytes = memoryBytes - config.interfaces = networkInterfaces - config.useInit = useInit - if let dns { config.dns = dns } - if let hosts { config.hosts = hosts } - - for mount in extraMounts { + if let ociRuntimePath = self.ociRuntimePath { + config.ociRuntimePath = ociRuntimePath + } + config.seccompProfile = seccompSelection + + for mount in self.mounts { let paths = mount.split(separator: ":") if paths.count != 2 { throw ContainerizationError( @@ -729,17 +683,11 @@ extension Application { Mount.share(source: String(paths[0]), destination: String(paths[1])) ) } + config.mounts.append(contentsOf: self.blocks) - if let runtimePath { - config.ociRuntimePath = runtimePath - } - config.seccompProfile = seccompSelection - - config.mounts.append(contentsOf: extraBlocks) - - if !extraCaps.isEmpty { + if !self.capAdd.isEmpty { var caps = LinuxCapabilities.defaultOCICapabilities - for cap in extraCaps { + for cap in self.capAdd { caps.bounding.append(cap) caps.effective.append(cap) caps.permitted.append(cap) @@ -748,6 +696,10 @@ extension Application { } } + defer { + try? manager.delete(id) + } + try await container.create() try await container.start() diff --git a/Tests/ContainerizationExtrasTests/TestCIDR.swift b/Tests/ContainerizationExtrasTests/TestCIDR.swift index b884bf023..575645c84 100644 --- a/Tests/ContainerizationExtrasTests/TestCIDR.swift +++ b/Tests/ContainerizationExtrasTests/TestCIDR.swift @@ -467,4 +467,10 @@ struct TestCIDR { let expected = try CIDRv6(cidr) #expect(decoded == expected) } + + @Test func testCIDRv6Gateway() throws { + // The network gateway is the lowest address + 1. + #expect((try CIDRv6("fd00::/64")).gateway == (try IPv6Address("fd00::1"))) + #expect((try CIDRv6("fd00:abcd:1234::/48")).gateway == (try IPv6Address("fd00:abcd:1234::1"))) + } } diff --git a/Tests/ContainerizationTests/AllocatorTests.swift b/Tests/ContainerizationTests/AllocatorTests.swift index 8bb80d2a9..56f1dd1a4 100644 --- a/Tests/ContainerizationTests/AllocatorTests.swift +++ b/Tests/ContainerizationTests/AllocatorTests.swift @@ -101,12 +101,6 @@ struct AllocatorTests { #expect(bHost == 3) } - @Test func cidrV6Gateway() throws { - // The network gateway is the lowest address + 1. - #expect((try CIDRv6("fd00::/64")).gateway == (try IPv6Address("fd00::1"))) - #expect((try CIDRv6("fd00:abcd:1234::/48")).gateway == (try IPv6Address("fd00:abcd:1234::1"))) - } - @available(macOS 26, *) private actor SerialAllocator { private var inner: VmnetNetwork.Allocator diff --git a/Tests/ContainerizationTests/ContainerManagerTests.swift b/Tests/ContainerizationTests/ContainerManagerTests.swift index 1eb340a76..7253dc2ec 100644 --- a/Tests/ContainerizationTests/ContainerManagerTests.swift +++ b/Tests/ContainerizationTests/ContainerManagerTests.swift @@ -14,9 +14,6 @@ // limitations under the License. //===----------------------------------------------------------------------===// -#if os(macOS) - -import Containerization import ContainerizationArchive import ContainerizationEXT4 import ContainerizationError @@ -45,6 +42,14 @@ private struct NilGatewayNetwork: Network { mutating func releaseInterface(_ id: String) throws {} } +/// A VMM that cannot boot. `ContainerManager.create` only builds a +/// `LinuxContainer`, so nothing here is ever called. +private struct UnbootableVirtualMachineManager: VirtualMachineManager { + func create(config: some VMCreationConfig) async throws -> any VirtualMachineInstance { + throw ContainerizationError(.unsupported, message: "test VMM cannot boot") + } +} + @Suite struct ContainerManagerTests { @Test func testCreateThrowsWhenGatewayMissing() async throws { @@ -52,17 +57,8 @@ struct ContainerManagerTests { let root = fm.uniqueTemporaryDirectory(create: true) defer { try? fm.removeItem(at: root) } - let kernelPath = root.appendingPathComponent("vmlinux") - fm.createFile(atPath: kernelPath.path, contents: Data(), attributes: nil) - let initfsPath = root.appendingPathComponent("initfs.ext4") - fm.createFile(atPath: initfsPath.path, contents: Data(), attributes: nil) - - let kernel = Kernel(path: kernelPath, platform: .linuxArm) - let initfs = Mount.block(format: "ext4", source: initfsPath.path, destination: "/") - var manager = try ContainerManager( - kernel: kernel, - initfs: initfs, + vmm: UnbootableVirtualMachineManager(), root: root, network: NilGatewayNetwork() ) @@ -79,7 +75,7 @@ struct ContainerManagerTests { let image = images.first! let rootfsPath = root.appendingPathComponent("rootfs.ext4") - fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) + _ = fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) let rootfs = Mount.block(format: "ext4", source: rootfsPath.path, destination: "/") do { @@ -98,19 +94,10 @@ struct ContainerManagerTests { let root = fm.uniqueTemporaryDirectory(create: true) defer { try? fm.removeItem(at: root) } - let kernelPath = root.appendingPathComponent("vmlinux") - fm.createFile(atPath: kernelPath.path, contents: Data(), attributes: nil) - let initfsPath = root.appendingPathComponent("initfs.ext4") - fm.createFile(atPath: initfsPath.path, contents: Data(), attributes: nil) - - let kernel = Kernel(path: kernelPath, platform: .linuxArm) - let initfs = Mount.block(format: "ext4", source: initfsPath.path, destination: "/") - // Use NilGatewayNetwork — with networking: true this would throw invalidState, // but with networking: false the network's createInterface() is never called. var manager = try ContainerManager( - kernel: kernel, - initfs: initfs, + vmm: UnbootableVirtualMachineManager(), root: root, network: NilGatewayNetwork() ) @@ -127,7 +114,7 @@ struct ContainerManagerTests { let image = images.first! let rootfsPath = root.appendingPathComponent("rootfs.ext4") - fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) + _ = fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) let rootfs = Mount.block(format: "ext4", source: rootfsPath.path, destination: "/") // With networking: false, NilGatewayNetwork.createInterface() is never called, @@ -160,15 +147,7 @@ struct ContainerManagerTests { let root = fm.uniqueTemporaryDirectory(create: true) defer { try? fm.removeItem(at: root) } - let kernelPath = root.appendingPathComponent("vmlinux") - fm.createFile(atPath: kernelPath.path, contents: Data(), attributes: nil) - let initfsPath = root.appendingPathComponent("initfs.ext4") - fm.createFile(atPath: initfsPath.path, contents: Data(), attributes: nil) - - let kernel = Kernel(path: kernelPath, platform: .linuxArm) - let initfs = Mount.block(format: "ext4", source: initfsPath.path, destination: "/") - - var manager = try ContainerManager(kernel: kernel, initfs: initfs, root: root, network: NilGatewayNetwork()) + var manager = try ContainerManager(vmm: UnbootableVirtualMachineManager(), root: root, network: NilGatewayNetwork()) let tempDir = fm.uniqueTemporaryDirectory() defer { try? fm.removeItem(at: tempDir) } @@ -183,7 +162,7 @@ struct ContainerManagerTests { // Stands in for a root filesystem outside the container's directory, such as an NBD export. let rootfsPath = root.appendingPathComponent("shared.ext4") - fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) + _ = fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) let rootfs = Mount.block(format: "ext4", source: rootfsPath.path, destination: "/") let container = try await manager.create( @@ -208,21 +187,42 @@ struct ContainerManagerTests { #expect(!fm.fileExists(atPath: root.appendingPathComponent("containers").appendingPathComponent("rootfs-failed").path)) } - @Test func testCreateFromSnapshotClonesTheSnapshotIntoTheContainerDirectory() async throws { + @Test func testFailedCreateFromRootfsMountRemovesTheContainerDirectory() async throws { let fm = FileManager.default let root = fm.uniqueTemporaryDirectory(create: true) defer { try? fm.removeItem(at: root) } - let kernelPath = root.appendingPathComponent("vmlinux") - fm.createFile(atPath: kernelPath.path, contents: Data(), attributes: nil) - let initfsPath = root.appendingPathComponent("initfs.ext4") - fm.createFile(atPath: initfsPath.path, contents: Data(), attributes: nil) + var manager = try ContainerManager(vmm: UnbootableVirtualMachineManager(), root: root, network: NilGatewayNetwork()) + + let tempDir = fm.uniqueTemporaryDirectory() + defer { try? fm.removeItem(at: tempDir) } + + let tarPath = try #require(Foundation.Bundle.module.url(forResource: "scratch", withExtension: "tar")) + let reader = try ArchiveReader(format: .pax, filter: .none, file: tarPath) + let rejectedPaths = try reader.extractContents(to: tempDir) + #expect(rejectedPaths.isEmpty) + + let images = try await manager.imageStore.load(from: tempDir) + let image = try #require(images.first) - let kernel = Kernel(path: kernelPath, platform: .linuxArm) - let initfs = Mount.block(format: "ext4", source: initfsPath.path, destination: "/") + let rootfsPath = root.appendingPathComponent("shared.ext4") + _ = fm.createFile(atPath: rootfsPath.path, contents: Data(), attributes: nil) + let rootfs = Mount.block(format: "ext4", source: rootfsPath.path, destination: "/") + + // NilGatewayNetwork makes the create fail inside the configuration closure. + await #expect(throws: ContainerizationError.self) { + _ = try await manager.create("rootfs-mount-failed", image: image, rootfs: rootfs) { _ in } + } + #expect(!fm.fileExists(atPath: root.appendingPathComponent("containers").appendingPathComponent("rootfs-mount-failed").path)) + } + + @Test func testCreateFromSnapshotClonesTheSnapshotIntoTheContainerDirectory() async throws { + let fm = FileManager.default + let root = fm.uniqueTemporaryDirectory(create: true) + defer { try? fm.removeItem(at: root) } let snapshots = try SnapshotManager(path: root.appendingPathComponent("snapshots"), capacityInBytes: 16.mib()) - var manager = try ContainerManager(kernel: kernel, initfs: initfs, root: root, snapshots: snapshots) + var manager = try ContainerManager(vmm: UnbootableVirtualMachineManager(), root: root, snapshots: snapshots) let tempDir = fm.uniqueTemporaryDirectory() defer { try? fm.removeItem(at: tempDir) } @@ -265,5 +265,3 @@ struct ContainerManagerTests { #expect(fm.fileExists(atPath: second.rootfs.source)) } } - -#endif diff --git a/docs/x86_64-build.md b/docs/x86_64-build.md index 102a1bbfb..71d31f05b 100644 --- a/docs/x86_64-build.md +++ b/docs/x86_64-build.md @@ -21,13 +21,16 @@ distro shipped in the last few years. Before the first `make dist-x86_64`: -1. **Source checkouts under `.local/`** — pinned by you, not fetched by the - build. There is no fetch target; clone the revision you want shipped: +1. **Source checkouts under `.local/`** — fetched by the build. `make + dist-x86_64` depends on `fetch-cloud-hypervisor-source` and + `fetch-virtiofsd`, which clone the pinned tags + (`CLOUD_HYPERVISOR_VERSION`, `VIRTIOFSD_VERSION` in the Makefile) with + full history. Either target is a no-op once the directory exists, so to + ship a different revision, check it out in place: ```sh - git clone -b v52.0 https://github.com/cloud-hypervisor/cloud-hypervisor \ - .local/cloud-hypervisor - git clone https://gitlab.com/virtio-fs/virtiofsd .local/virtiofsd + make fetch-cloud-hypervisor-source fetch-virtiofsd + git -C .local/cloud-hypervisor checkout ``` 2. **An x86_64 kernel** at `kernel/vmlinuz-x86_64` (preferred) or @@ -198,9 +201,9 @@ triggers a rebuild on the next `make dist-x86_64`. ## Troubleshooting -- **`ERROR: missing .local/cloud-hypervisor source checkout`** — see - Prerequisites. There is no fetch target; clone the revision you want - pinned. +- **`ERROR: missing .local/cloud-hypervisor source checkout`** — the + script was run directly rather than via `make dist-x86_64`. Run + `make fetch-cloud-hypervisor-source` (or `make fetch-virtiofsd`) first. - **`ERROR: no x86_64 kernel found`** — run `make -C kernel TARGET_ARCH=x86_64`. The build refuses to ship a tarball without a kernel. diff --git a/scripts/build-dist-x86_64.sh b/scripts/build-dist-x86_64.sh index 765a8fa27..1a1ca07c9 100755 --- a/scripts/build-dist-x86_64.sh +++ b/scripts/build-dist-x86_64.sh @@ -80,12 +80,12 @@ export CARGO_TARGET_X86_64_UNKNOWN_LINUX_MUSL_RUSTFLAGS="-L native=${CROSS_PREFI # Pre-flight checks [ -f .local/cloud-hypervisor/Cargo.toml ] || { echo "ERROR: missing .local/cloud-hypervisor source checkout." >&2 - echo " git clone -b v52.0 https://github.com/cloud-hypervisor/cloud-hypervisor .local/cloud-hypervisor" >&2 + echo " run 'make fetch-cloud-hypervisor-source' on the host" >&2 exit 1 } [ -f .local/virtiofsd/Cargo.toml ] || { echo "ERROR: missing .local/virtiofsd source checkout." >&2 - echo " git clone https://gitlab.com/virtio-fs/virtiofsd .local/virtiofsd" >&2 + echo " run 'make fetch-virtiofsd' on the host" >&2 exit 1 }