`system prune` removes only stopped containers and reports 0B; `image prune` is unsupported; build cache cannot be reclaimed
mocker version: 0.9.7 (Homebrew) — macOS 27, container 1.5.0, arm64; reproduced on 0.9.6 and again on 0.9.7. Code references are against main @ 4402015.
Summary
system prune asks the Docker question — stopped containers, dangling images, with --volumes unused volumes — and then removes only the stopped containers and prints Total reclaimed space: 0B (System.swift:154-188). image prune throws "not yet supported" (ImagePrune.swift:33). Networks and the build cache are not touched at all, and the build cache is where the space goes: BuildKit runs in the builder VM and its disk only grows.
$ du -sh ~/Library/Application\ Support/com.apple.container/containers/buildkit/rootfs.ext4
24G
Reproduction
$ mocker system prune
WARNING! This will remove:
- all stopped containers
- all dangling images
Are you sure you want to continue? [y/N] y
Deleted 0 containers
Total reclaimed space: 0B # 10 untagged builds (1 GB) and the 24 GB builder disk are still there
$ mocker image prune
Error response from daemon: image prune is not yet supported with Apple Containerization
Docker's contract for system prune: stopped containers, networks not used by a container, dangling images (with -a: every image no container uses), build cache (with -a: all of it), and with --volumes anonymous volumes not used by a container.
Proposed behaviour (what the branch does)
Docker is the contract; the runtime is only the means. Where container cannot do exactly the same thing, the branch goes for the same visible outcome, and never silently skips a step.
system pruneremoves stopped containers, unused networks (via the existingnetwork prunelogic, moved toNetworkManager.prune()), dangling images and the build cache;--volumesadds anonymous volumes and-aevery image no container uses. Output follows Docker's sections (Deleted Containers:…Total reclaimed space:) and the total is measured.image prune [-a]is implemented. Docker's "dangling" is an unnamed image; this store names every image and an untaggedmocker buildgets a UUID, so a UUID-named:latestimage is what dangling means here. The runtime's own images (ghcr.io/apple/containerization/*,ghcr.io/apple/container-builder-shim/*) are never candidates. Afterwardscontainer image prunegarbage-collects orphaned blobs.builder pruneis new.containerhas no way to prune part of BuildKit's cache, so Docker's "remove build cache" maps tocontainer builder delete; the nextmocker buildstarts a fresh builder on its own. A build loses time to it, never data. This is also whatsystem prunedoes for the cache in both modes.--filteris rejected on both prune commands rather than ignored, asvolume prunealready does.
Verified on container 1.5.0:
$ mocker builder prune -f
Total: 25,91 GB # builder gone; the next `mocker build` recreated it unasked
$ mocker image prune -f
Deleted Images:
untagged: docker.io/library/79924ea9-95a0-4646-a6ed-bc3a748b5761:latest
… # 10 untagged builds
Total reclaimed space: 1,04 GB # alpine, golang, node, … and the runtime's images untouched
$ mocker system prune -f --volumes # with a stopped container, an unused network, an unused anonymous volume
Deleted Containers:
sp-stopped
Deleted Networks:
sp-net
Deleted Volumes:
fa55bd35-1d46-4810-a449-918c5abefdd5
Deleted Images:
untagged: docker.io/library/945ea921-1378-4d8e-82b6-a865b93aac7d:latest
Deleted build cache
Total reclaimed space: 480,1 MB
$ mocker system prune -a -f # with a container running alpine:3.20
… # removed every other image; kept alpine:3.20 and the runtime's four images
Left out on purpose: --filter until=… (no timestamps to evaluate), system df, and — a separate bug — mocker run -v /path does not create an anonymous volume the way container run -v /path does, so --volumes mostly finds volumes created by compose or by container directly.
A tested fix is on my fork, branch fix/system-prune (compare); the diff is below. Happy to open it as a PR if you want it, or you can take it from here — see the note in #103 about coordinating.
Proposed fix: git diff main...fix/system-prune
diff --git a/Sources/Mocker/Commands/BuilderCmd.swift b/Sources/Mocker/Commands/BuilderCmd.swift
new file mode 100644
index 0000000..deaf13e
--- /dev/null
+++ b/Sources/Mocker/Commands/BuilderCmd.swift
@@ -0,0 +1,35 @@
+import ArgumentParser
+import MockerKit
+
+struct BuilderCommand: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "builder",
+ abstract: "Manage builds",
+ subcommands: [BuilderPrune.self]
+ )
+}
+
+struct BuilderPrune: AsyncParsableCommand {
+ static let configuration = CommandConfiguration(
+ commandName: "prune",
+ abstract: "Remove build cache"
+ )
+
+ @Flag(name: .shortAndLong, help: "Remove all unused build cache, not just dangling ones")
+ var all = false
+
+ @Flag(name: .shortAndLong, help: "Do not prompt for confirmation")
+ var force = false
+
+ func run() async throws {
+ // The cache cannot be pruned in part (see `BuildCache`), so --all changes nothing here.
+ if !force {
+ print("WARNING! This will remove all build cache. Are you sure you want to continue? [y/N] ", terminator: "")
+ guard let answer = readLine(), answer.lowercased() == "y" else {
+ print("Cancelled.")
+ return
+ }
+ }
+ print("Total: \(ImagePrune.bytes(try await BuildCache.prune()))")
+ }
+}
diff --git a/Sources/Mocker/Commands/ImagePrune.swift b/Sources/Mocker/Commands/ImagePrune.swift
index ee71996..4f7b11a 100644
--- a/Sources/Mocker/Commands/ImagePrune.swift
+++ b/Sources/Mocker/Commands/ImagePrune.swift
@@ -1,4 +1,5 @@
import ArgumentParser
+import Foundation
import MockerKit
struct ImagePrune: AsyncParsableCommand {
@@ -17,6 +18,36 @@ struct ImagePrune: AsyncParsableCommand {
var force = false
func run() async throws {
- throw MockerError.operationFailed("image prune is not yet supported with Apple Containerization")
+ // Pruning more than the filter asks for would delete images the user meant to keep.
+ guard filter.isEmpty else {
+ throw MockerError.operationFailed("image prune --filter is not supported")
+ }
+ if !force {
+ print("WARNING! This will remove \(all ? "all images without at least one container associated to them" : "all dangling images").")
+ print("Are you sure you want to continue? [y/N] ", terminator: "")
+ guard let answer = readLine(), answer.lowercased() == "y" else {
+ print("Cancelled.")
+ return
+ }
+ }
+
+ let config = MockerConfig()
+ let inUse = try await ContainerEngine(config: config).list(all: true).map(\.image)
+ let result = try await ImageManager(config: config).prune(all: all, inUse: inUse)
+ Self.report(result.removed)
+ print("Total reclaimed space: \(Self.bytes(result.reclaimed))")
+ }
+
+ /// Docker's listing of what went: one `untagged:` line per name.
+ static func report(_ images: [ImageInfo]) {
+ guard !images.isEmpty else { return }
+ print("Deleted Images:")
+ for image in images { print("untagged: \(image.reference)") }
+ print("")
+ }
+
+ static func bytes(_ count: UInt64) -> String {
+ // The formatter says "Zero KB"; Docker says "0B".
+ count == 0 ? "0B" : ByteCountFormatter.string(fromByteCount: Int64(count), countStyle: .file)
}
}
diff --git a/Sources/Mocker/Commands/Network.swift b/Sources/Mocker/Commands/Network.swift
index bced543..f86b19f 100644
--- a/Sources/Mocker/Commands/Network.swift
+++ b/Sources/Mocker/Commands/Network.swift
@@ -253,20 +253,8 @@ struct NetworkPrune: AsyncParsableCommand {
let config = MockerConfig()
let manager = try NetworkManager(config: config)
- let networks = try await manager.list()
-
- var removed = 0
- // `list()` now returns the runtime's real networks, which include its built-in
- // one — pruning that would break every container that does not name a network.
- for n in networks where !NetworkManager.isBuiltIn(n)
- && n.name != "bridge" && n.name != "host" && n.name != "none" {
- // Count what was actually removed: a network with containers attached stays,
- // and reporting it as deleted sends people looking for a network that is still there.
- if (try? await manager.remove(n.name)) != nil {
- removed += 1
- }
- }
- print("Deleted \(removed) networks")
+ let removed = try await manager.prune()
+ print("Deleted \(removed.count) networks")
}
}
diff --git a/Sources/Mocker/Commands/System.swift b/Sources/Mocker/Commands/System.swift
index 067aecb..43ae9ac 100644
--- a/Sources/Mocker/Commands/System.swift
+++ b/Sources/Mocker/Commands/System.swift
@@ -152,17 +152,19 @@ struct SystemPrune: AsyncParsableCommand {
var filter: [String] = []
func run() async throws {
+ // Pruning more than the filter asks for would delete data the user meant to keep.
+ guard filter.isEmpty else {
+ throw MockerError.operationFailed("system prune --filter is not supported")
+ }
if !force {
print("WARNING! This will remove:")
print(" - all stopped containers")
- if all {
- print(" - all unused images")
- } else {
- print(" - all dangling images")
- }
+ print(" - all networks not used by at least one container")
if volumes {
- print(" - all unused volumes")
+ print(" - all anonymous volumes not used by at least one container")
}
+ print(all ? " - all images without at least one container associated to them" : " - all dangling images")
+ print(all ? " - all build cache" : " - unused build cache")
print("")
print("Are you sure you want to continue? [y/N] ", terminator: "")
@@ -175,16 +177,37 @@ struct SystemPrune: AsyncParsableCommand {
let config = MockerConfig()
let engine = try ContainerEngine(config: config)
- // Remove stopped containers
let containers = try await engine.list(all: true)
- var removedContainers = 0
+ var deletedContainers: [String] = []
for container in containers where !container.state.isActive {
- _ = try await engine.remove(container.id)
- removedContainers += 1
+ deletedContainers.append(try await engine.remove(container.id).name)
+ }
+ Self.report("Deleted Containers:", deletedContainers)
+
+ Self.report("Deleted Networks:", try await NetworkManager(config: config).prune())
+
+ if volumes {
+ Self.report("Deleted Volumes:", try await VolumeManager(config: config).prune(all: false))
}
- print("Deleted \(removedContainers) containers")
- print("Total reclaimed space: 0B")
+ // Only the containers still present keep their images.
+ let inUse = containers.filter { $0.state.isActive }.map(\.image)
+ let images = try await ImageManager(config: config).prune(all: all, inUse: inUse)
+ ImagePrune.report(images.removed)
+
+ // The builder's cache cannot be pruned in part (see `BuildCache`), so it goes
+ // whole in both modes; a build only loses time to it, never data.
+ let cache = try await BuildCache.prune()
+ if cache > 0 { print("Deleted build cache\n") }
+
+ print("Total reclaimed space: \(ImagePrune.bytes(images.reclaimed + cache))")
+ }
+
+ private static func report(_ title: String, _ names: [String]) {
+ guard !names.isEmpty else { return }
+ print(title)
+ for name in names { print(name) }
+ print("")
}
}
diff --git a/Sources/Mocker/MockerCLI.swift b/Sources/Mocker/MockerCLI.swift
index a9a93c8..990baa3 100644
--- a/Sources/Mocker/MockerCLI.swift
+++ b/Sources/Mocker/MockerCLI.swift
@@ -47,6 +47,7 @@ struct MockerCLI: AsyncParsableCommand {
Import.self,
Search.self,
ContainerCommand.self,
+ BuilderCommand.self,
ImageCommand.self,
ManifestCommand.self,
NetworkCommand.self,
diff --git a/Sources/MockerKit/Image/BuildCache.swift b/Sources/MockerKit/Image/BuildCache.swift
new file mode 100644
index 0000000..f454214
--- /dev/null
+++ b/Sources/MockerKit/Image/BuildCache.swift
@@ -0,0 +1,28 @@
+import Foundation
+
+/// BuildKit's cache lives on the builder VM's disk, and `container` cannot prune part of
+/// it. Docker's "remove build cache" therefore maps to deleting the builder; the next
+/// `container build` starts a fresh one.
+public enum BuildCache {
+ /// Delete the builder and return the disk space its root filesystem occupied.
+ public static func prune(runner: ProcessRunning = RealProcessRunner()) async throws -> UInt64 {
+ let bytes = allocatedSize()
+ let (output, status) = try await runner.run(
+ executable: CLIResolver.resolve(), arguments: ["builder", "delete", "--force"]
+ )
+ // No builder means no cache: nothing to do, not a failure.
+ guard status == 0 || output.localizedCaseInsensitiveContains("not found") else {
+ throw MockerError.operationFailed(
+ NetworkManager.errorMessage(from: output, fallback: "failed to delete the builder"))
+ }
+ return bytes
+ }
+
+ /// Bytes the builder's root filesystem image occupies on disk (it is a sparse file).
+ static func allocatedSize() -> UInt64 {
+ guard let root = MockerConfig.appleContainerStorePath() else { return 0 }
+ let disk = root.appendingPathComponent("containers/buildkit/rootfs.ext4")
+ let values = try? disk.resourceValues(forKeys: [.totalFileAllocatedSizeKey])
+ return UInt64(values?.totalFileAllocatedSize ?? 0)
+ }
+}
diff --git a/Sources/MockerKit/Image/ImageManager.swift b/Sources/MockerKit/Image/ImageManager.swift
index 8e02e49..da688c5 100644
--- a/Sources/MockerKit/Image/ImageManager.swift
+++ b/Sources/MockerKit/Image/ImageManager.swift
@@ -126,6 +126,59 @@ public actor ImageManager {
return info
}
+ // MARK: - Prune
+
+ /// Images the runtime itself depends on; never the user's to prune.
+ static let runtimeImagePrefixes = ["ghcr.io/apple/containerization/", "ghcr.io/apple/container-builder-shim/"]
+
+ /// Docker's "dangling" is an image with no name. The store names every image, and an
+ /// untagged `mocker build` gets a UUID, so that is what dangling looks like here.
+ static func isDangling(_ image: ImageInfo) -> Bool {
+ var name = image.repository
+ if name.hasPrefix("docker.io/library/") { name.removeFirst("docker.io/library/".count) }
+ return image.tag == "latest" && UUID(uuidString: name) != nil
+ }
+
+ /// What `prune` removes: dangling images, or with `all` every image no container uses.
+ /// Pure, so the selection can be tested without a store.
+ /// - Parameter inUse: image references the way containers spell them (name, name:tag or ID).
+ static func pruneCandidates(_ images: [ImageInfo], all: Bool, inUse: [String]) -> [ImageInfo] {
+ images.filter { image in
+ if runtimeImagePrefixes.contains(where: { image.repository.hasPrefix($0) }) { return false }
+ guard all else { return isDangling(image) }
+ return !inUse.contains { matches(image, reference: $0) }
+ }
+ }
+
+ /// Whether `reference` — `alpine`, `alpine:3.20`, `docker.io/library/alpine:3.20` or an
+ /// ID prefix — names `image`.
+ static func matches(_ image: ImageInfo, reference: String) -> Bool {
+ if looksLikeDigest(reference), digestBody(image.id).hasPrefix(digestBody(reference)) { return true }
+ guard let ref = try? ImageReference.parse(reference) else { return false }
+ return image.tag == ref.tag
+ && (image.repository == ref.fullRepository || image.repository.hasSuffix("/\(ref.repository)"))
+ }
+
+ /// Remove dangling images, or with `all` every image not in `inUse`, then let the
+ /// runtime drop the blobs nothing references any more.
+ /// - Returns: the images removed and the bytes their digests freed (a digest another
+ /// name still points at frees nothing).
+ public func prune(all: Bool, inUse: [String]) async throws -> (removed: [ImageInfo], reclaimed: UInt64) {
+ var removed: [ImageInfo] = []
+ for image in Self.pruneCandidates(try await list(), all: all, inUse: inUse) {
+ removed.append(try await remove(image.reference))
+ }
+ // Orphaned blobs are garbage-collected by the CLI; the store API does not expose that.
+ _ = try await RealProcessRunner().run(executable: Self.containerCLI, arguments: ["image", "prune"])
+
+ let remaining = Set(try await list(enrich: false).map(\.id))
+ var counted: Set<String> = []
+ let reclaimed = removed
+ .filter { !remaining.contains($0.id) && counted.insert($0.id).inserted }
+ .reduce(UInt64(0)) { $0 + ($1.size ?? 0) }
+ return (removed, reclaimed)
+ }
+
// MARK: - Tag
/// Tag an image with a new reference.
diff --git a/Sources/MockerKit/Network/NetworkManager.swift b/Sources/MockerKit/Network/NetworkManager.swift
index f1bee18..307a31d 100644
--- a/Sources/MockerKit/Network/NetworkManager.swift
+++ b/Sources/MockerKit/Network/NetworkManager.swift
@@ -139,6 +139,21 @@ public actor NetworkManager {
/// Networks the runtime owns and that must never be pruned, identified the way the
/// runtime itself marks them rather than by guessing at names.
+ /// Remove every network no container uses. The runtime's built-in network stays:
+ /// pruning it would break every container that does not name a network.
+ /// - Returns: the names actually removed. A network with containers attached is
+ /// refused by the runtime and skipped, so it is not reported as deleted.
+ public func prune() async throws -> [String] {
+ var removed: [String] = []
+ for network in try await list() where !Self.isBuiltIn(network)
+ && !["bridge", "host", "none"].contains(network.name) {
+ if (try? await remove(network.name)) != nil {
+ removed.append(network.name)
+ }
+ }
+ return removed
+ }
+
public static func isBuiltIn(_ network: NetworkInfo) -> Bool {
network.labels["com.apple.container.resource.role"] == "builtin" || network.name == "default"
}
diff --git a/Tests/MockerKitTests/ImageManagerPruneTests.swift b/Tests/MockerKitTests/ImageManagerPruneTests.swift
new file mode 100644
index 0000000..0632635
--- /dev/null
+++ b/Tests/MockerKitTests/ImageManagerPruneTests.swift
@@ -0,0 +1,37 @@
+import Testing
+@testable import MockerKit
+
+/// `ImageManager.pruneCandidates` — the pure selection behind `image prune` and
+/// `system prune`. Docker semantics: dangling = unnamed (here: a UUID-named untagged
+/// build), `--all` = every image no container uses; the runtime's own images never.
+@Suite("ImageManager prune candidates")
+struct ImageManagerPruneTests {
+
+ private let untaggedBuild = ImageInfo(
+ id: "sha256:aaa1", repository: "docker.io/library/0be91dde-ab34-4ed8-8b26-d4fb1ef97666", tag: "latest")
+ private let alpine = ImageInfo(id: "sha256:bbb2", repository: "docker.io/library/alpine", tag: "3.20")
+ private let app = ImageInfo(id: "sha256:ccc3", repository: "ghcr.io/acme/app", tag: "1.0")
+ private let vminit = ImageInfo(id: "sha256:ddd4", repository: "ghcr.io/apple/containerization/vminit", tag: "0.47.0")
+ private let shim = ImageInfo(id: "sha256:eee5", repository: "ghcr.io/apple/container-builder-shim/builder", tag: "0.13.2")
+ private var all: [ImageInfo] { [untaggedBuild, alpine, app, vminit, shim] }
+
+ @Test("without --all only untagged (UUID-named) builds are dangling")
+ func danglingOnly() {
+ #expect(ImageManager.pruneCandidates(all, all: false, inUse: []).map(\.id) == ["sha256:aaa1"])
+ }
+
+ @Test("--all removes every image no container uses, however the container spells it")
+ func allUnused() {
+ #expect(ImageManager.pruneCandidates(all, all: true, inUse: []).map(\.id) == ["sha256:aaa1", "sha256:bbb2", "sha256:ccc3"])
+ #expect(ImageManager.pruneCandidates(all, all: true, inUse: ["alpine:3.20", "ghcr.io/acme/app:1.0"]).map(\.id) == ["sha256:aaa1"])
+ // By ID prefix, and by the fully-qualified name a pull stores.
+ #expect(ImageManager.pruneCandidates(all, all: true, inUse: ["bbb2", "docker.io/library/alpine:3.20"]).map(\.id) == ["sha256:aaa1", "sha256:ccc3"])
+ }
+
+ @Test("the runtime's own images are never candidates")
+ func runtimeImagesKept() {
+ let ids = ImageManager.pruneCandidates(all, all: true, inUse: []).map(\.id)
+ #expect(!ids.contains("sha256:ddd4"))
+ #expect(!ids.contains("sha256:eee5"))
+ }
+}
Shipped in 0.9.8 (ref #109), checked with the Homebrew build on container 1.5.0. Thanks @BluPix!