Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ integration: init-block
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIExecCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLICreateCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIRunCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIPruneCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIStatsCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIImagesCommand || exit_code=1 ; \
$(SWIFT) test -c $(BUILD_CONFIGURATION) $(SWIFT_CONFIGURATION) --filter TestCLIRunBase || exit_code=1 ; \
Expand Down
14 changes: 14 additions & 0 deletions Sources/ContainerClient/Core/ClientContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,20 @@ extension ClientContainer {
}
}

public static func prune() async throws -> ([String], Int64) {
let client = Self.newXPCClient()
let request = XPCMessage(route: .containerPrune)
let reply = try await client.send(request)

guard let responseData = reply.dataNoCopy(key: .containers) else {
return ([], 0)
}

let containerIds = try JSONDecoder().decode([String].self, from: responseData)
let size = reply.int64(key: .imageSize)
return (containerIds, size)
}

/// Create a new process inside a running container. The process is in a
/// created state and must still be started.
public func createProcess(
Expand Down
1 change: 1 addition & 0 deletions Sources/ContainerClient/Core/XPC+.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ public enum XPCRoute: String {
case containerStartProcess
case containerWait
case containerDelete
case containerPrune
case containerStop
case containerDial
case containerResize
Expand Down
1 change: 1 addition & 0 deletions Sources/ContainerCommands/Application.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public struct Application: AsyncParsableCommand {
ContainerStart.self,
ContainerStats.self,
ContainerStop.self,
ContainerPrune.self,
]
),
CommandGroup(
Expand Down
41 changes: 41 additions & 0 deletions Sources/ContainerCommands/Container/ContainerPrune.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import ArgumentParser
import ContainerClient
import ContainerizationError
import Foundation

extension Application {
public struct ContainerPrune: AsyncParsableCommand {
public init() {}

public static let configuration = CommandConfiguration(
commandName: "prune",
abstract: "Remove all stopped containers"
)
public func run() async throws {
let (containerIds, size) = try await ClientContainer.prune()
let formatter = ByteCountFormatter()
let freed = formatter.string(fromByteCount: size)

for name in containerIds {
print(name)
}
print("Reclaimed \(freed) in disk space")
}
}
}
1 change: 1 addition & 0 deletions Sources/Helpers/APIServer/APIServer+Start.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,7 @@ extension APIServer {
routes[XPCRoute.containerWait] = harness.wait
routes[XPCRoute.containerKill] = harness.kill
routes[XPCRoute.containerStats] = harness.stats
routes[XPCRoute.containerPrune] = harness.prune

return service
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,17 @@ public struct ContainersHarness: Sendable {
return message.reply()
}

@Sendable
public func prune(_ message: XPCMessage) async throws -> XPCMessage {
let (containerIds, size) = try await service.prune()
let data = try JSONEncoder().encode(containerIds)

let reply = message.reply()
reply.set(key: .containers, value: data)
reply.set(key: .imageSize, value: Int64(size))
return reply
}

@Sendable
public func logs(_ message: XPCMessage) async throws -> XPCMessage {
let id = message.string(key: .id)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,34 @@ public actor ContainersService {
}
}

public func prune() async throws -> ([String], UInt64) {
self.log.debug("\(#function)")
let stoppedContainers = self.containers.filter { $0.value.snapshot.status == .stopped }

var pruned = [String]()
var totalSize: UInt64 = 0

for (id, _) in stoppedContainers {
do {
let containerPath = self.containerRoot.appendingPathComponent(id).path
let size = Self.calculateDirectorySize(at: containerPath)

try await self.lock.withLock { context in
try await self.cleanup(id: id, context: context)
}

pruned.append(id)
totalSize += size

self.log.info("Pruned container", metadata: ["id": "\(id)", "size": "\(size)"])
} catch {
self.log.error("Failed to prune container \(id): \(error)")
}
}

return (pruned, totalSize)
}

private func handleContainerExit(id: String, code: ExitStatus? = nil) async throws {
try await self.lock.withLock { [self] context in
try await handleContainerExit(id: id, code: code, context: context)
Expand Down
87 changes: 87 additions & 0 deletions Tests/CLITests/Subcommands/Containers/TestCLIPrune.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//===----------------------------------------------------------------------===//
// Copyright © 2025 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//

import Foundation
import Testing

@Suite(.serialized)
class TestCLIPruneCommand: CLITest {
private func getTestName() -> String {
Test.current!.name.trimmingCharacters(in: ["(", ")"]).lowercased()
}

@Test func testContainerPruneNoContainers() throws {
let (_, output, error, status) = try run(arguments: ["prune"])
if status != 0 {
throw CLIError.executionFailed("container prune failed: \(error)")
}

#expect(output.contains("Reclaimed Zero KB in disk space"), "should show no containers message")
}

@Test func testContainerPruneStoppedContainers() throws {
let testName = getTestName()
let npcName = "\(testName)_wont_be_pruned"
let pc0Name = "\(testName)_pruned_0"
let pc1Name = "\(testName)_pruned_1"

try doLongRun(name: npcName, containerArgs: ["sleep", "3600"], autoRemove: true)
try doLongRun(name: pc0Name, containerArgs: ["sleep", "3600"], autoRemove: false)
try doLongRun(name: pc1Name, containerArgs: ["sleep", "3600"], autoRemove: false)
defer {
try? doStop(name: npcName)
try? doStop(name: pc0Name)
try? doStop(name: pc1Name)
try? doRemove(name: npcName)
try? doRemove(name: pc0Name)
try? doRemove(name: pc1Name)
}
try waitForContainerRunning(npcName)
try waitForContainerRunning(pc0Name)
try waitForContainerRunning(pc1Name)

try doStop(name: pc0Name)
try doStop(name: pc1Name)

let pc0Id = try getContainerId(pc0Name)
let pc1Id = try getContainerId(pc1Name)

// Poll status until both containers are stopped, with interval checks and a timeout to avoid infinite loop
let start = Date()
let timeout: TimeInterval = 30 // seconds
while true {
let s0 = try getContainerStatus(pc0Name)
let s1 = try getContainerStatus(pc1Name)
if s0 == "stopped" && s1 == "stopped" { break }
if Date().timeIntervalSince(start) > timeout {
throw CLIError.executionFailed("Timeout waiting for containers to stop: pc0=\(s0), pc1=\(s1)")
}
Thread.sleep(forTimeInterval: 0.2)
}

let (_, output, error, status) = try run(arguments: ["prune"])

if status != 0 {
throw CLIError.executionFailed("container prune failed: \(error)")
}

#expect(output.contains(pc0Id) && output.contains(pc1Id), "should show the stopped containers id")
#expect(!output.contains("Reclaimed Zero KB in disk space"), "reclaimed spaces should not Zero KB")

let checkStatus = try getContainerStatus(npcName)
#expect(checkStatus == "running", "not pruned container should still be running")
}
}
4 changes: 4 additions & 0 deletions Tests/CLITests/Utilities/CLITest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,10 @@ class CLITest {
try inspectContainer(name).status
}

func getContainerId(_ name: String) throws -> String {
try inspectContainer(name).configuration.id
}

func inspectContainer(_ name: String) throws -> inspectOutput {
let response = try run(arguments: [
"inspect",
Expand Down
14 changes: 14 additions & 0 deletions docs/command-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,20 @@ container stats --no-stream web
container stats --format json --no-stream web
```

### `container prune`

Removes stopped containers to reclaim disk space. The command outputs the amount of space freed after deletion.

**Usage**

```bash
container prune [--debug]
```

**Options**

No options.

## Image Management

### `container image list (ls)`
Expand Down