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
61 changes: 53 additions & 8 deletions Sources/Containerization/LinuxContainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ public final class LinuxContainer: Container, Sendable {
/// The container has run and fully stopped.
case stopped
/// An error occurred during the lifetime of this class.
case errored(Swift.Error)
case errored(Swift.Error, cleanup: FailedCreateCleanup? = nil)
/// The container is paused.
case paused(PausedState)

Expand All @@ -204,6 +204,35 @@ public final class LinuxContainer: Container, Sendable {
var fileMountContext: FileMountContext
}

struct FailedCreateCleanup: Sendable {
var vm: (any VirtualMachineInstance)?
var relayManager: UnixSocketRelayManager?

mutating func stop() async throws {
var firstError: Error?
// Terminate before relay cleanup so a relay failure cannot skip VM stop.
if let vm {
do {
try await vm.stop()
self.vm = nil
} catch {
firstError = error
}
}
if let relayManager {
do {
try await relayManager.stopAll()
self.relayManager = nil
} catch {
firstError = firstError ?? error
}
}
if let firstError {
throw firstError
}
}
}

struct StartedState: Sendable {
let vm: any VirtualMachineInstance
let process: LinuxProcess
Expand Down Expand Up @@ -248,7 +277,7 @@ public final class LinuxContainer: Container, Sendable {
switch self {
case .created(let state):
return state
case .errored(let err):
case .errored(let err, _):
throw err
default:
throw ContainerizationError(
Expand All @@ -262,7 +291,7 @@ public final class LinuxContainer: Container, Sendable {
switch self {
case .started(let state):
return state
case .errored(let err):
case .errored(let err, _):
throw err
default:
throw ContainerizationError(
Expand All @@ -276,7 +305,7 @@ public final class LinuxContainer: Container, Sendable {
switch self {
case .paused(let state):
return state
case .errored(let err):
case .errored(let err, _):
throw err
default:
throw ContainerizationError(
Expand All @@ -290,7 +319,7 @@ public final class LinuxContainer: Container, Sendable {
switch self {
case .initialized, .stopped:
break
case .errored(let err):
case .errored(let err, _):
throw err
default:
throw ContainerizationError(
Expand All @@ -312,7 +341,7 @@ public final class LinuxContainer: Container, Sendable {
return state.vm
case .paused(let state):
return state.vm
case .errored(let err):
case .errored(let err, _):
throw err
default:
throw ContainerizationError(
Expand Down Expand Up @@ -910,9 +939,14 @@ extension LinuxContainer {
}
state = .created(.init(vm: vm, relayManager: relayManager, fileMountContext: fileMountContextHolder.withLock { $0 }))
} catch {
try? await relayManager.stopAll()
try? await vm.stop()
state.setErrored(error: error)
var cleanup = State.FailedCreateCleanup(vm: vm, relayManager: relayManager)
do {
try await cleanup.stop()
} catch let cleanupError {
state = .errored(error, cleanup: cleanup)
self.logger?.error("failed to clean up container creation: \(cleanupError)")
}
throw error
}
}
Expand Down Expand Up @@ -1016,6 +1050,17 @@ extension LinuxContainer {
return
}

if case .errored(let error, var cleanup?) = state {
do {
try await cleanup.stop()
state = .stopped
} catch let cleanupError {
state = .errored(error, cleanup: cleanup)
throw cleanupError
}
return
}

let vm: any VirtualMachineInstance
let relayManager: UnixSocketRelayManager

Expand Down
5 changes: 3 additions & 2 deletions Sources/Containerization/UnixSocketRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,13 +64,13 @@ extension UnixSocketRelay {

func stop() throws {
try state.withLock {
guard let t = $0.t else {
guard $0.t != nil || $0.listener != nil else {
throw ContainerizationError(
.invalidState,
message: "failed to stop socket relay: relay has not been started"
)
}
t.cancel()
$0.t?.cancel()
$0.t = nil
for (_, relay) in $0.activeRelays {
relay.stop()
Expand All @@ -84,6 +84,7 @@ extension UnixSocketRelay {
try? FileManager.default.removeItem(at: self.configuration.destination)
case .into:
try $0.listener?.finish()
$0.listener = nil
}
}
}
Expand Down
13 changes: 11 additions & 2 deletions Sources/Containerization/UnixSocketRelayManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,17 @@ extension UnixSocketRelayManager {
}

func stopAll() async throws {
for (_, relay) in relays {
try relay.stop()
var firstError: Error?
for (id, relay) in relays {
do {
try relay.stop()
relays.removeValue(forKey: id)
} catch {
firstError = firstError ?? error
}
}
if let firstError {
throw firstError
}
}
}
18 changes: 6 additions & 12 deletions Sources/Containerization/VsockListener.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,23 +42,17 @@ public final class VsockListener: NSObject, Sendable, AsyncSequence {
self.finished = Mutex(false)
}

/// Idempotent: calling more than once is a no-op. setupIO and the
/// caller-side defer can both call finish without double-closing the
/// listening fd (a double-close would target whatever fd was reallocated
/// in between, hanging the next operation that touched it).
/// Listener removal is serialized and is not repeated after success.
/// Failed removal can be retried.
public func finish() throws {
let alreadyFinished = self.finished.withLock { state -> Bool in
try self.finished.withLock { state in
if state {
return true
return
}
self.cont.finish()
try self.stopListening(self.port)
state = true
return false
}
if alreadyFinished {
return
}
self.cont.finish()
try self.stopListening(self.port)
}

/// Push an accepted connection into the listener's stream. Used by
Expand Down
98 changes: 94 additions & 4 deletions Tests/ContainerizationTests/LinuxContainerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,13 @@ struct LinuxContainerTests {
#expect(explicit.memoryInBytes == 512.mib())
}

/// A `VirtualMachineManager` that records the configuration it is handed and
/// then refuses to boot. `LinuxContainer.create()` builds the `VMConfiguration`
/// and passes it straight to `vmm.create`, so this captures the VM sizing
/// without needing a real VM.
private final class StubVMM: VirtualMachineManager {
private let captured = Mutex<VMConfiguration?>(nil)
private let instance: (any VirtualMachineInstance)?

init(instance: (any VirtualMachineInstance)? = nil) {
self.instance = instance
}

/// The configuration `LinuxContainer.create()` asked for, if it got that far.
var capturedConfiguration: VMConfiguration? {
Expand All @@ -212,10 +213,99 @@ struct LinuxContainerTests {

func create(config: some VMCreationConfig) async throws -> any VirtualMachineInstance {
captured.withLock { $0 = config.configuration }
if let instance {
return instance
}
throw ContainerizationError(.unsupported, message: "stub")
}
}

private enum LifecycleError: Error {
case startup
case stop
}

private final class FailingVirtualMachine: VirtualMachineInstance {
typealias Agent = Vminitd

private struct Status {
var running = false
var stopFailures = 2
var stopCalls = 0
}

private let status = Mutex(Status())

var state: VirtualMachineInstanceState {
status.withLock { $0.running ? .running : .stopped }
}

var mounts: [String: [AttachedFilesystem]] {
[:]
}

var stopCalls: Int {
status.withLock { $0.stopCalls }
}

func start() async throws {
status.withLock { $0.running = true }
throw LifecycleError.startup
}

func stop() async throws {
try status.withLock {
$0.stopCalls += 1
if $0.stopFailures > 0 {
$0.stopFailures -= 1
throw LifecycleError.stop
}
$0.running = false
}
}

func dialAgent() async throws -> Vminitd {
throw ContainerizationError(.unsupported, message: "dialAgent")
}

func dial(_ port: UInt32) async throws -> FileHandle {
throw ContainerizationError(.unsupported, message: "dial")
}

func listen(_ port: UInt32) throws -> VsockListener {
throw ContainerizationError(.unsupported, message: "listen")
}
}

@Test func stopRetriesCleanupAfterFailedCreation() async throws {
let vm = FailingVirtualMachine()
let container = try LinuxContainer("failed-creation", rootfs: Self.testRootfs, vmm: StubVMM(instance: vm)) { config in
config.process.arguments = ["/bin/true"]
}

await #expect(throws: LifecycleError.startup) {
try await container.create()
}
#expect(vm.state == .running)
#expect(vm.stopCalls == 1)

await #expect(throws: LifecycleError.stop) {
try await container.stop()
}
#expect(vm.state == .running)
#expect(vm.stopCalls == 2)

await #expect(throws: LifecycleError.startup) {
try await container.create()
}
try await container.stop()
#expect(vm.state == .stopped)
#expect(vm.stopCalls == 3)

try await container.stop()
#expect(vm.stopCalls == 3)
}

@Test func runtimeSpecUsesContainerLimitsNotVMSize() async throws {
// The OCI cgroup limit comes from the container configuration, the VM size from `vm`.
let vmm = StubVMM()
Expand Down
45 changes: 41 additions & 4 deletions Tests/ContainerizationTests/UnixSocketRelayTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,32 @@ import Musl
#endif

struct UnixSocketRelayTests {
@Test func stopAllRetriesOnlyUnfinishedRelays() async throws {
let allowStop = Mutex(false)
let stoppedPorts = Mutex<[UInt32]>([])
let vm = RelayVirtualMachine { port in
if port == 1026 && !allowStop.withLock({ $0 }) {
throw POSIXError(.EIO)
}
stoppedPorts.withLock { $0.append(port) }
}
let manager = UnixSocketRelayManager(vm: vm)
let path = FileManager.default.temporaryDirectory.appendingPathComponent("relay.sock")
for port: UInt32 in [1025, 1026] {
try await manager.start(port: port, socket: .init(source: path, destination: path, direction: .into))
}

await #expect(throws: POSIXError(.EIO)) {
try await manager.stopAll()
}
#expect(stoppedPorts.withLock { $0 } == [1025])

allowStop.withLock { $0 = true }
try await manager.stopAll()
try await manager.stopAll()
#expect(stoppedPorts.withLock { $0.sorted() } == [1025, 1026])
}

private func socketPair() throws -> (connection: FileHandle, peer: FileHandle) {
var fds: [Int32] = [-1, -1]
#if canImport(Glibc)
Expand Down Expand Up @@ -72,7 +98,7 @@ struct UnixSocketRelayTests {

@Test(.timeLimit(.minutes(1)))
func refusedConnectionsCloseAndListenerRecovers() async throws {
let path = URL(filePath: "/tmp/relay-\(UUID().uuidString).sock")
let path = FileManager.default.temporaryDirectory.appendingPathComponent("relay-\(UUID().uuidString).sock")
defer { try? FileManager.default.removeItem(at: path) }
let type = try UnixType(path: path.path, unlinkExisting: true)
let unavailable = try Socket(type: type)
Expand Down Expand Up @@ -121,7 +147,7 @@ struct UnixSocketRelayTests {

@Test(.timeLimit(.minutes(1)))
func refusedDialsCloseAndListenerRecovers() async throws {
let path = URL(filePath: "/tmp/relay-\(UUID().uuidString).sock")
let path = FileManager.default.temporaryDirectory.appendingPathComponent("relay-\(UUID().uuidString).sock")
defer { try? FileManager.default.removeItem(at: path) }
let type = try UnixType(path: path.path)
let vm = RelayVirtualMachine()
Expand Down Expand Up @@ -159,12 +185,23 @@ struct UnixSocketRelayTests {
private final class RelayVirtualMachine: VirtualMachineInstance {
typealias Agent = Vminitd

let listener = VsockListener(port: 1025) { _ in }
let listener: VsockListener
private let stopListening: @Sendable (UInt32) throws -> Void
let dialConnection = Mutex<FileHandle?>(nil)
var state: VirtualMachineInstanceState { .running }
var mounts: [String: [AttachedFilesystem]] { [:] }

func listen(_ port: UInt32) throws -> VsockListener { listener }
init(stopListening: @escaping @Sendable (UInt32) throws -> Void = { _ in }) {
self.stopListening = stopListening
self.listener = VsockListener(port: 1025, stopListen: stopListening)
}

func listen(_ port: UInt32) throws -> VsockListener {
if port == listener.port {
return listener
}
return VsockListener(port: port, stopListen: stopListening)
}
func dialAgent() async throws -> Vminitd {
throw ContainerizationError(.unsupported, message: "dialAgent")
}
Expand Down