diff --git a/AGENTS.md b/AGENTS.md index 2249e11..6130c16 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,15 +36,16 @@ Calls flow in one direction: ``` SwiftUI / AppKit views → Managers (ContainerSystem, @MainActor, public) - → Services (ContainerSystem, actors, internal) - → Containerization + → ContainerRuntime.get…Service() + → Services (ContainerSystem, actors, internal) + → Containerization ``` - `ContainerRuntime` (`ContainerRuntime.shared`) owns the services and the runtime's shared state: system status, setup progress and reports. It also installs the prerequisites (kernel, init image) on first start. -- Managers are thin handles over the runtime, one per domain. `ImageManager()` uses the shared runtime; tests pass a `MockContainerRuntime` through `init(testRuntime:)`. -- Services are the engine: internal actors that hold the state of containers, images and kernels. Only managers call them. +- Managers are thin handles over the runtime, one per domain. `ImageManager()` uses the shared runtime; tests pass a `MockContainerRuntime` through `init(testRuntime:)`. A manager can use any service, but never another manager. +- Services are the engine: internal actors that hold the state of containers, images, kernels and reports. Only the runtime creates them, when the system starts, and lets go of them when it stops. Everything else reaches them through the runtime's `get…Service()` accessors: managers and `Build/`. Nothing works while the system is stopped, by design. - Progress is Foundation's `Progress`. A method that reports progress takes `progress: Progress? = nil`, sets `totalUnitCount` to its own steps and runs each with `progress.performStep("…") { step in … }` (`Progress/Progress+Steps.swift`). Callers compose operations by weighting steps with `pendingUnitCount`. -- Failed work is recorded by `ReportManager` into `ReportStore`: a plist manifest plus one gzipped body per report. +- Failed work is recorded by `ReportManager` through `ReportsService` into `ReportStore`: a plist manifest plus one gzipped body per report. Managers that delete items also delete their reports through `ReportsService`. - Errors are thrown as they are. Views turn them into an `ErrorAlert`; the framework and app models never build alerts. ## ContainerSystem layout @@ -52,7 +53,7 @@ SwiftUI / AppKit views Role first, with domains inside each role: - `Managers/`: `ContainerManager`, `ImageManager`, `VolumeManager`, `NetworkManager`, `SystemManager`, `ReportManager`. -- `Services/`: `ContainersService`, `ImagesService`, `KernelService`. +- `Runtime/`: `ContainerRuntime` and its extensions, with `Services/` inside it (`ContainersService`, `ImagesService`, `KernelService`, `ReportsService`), since the runtime owns the services. - `Container/`, `Image/`, `Network/`, `Volume/`: value types for each domain (`ContainerConfiguration`, `ContainerSnapshot`, `ImageSummary`, `VolumeSummary`, …). - `Build/`: the BuildKit client. `Builder/` holds the gRPC client and the builder container's controller; `BuildPipeline/` handles the stream, split by concern (`+ImageResolver`, `+ContentStore`, `+FSSync`, `+Export`, `+Stdio`). - `Persistence/`, `Plugin/`, `Log/`, `Progress/`, `Reports/`, `Common/`: one folder per infrastructure concern. @@ -63,8 +64,8 @@ Layer first, like Apple's SwiftUI samples: - `ContainersApp.swift`: scenes, window IDs and the objects put in the environment. - `Models/`: value types, grouped by feature to mirror `Views/` (`Containers/`, `Images/`, `Volumes/`, `Reports/`, `Dashboard/`, `Shared/`). Models never fetch or do work. -- `ViewModels/`: `@Observable` objects a single view creates and owns with `@State` (`RegistryLookup`). -- `Utilities/`: `@Observable` objects the app owns and shares through the environment (`ActivityCenter`, `SystemActions`), plus support types (`ProgressObserver`, `WindowResizer`). +- `ViewModels/`: `@Observable` objects that hold state and actions for views: `RegistryLookup`, owned by the pull sheet with `@State`, and `SystemActions`, created by the app and shared by the menu bar and the status bar. +- `Utilities/`: app-wide objects not tied to a screen (`ActivityCenter`), plus support types (`ProgressObserver`, `WindowResizer`). - `Controllers/`: AppKit controllers only, such as the `NSToolbarDelegate` objects. Their `NSViewRepresentable` binders live in `Views/`. - `Views//`: one folder per screen. `Views/Shared/` holds complete units that appear once on a screen (`TableView`, `DetailView`, `CreateView`, `ScopeBar`). `Views/Components/` holds small reusable elements that can repeat on a screen (`BarToggle`, `SearchToken`, form rows). - `Extensions/`: one `Type+Topic.swift` per extension. diff --git a/ContainerSystem/Managers/ContainerManager.swift b/ContainerSystem/Managers/ContainerManager.swift index 46df34c..5f6cde3 100644 --- a/ContainerSystem/Managers/ContainerManager.swift +++ b/ContainerSystem/Managers/ContainerManager.swift @@ -12,21 +12,26 @@ import ContainerizationOS import Foundation import Logging -/// Manages container operations. -/// Create instances via public init() - automatically references shared runtime. +/// A manager that creates, runs, stops and deletes containers. +/// +/// Methods that work on one container take its `id`. Containers the container system runs for itself, +/// such as the builder, are left out of ``list()``. @Observable @MainActor public final class ContainerManager { - /// Internal runtime reference (hidden from UI) let runtime: ContainerRuntime private let logger: Logger private static let internalContainerIDs: Set = ["buildkit"] + /// The time a container last changed state, such as when it started or stopped. + /// + /// Observe this property to refresh a list of containers when one of them changes. public var lastContainerChange: Date { runtime.lastContainerStateChange } + /// Creates a manager for the shared container system. public init() { self.runtime = ContainerRuntime.shared var logger = Logger(label: "app.containers.manager.container") @@ -35,7 +40,7 @@ public final class ContainerManager { } #if DEBUG - /// Internal initializer for testing - allows injection of test runtime + /// Creates a manager for the given runtime, so tests can use a runtime of their own. init(testRuntime: ContainerRuntime) { self.runtime = testRuntime var logger = Logger(label: "app.containers.manager.container.test") @@ -46,6 +51,19 @@ public final class ContainerManager { // MARK: - Public API + /// Creates a container from an image, pulling and unpacking the image first if needed. + /// + /// - Parameters: + /// - imageReference: The image to create the container from. + /// - imagesDir: The folder that holds the container system's images. + /// - arguments: Arguments to pass to the container's process, after its entry point. + /// - process: How to run the container's process, such as its environment and working directory. + /// - configuration: The container's resources, mounts, ports and other settings. + /// - options: Options for managing the container, such as its name and whether to delete it when it stops. + /// - registryScheme: The scheme to reach the image's registry with. + /// - progress: A progress that follows the work, step by step, or `nil` to not follow it. + /// - Returns: The container's ID. + /// - Throws: An error if a container with the same ID exists, or the container can't be created. @discardableResult public func create( imageReference: String, @@ -59,15 +77,17 @@ public final class ContainerManager { ) async throws -> String { let service = try await runtime.getContainersService() let containerID = try Self.createContainerID(name: options.name) + logger.info("Creating container", metadata: ["id": "\(containerID)", "image": "\(imageReference)"]) + let existingContainers = await service.list() + guard !existingContainers.contains(where: { $0.configuration.id == containerID }) else { logger.error("Container \(containerID) already exists") - throw ContainerizationError(.exists, message: "container already exists: \(containerID)") } @@ -110,8 +130,14 @@ public final class ContainerManager { return configuration.id } - /// Starts a container, returning its exit code when attached to it and - /// `nil` when detached from it. + /// Starts a container. + /// + /// - Parameters: + /// - id: The container's ID. + /// - detach: Whether to return as soon as the container starts, rather than wait for it to exit. + /// - progress: A progress that follows the work, step by step, or `nil` to not follow it. + /// - Returns: The container's exit code, or `nil` if `detach` is `true`. + /// - Throws: An error if the container can't start. A container that fails to start is stopped. @discardableResult public func run(id: String, detach: Bool = true, progress: Progress? = nil) async throws -> Int32? { logger.info("Starting container", metadata: ["id": "\(id)"]) @@ -140,6 +166,7 @@ public final class ContainerManager { return try await service.wait(id: id) } + /// Returns the memory and CPU time each running container uses, or an empty array if the system isn't running. public func resourceUsage() async -> [ContainerResourceUsage] { guard let service = try? await runtime.getContainersService() else { return [] @@ -148,6 +175,7 @@ public final class ContainerManager { return await service.resourceUsage() } + /// Returns every container, except the ones the container system uses itself, such as the builder. public func list() async throws -> [ContainerSnapshot] { let service = try await runtime.getContainersService() @@ -156,6 +184,11 @@ public final class ContainerManager { } } + /// Returns a container. + /// + /// - Parameter id: The container's ID. + /// - Returns: The container. + /// - Throws: An error if there's no container with that ID. public func get(id: String) async throws -> ContainerSnapshot { let service = try await runtime.getContainersService() @@ -170,11 +203,24 @@ public final class ContainerManager { return snapshot } + /// Runs a command in a running container and returns its output. + /// + /// - Parameters: + /// - id: The container's ID. + /// - arguments: The command and its arguments. + /// - Returns: What the command writes to its standard output. + /// - Throws: An error if the container isn't running or the command can't run. public func exec(id: String, arguments: [String]) async throws -> String { let service = try await runtime.getContainersService() return try await service.exec(id: id, arguments: arguments) } + /// Stops containers, giving each one's process time to exit before forcing it. + /// + /// - Parameters: + /// - ids: The IDs of the containers to stop. + /// - timeoutSeconds: How long to wait for each process to exit after sending it `SIGTERM`. + /// - Throws: An error that lists each container that couldn't be stopped. public func stop(ids: [String], timeoutSeconds: Int32) async throws { let service = try await runtime.getContainersService() @@ -199,16 +245,28 @@ public final class ContainerManager { } } + /// Stops containers, giving each one's process time to exit before forcing it. + /// + /// - Parameters: + /// - snapshots: The containers to stop. + /// - timeoutSeconds: How long to wait for each process to exit after sending it `SIGTERM`. + /// - Throws: An error that lists each container that couldn't be stopped. public func stop(snapshots: [ContainerSnapshot], timeoutSeconds: Int32) async throws { try await stop(ids: snapshots.map(\.configuration.id), timeoutSeconds: timeoutSeconds) } + /// Deletes containers, along with their data and any reports about them. + /// + /// - Parameters: + /// - ids: The IDs of the containers to delete. + /// - force: Whether to stop a running container and delete it, rather than leave it. + /// - Throws: An error that lists each container that couldn't be deleted. public func delete(ids: [String], force: Bool) async throws { let service = try await runtime.getContainersService() let snapshots = await service.list() - var failed: [(String, Error)] = [] var deleted: [String] = [] + var failed: [(String, Error)] = [] for id in ids { do { @@ -237,8 +295,7 @@ public final class ContainerManager { } } - // What was reported against a container has nothing left to say once the container has gone. - await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.container]) + try await runtime.getReportsService().delete(named: deleted, ofKind: [.container]) if !failed.isEmpty { let failures = failed.map({ "\($0.0): \($0.1)" }).joined(separator: "\n") @@ -248,6 +305,12 @@ public final class ContainerManager { } } + /// Deletes containers, along with their data and any reports about them. + /// + /// - Parameters: + /// - snapshots: The containers to delete. + /// - force: Whether to stop a running container and delete it, rather than leave it. + /// - Throws: An error that lists each container that couldn't be deleted. public func delete(snapshots: [ContainerSnapshot], force: Bool) async throws { try await delete(ids: snapshots.map(\.configuration.id), force: force) } @@ -298,9 +361,14 @@ public final class ContainerManager { return tokens } - /// The name a container will be known by: what it was given, or one made - /// up for it. Settled before the work starts, so that what is watching it - /// can say which container it is watching. + /// Returns the ID a new container will have: its name, or a generated ID if it has none. + /// + /// The ID is settled before the container is created, so work on the container can be tracked from + /// the start. + /// + /// - Parameter name: The name to give the container, or `nil`. + /// - Returns: The name, or a generated ID if `name` is `nil` or empty. + /// - Throws: An error if the name isn't a valid container name. public static func createContainerID(name: String?) throws -> String { let trimmedName = name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" @@ -319,7 +387,7 @@ public final class ContainerManager { return trimmedName } - /// Whether a name can be a container id. + /// Returns a Boolean value that indicates whether a name can be a container's ID. public static func isValidContainerName(_ name: String) -> Bool { EntityName.isValid(name) } diff --git a/ContainerSystem/Managers/ImageManager.swift b/ContainerSystem/Managers/ImageManager.swift index efff6ec..50c6a63 100644 --- a/ContainerSystem/Managers/ImageManager.swift +++ b/ContainerSystem/Managers/ImageManager.swift @@ -16,17 +16,18 @@ import Logging import NIO import Observation -/// Manages image operations. -/// Create instances via public init() - automatically references shared runtime. +/// A manager that pulls, builds, loads, saves and deletes images. +/// +/// Images the container system uses itself, such as the builder's image, are left out of +/// ``list(platform:includeVariants:)``. @Observable @MainActor public final class ImageManager { - /// Internal runtime reference (hidden from UI) let runtime: ContainerRuntime private let logger: Logger - /// Public initializer - creates instance referencing shared runtime + /// Creates a manager for the shared container system. public init() { self.runtime = ContainerRuntime.shared var logger = Logger(label: "app.containers.manager.image") @@ -35,7 +36,7 @@ public final class ImageManager { } #if DEBUG - /// Internal initializer for testing - allows injection of test runtime + /// Creates a manager for the given runtime, so tests can use a runtime of their own. init(testRuntime: ContainerRuntime) { self.runtime = testRuntime var logger = Logger(label: "app.containers.manager.image.test") @@ -46,8 +47,15 @@ public final class ImageManager { // MARK: - Public API - /// `includeVariants` reads the manifest and config of every platform in - /// each image's index, which `list` otherwise skips. + /// Returns every image, except the ones the container system uses itself, with whether a container uses it. + /// + /// - Parameters: + /// - platform: The platform to describe each image for, such as its size and creation date, or `nil` + /// to describe only the image as a whole. + /// - includeVariants: Whether to also describe every platform in each image's index, which means + /// reading their manifests and configurations. + /// - Returns: The images. + /// - Throws: An error if the container system isn't running. public func list( platform: Platform? = nil, includeVariants: Bool = false @@ -97,6 +105,11 @@ public final class ImageManager { return items } + /// Returns the details of an image, including every platform in its index. + /// + /// - Parameter image: The image to inspect. + /// - Returns: The image's details. + /// - Throws: An error if the image isn't in the container system. public func inspect(image: ImageDescription) async throws -> ImageResource { let storedImage = try await getStoredImage(reference: image.reference) let index = try await storedImage.index() @@ -111,6 +124,15 @@ public final class ImageManager { ) } + /// Pulls an image from a registry and unpacks it. + /// + /// - Parameters: + /// - reference: The image's reference, such as `nginx:latest`. A reference without a registry pulls + /// from Docker Hub. + /// - platform: The platform to pull, or `nil` to pull every platform in the image's index. + /// - scheme: The scheme to reach the registry with. + /// - progress: A progress that follows the work, step by step, or `nil` to not follow it. + /// - Throws: An error if the image can't be pulled or unpacked. public func pull( reference: String, platform: Platform? = .current, @@ -150,6 +172,11 @@ public final class ImageManager { logger.info("Image pulled successfully: \(processedReference)") } + /// Builds an image from a Dockerfile, using BuildKit in the builder container. + /// + /// Each build starts the builder container, or restarts it so that it can read the build's files. + /// The built image is written to `outputs`: an OCI output adds it to the container system's images, + /// and a tar or local output writes its files to the output's destination. public func build( dockerFile: URL, contextDirectory: URL, @@ -464,6 +491,13 @@ public final class ImageManager { logger.info("Image built successfully: \(tag)") } + /// Saves images to a tar archive in the OCI image layout. + /// + /// - Parameters: + /// - images: The images to save. + /// - platform: The platform to save. + /// - outputURL: Where to write the archive. + /// - Throws: An error if an image can't be saved or the archive can't be written. public func save(images: [ImageDescription], platform: Platform = .current, outputURL: URL) async throws { let service = try await runtime.getImagesService() @@ -484,8 +518,16 @@ public final class ImageManager { logger.info("Saved \(images.count) image(s)") } - /// - Returns: The images the archive held, which is only known once it - /// has been read. + /// Loads the images in a tar archive and unpacks them. + /// + /// - Parameters: + /// - tar: The archive to load. + /// - force: Whether to load the archive even if some of its entries were rejected while extracting it, + /// such as entries with unsafe paths. + /// - progress: A progress that follows the work, step by step, or `nil` to not follow it. + /// - Returns: The images the archive held, which is only known once it has been read. + /// - Throws: An error if the archive can't be read or loaded, or if it has rejected entries and `force` is + /// `false`. @discardableResult public func load( tar: URL, @@ -568,13 +610,19 @@ public final class ImageManager { return loaded.0 } + /// Deletes images, along with any reports about pulling or building them. + /// + /// The images the container system uses itself aren't deleted. + /// + /// - Parameter images: The images to delete. + /// - Throws: An error that lists each image that couldn't be deleted. public func delete(images: [ImageDescription]) async throws { let service = try await runtime.getImagesService() logger.info("Deleting \(images.count) image(s)") - var failed: [(String, Error)] = [] var deleted: [String] = [] + var failed: [(String, Error)] = [] var didDeleteAnyImage = false for image in images { @@ -592,9 +640,8 @@ public final class ImageManager { } } - // A build is reported against the image it was making, so both go - // with the image itself. - await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.image, .build]) + // A build is reported against the image it was making, so both go with the image. + try await runtime.getReportsService().delete(named: deleted, ofKind: [.image, .build]) if !failed.isEmpty { let failures = (failed.map({ "\($0.0): \($0.1)" })).joined(separator: "\n") @@ -608,6 +655,13 @@ public final class ImageManager { } } + /// Returns the layers of an image for a platform, with the step of the image's history that created each one. + /// + /// - Parameters: + /// - imageReference: The image's reference. + /// - platform: The platform whose layers to return. + /// - Returns: The image's layers. + /// - Throws: An error if the image or its configuration can't be read. public func getImageLayers(imageReference: String, platform: Platform) async throws -> [ImageLayer] { let appRoot = try runtime.getAppRoot() let imagesDir = appRoot.appendingPathComponent("images") @@ -817,17 +871,27 @@ public final class ImageManager { } } +/// Where and in which format a build writes the image it produces. public struct BuildImageOutputConfiguration { - // Public initializer to allow usage in default argument values + /// Creates an output configuration. + /// + /// - Parameters: + /// - type: The format to write the image in. + /// - destinationDirectory: Where to write the image. Required for every format except OCI. + /// - additionalFields: Extra settings to pass to BuildKit for this output. public init(type: BuildType, destinationDirectory: URL? = nil, additionalFields: [KeyValue] = []) { self.type = type self.destinationDirectory = destinationDirectory self.additionalFields = additionalFields } + /// The formats a build can write an image in. public enum BuildType: String, Identifiable { + /// An image in the OCI format, added to the container system's images. case oci + /// A tar archive of the image's files. case tar + /// The image's files, in a folder. case local public var id: String { @@ -858,10 +922,10 @@ public struct BuildImageOutputConfiguration { } } + /// The format to write the image in. public let type: BuildType - // required for local and tar - // for OCi, will use a temporary URL specific for the build + /// Where to write the image, or `nil` for the OCI format. public let destinationDirectory: URL? private var destination: URL? { @@ -875,6 +939,7 @@ public struct BuildImageOutputConfiguration { } } + /// Extra settings to pass to BuildKit for this output. public let additionalFields: [KeyValue] private static func keyValueString(key: String, value: String) -> String { @@ -907,6 +972,7 @@ public struct BuildImageOutputConfiguration { ) } + /// Checks that the configuration has a destination for formats that need one. public func verify() throws { guard let destinationDirectory = self.destinationDirectory else { if self.type == .oci { diff --git a/ContainerSystem/Managers/NetworkManager.swift b/ContainerSystem/Managers/NetworkManager.swift index 974a81b..b6ad3e4 100644 --- a/ContainerSystem/Managers/NetworkManager.swift +++ b/ContainerSystem/Managers/NetworkManager.swift @@ -12,17 +12,21 @@ import Foundation import Logging import Observation -/// Manages DNS resolver configuration for container domains. +/// A manager that reads the DNS domains configured for containers on the Mac. +/// +/// macOS keeps a resolver file for each domain in ``resolverDirectory``. Changing those files needs +/// administrator privileges, so this manager can list domains but not create or delete them. @Observable @MainActor public final class NetworkManager { + /// The folder where macOS keeps a resolver file for each DNS domain. public static let resolverDirectory = URL(fileURLWithPath: "/etc/resolver", isDirectory: true) private static let filePrefix = "containerization." private let logger: Logger - /// Public initializer - creates instance + /// Creates a manager for the shared container system. public init() { var logger = Logger(label: "app.containers.manager.network") logger.logLevel = .debug @@ -31,6 +35,13 @@ public final class NetworkManager { // MARK: - Public API + /// Returns the DNS domains that resolver files in a folder configure for containers, sorted by name. + /// + /// Only the resolver files the container tools create are read, and a file without a `domain` entry + /// is skipped. + /// + /// - Parameter directory: The folder to read, usually ``resolverDirectory``. + /// - Returns: The domains, or an empty array if the folder can't be read. public func listDomains(in directory: URL) -> [String] { let fileManager = FileManager.default let isScoped = directory.startAccessingSecurityScopedResource() @@ -83,6 +94,13 @@ public final class NetworkManager { // MARK: - Create domain + /// Creates a DNS domain for containers. + /// + /// Creating a resolver file needs administrator privileges, which the app doesn't have, so this method + /// always throws ``DNSError/notSupported``. + /// + /// - Parameter name: The domain to create. + /// - Throws: ``DNSError/notSupported``, always. public func createDomain(name: String) throws { // DNS domain creation requires root privileges. // This functionality is disabled in the GUI. @@ -92,6 +110,13 @@ public final class NetworkManager { // MARK: - Delete domain + /// Deletes a DNS domain for containers. + /// + /// Deleting a resolver file needs administrator privileges, which the app doesn't have, so this method + /// always throws ``DNSError/notSupported``. + /// + /// - Parameter name: The domain to delete. + /// - Throws: ``DNSError/notSupported``, always. public func deleteDomain(name: String) throws { // DNS domain deletion requires root privileges. // This functionality is disabled in the GUI. @@ -101,8 +126,11 @@ public final class NetworkManager { // MARK: - Errors + /// Errors that DNS domain operations throw. public enum DNSError: LocalizedError { + /// The domain name isn't valid. case invalidDomainName + /// The app can't create or delete DNS domains. case notSupported public var errorDescription: String? { diff --git a/ContainerSystem/Managers/ReportManager.swift b/ContainerSystem/Managers/ReportManager.swift index 5fb2d36..226c8dd 100644 --- a/ContainerSystem/Managers/ReportManager.swift +++ b/ContainerSystem/Managers/ReportManager.swift @@ -9,33 +9,49 @@ import Foundation import Logging import Observation -/// Records failed work and keeps the reports the app shows. Every instance shares the runtime's reports. +/// A manager that records failed work, and keeps the reports it leaves. +/// +/// A report keeps what went wrong with a pull, a build or a container after the work ends, so people +/// can review it later. Reports are saved in the container system's storage folder. @Observable @MainActor public final class ReportManager { let runtime: ContainerRuntime private let logger: Logger - private let folder: String - /// The most recent first. - public private(set) var reports: [Report] { - get { runtime.reports } - set { runtime.reports = newValue } + /// The reports, most recent first. + public var reports: [Report] { + runtime.reports } - public convenience init() { - self.init(runtime: ContainerRuntime.shared) - } - - init(runtime: ContainerRuntime, folder: String = "reports") { - self.runtime = runtime + /// Creates a manager for the shared container system. + public init() { + self.runtime = ContainerRuntime.shared self.logger = Logger(label: "app.containers.manager.report") - self.folder = folder } - /// Doesn't throw: failing to write a report isn't worth a second failure. - /// A container's own output isn't copied in, as its Logs already hold it. + #if DEBUG + /// Creates a manager for the given runtime, so tests can use a runtime of their own. + init(testRuntime: ContainerRuntime) { + self.runtime = testRuntime + self.logger = Logger(label: "app.containers.manager.report.test") + } + #endif + + /// Records a report of failed work. + /// + /// This method doesn't throw: if the report can't be saved, it returns `nil`. A container's own + /// output isn't copied into its report, because the container's logs already keep it. + /// + /// - Parameters: + /// - level: How serious the problem is. + /// - kind: The kind of work that failed. + /// - name: The name of what the work was on, such as an image's reference or a container's ID. + /// - message: A short description of what went wrong. + /// - error: The error the work threw, which the report keeps in full. + /// - startedAt: When the work started, or `nil` if the report covers only the moment it failed. + /// - Returns: The new report, or `nil` if it couldn't be saved. @discardableResult public func record( level: Report.Level = .error, @@ -45,21 +61,16 @@ public final class ReportManager { error: any Error, startedAt: Date? = nil ) async -> Report? { - guard let store = try? store() else { return nil } - do { - let entry = try await store.record( - level: level, - kind: kind, - name: name, - message: message, - body: Self.body(for: error), - startedAt: startedAt - ) - - reports.insert(entry, at: 0) - - return entry + return try await runtime.getReportsService() + .record( + level: level, + kind: kind, + name: name, + message: message, + body: Self.body(for: error), + startedAt: startedAt + ) } catch { logger.error("Couldn’t write the report: \(error)") @@ -67,102 +78,107 @@ public final class ReportManager { } } + /// The number of reports that haven't been read. public var unreadCount: Int { reports.count { !$0.isRead } } + /// Marks reports as read. + /// + /// - Parameter ids: The IDs of the reports to mark. public func markRead(_ ids: [String]) async { - guard let store = try? store() else { return } - - let unread = Set( - reports.filter { !$0.isRead && ids.contains($0.id) }.map(\.id) - ) - - guard !unread.isEmpty else { return } - - await store.markRead(Array(unread)) + let ids = Set(ids) + let unread = reports.filter { !$0.isRead && ids.contains($0.id) }.map(\.id) - reports = reports.map { report in - guard unread.contains(report.id) else { return report } + guard !unread.isEmpty, let service = service() else { return } - return Report( - id: report.id, - date: report.date, - endDate: report.endDate, - level: report.level, - kind: report.kind, - name: report.name, - message: report.message, - isRead: true - ) - } + await service.markRead(unread) } + /// Reloads the reports from the storage folder. public func refresh() async { - guard let store = try? store() else { return } + guard let service = service() else { return } - reports = await store.list() + runtime.reports = await service.list() } - /// `kinds` lists every kind the item is filed under: an image is reported - /// both as `.image` and as `.build`. + /// Returns the most recent report about something. + /// + /// - Parameters: + /// - name: The name of what the work was on. + /// - kinds: Every kind of report it can have. An image, for example, has both image and build reports. + /// - Returns: The report, or `nil` if there isn't one. public func latestReport(named name: String, ofKind kinds: Set) -> Report? { reports.first { kinds.contains($0.kind) && $0.name == name } } + /// Returns the reports about something, most recent first. + /// + /// - Parameters: + /// - name: The name of what the work was on. + /// - kinds: Every kind of report it can have. + /// - Returns: The reports. public func reports(named name: String, ofKind kinds: Set) -> [Report] { reports.filter { kinds.contains($0.kind) && $0.name == name } } + /// Returns a Boolean value that indicates whether a report has been read. + /// + /// - Parameter id: The report's ID. + /// - Returns: `true` if the report has been read or doesn't exist. public func isRead(_ id: String) -> Bool { reports.first { $0.id == id }?.isRead ?? true } - public func entry(for id: String) async -> Report? { - guard let store = try? store() else { return nil } + /// Returns a report, read from the storage folder. + /// + /// - Parameter id: The report's ID. + /// - Returns: The report, or `nil` if it doesn't exist. + public func get(id: String) async -> Report? { + guard let service = service() else { return nil } - return await store.entry(for: id) + return await service.get(id: id) } + /// Returns the full text of a report. + /// + /// - Parameter id: The report's ID. + /// - Returns: The text, or `nil` if it can't be read. public func body(of id: String) async -> String? { - guard let store = try? store() else { return nil } - - return try? await store.body(of: id) - } + guard let service = service() else { return nil } - public func remove(_ ids: [String]) async { - guard let store = try? store() else { return } - - await store.remove(ids) + do { + return try await service.body(of: id) + } catch { + logger.error("Couldn’t read the report \(id): \(error)") - reports.removeAll { ids.contains($0.id) } + return nil + } } - /// For items that were deleted, whose reports nothing can lead to any more. - public func remove(named names: [String], ofKind kinds: Set) async { - let names = Set(names) - let ids = - reports - .filter { kinds.contains($0.kind) && names.contains($0.name) } - .map(\.id) - - guard !ids.isEmpty else { return } - - await remove(ids) + /// Deletes reports. + /// + /// - Parameter ids: The IDs of the reports to delete. + public func delete(ids: [String]) async { + await service()?.delete(ids: ids) } + /// Returns the location of a report's file, for showing it in the Finder. + /// + /// - Parameter id: The report's ID. + /// - Returns: The file's URL, or `nil` if the storage folder isn't available. public func url(for id: String) -> URL? { - try? store().url(for: id) + service()?.url(for: id) } - private func store() throws -> ReportStore { - if let store = runtime.reportStore { return store } - - let store = try ReportStore(root: runtime.getAppRoot().appendingPathComponent(folder)) - - runtime.reportStore = store + private func service() -> ReportsService? { + do { + return try runtime.getReportsService() + } catch { + logger.error("Couldn’t reach the reports: \(error)") - return store + return nil + } } static func body(for error: any Error) -> String { diff --git a/ContainerSystem/Managers/SystemManager.swift b/ContainerSystem/Managers/SystemManager.swift index 3fc61e6..93ac6b4 100644 --- a/ContainerSystem/Managers/SystemManager.swift +++ b/ContainerSystem/Managers/SystemManager.swift @@ -11,8 +11,10 @@ import Foundation import Logging import Observation -/// Public system manager for controlling container system lifecycle -/// This is the main API exposed to the UI layer for system control +/// A manager that starts and stops the container system, and reports its status. +/// +/// Start the container system before you use the other managers. The first start installs what the +/// system needs, such as the Linux kernel, and reports it through ``setupProgress``. @Observable @MainActor public final class SystemManager { @@ -21,17 +23,24 @@ public final class SystemManager { private let logger: Logger private var startTask: Task? + /// The error that made the last start fail, or `nil` if it didn't fail. public var startupError: (any Error)? { runtime.startupError } - /// Where the system is in its life cycle; `startupError` says why a start failed. + /// The stages of the container system's life cycle. public enum Status: Equatable { + /// The container system isn't running. case notStarted + /// The container system is starting, and may be installing what it needs first. case starting + /// The container system is running, and containers can be created and run. case running + /// The container system is stopping its containers and services. case stopping + /// The last start failed. ``SystemManager/startupError`` describes why. case failed } + /// The stage the container system is in. public var status: Status { if runtime.isStopping { return .stopping } if runtime.isStarting { return .starting } @@ -40,20 +49,22 @@ public final class SystemManager { return .notStarted } - /// How far a first start has got with installing what the system needs, - /// while it installs it; `nil` once there is nothing left to install. + /// The progress of installing what the container system needs, such as the Linux kernel and the + /// init image, while a start installs it. + /// + /// This property is `nil` when nothing is being installed. public var setupProgress: Progress? { runtime.setupProgress } - /// Public initializer - creates instance referencing shared runtime + /// Creates a manager for the shared container system. public init() { self.runtime = ContainerRuntime.shared self.logger = Logger(label: "app.containers.manager.system") } #if DEBUG - /// Internal initializer for testing - allows injection of test runtime + /// Creates a manager for the given runtime, so tests can use a runtime of their own. init(testRuntime: ContainerRuntime) { self.runtime = testRuntime self.logger = Logger(label: "app.containers.manager.system.test") @@ -62,9 +73,10 @@ public final class SystemManager { // MARK: - Lifecycle Methods - /// Start the container system. - /// - Parameter appRoot: Root directory for container data. - /// - Throws: An error if the runtime cannot initialize prerequisites, storage, services, or networking. + /// Starts the container system, installing what it needs the first time. + /// + /// - Parameter appRoot: The folder where the container system keeps its data. + /// - Throws: An error if the system can't install what it needs, or start its storage or services. public func start(appRoot: URL) async throws { logger.info("Starting system", metadata: ["appRoot": "\(appRoot.path)"]) @@ -87,18 +99,20 @@ public final class SystemManager { } } + /// Cancels a start that's in progress, including one another caller began. public func cancelStart() { logger.info("Cancelling start") startTask?.cancel() } + /// Returns the disk space the container system's data uses, in bytes, or `nil` if it isn't running. public func diskUsage() async -> Int64? { guard let appRoot = try? runtime.getAppRoot() else { return nil } return await FileIO.shared.allocatedSize(of: appRoot) } - /// Stop the container system + /// Stops the container system, and every container that's running. public func stop() async throws { logger.info("Stopping system") try await runtime.stop() diff --git a/ContainerSystem/Managers/VolumeManager.swift b/ContainerSystem/Managers/VolumeManager.swift index d003044..cdb9e85 100644 --- a/ContainerSystem/Managers/VolumeManager.swift +++ b/ContainerSystem/Managers/VolumeManager.swift @@ -14,13 +14,13 @@ import Logging import Observation import SystemPackage -/// Manages volume operations. -/// Create instances via public init() - automatically references shared runtime. +/// A manager that creates, lists and deletes volumes. +/// +/// Each volume is an ext4 disk image in the container system's storage folder. @Observable @MainActor public final class VolumeManager { - /// Internal runtime reference (hidden from UI) let runtime: ContainerRuntime private let logger: Logger @@ -28,7 +28,7 @@ public final class VolumeManager { // Storage constants private static let blockFile = "volume.ext4" - /// Public initializer - creates instance referencing shared runtime + /// Creates a manager for the shared container system. public init() { self.runtime = ContainerRuntime.shared @@ -39,7 +39,7 @@ public final class VolumeManager { } #if DEBUG - /// Internal initializer for testing - allows injection of test runtime + /// Creates a manager for the given runtime, so tests can use a runtime of their own. init(testRuntime: ContainerRuntime) { self.runtime = testRuntime @@ -52,6 +52,16 @@ public final class VolumeManager { // MARK: - Public API + /// Creates a volume. + /// + /// - Parameters: + /// - name: The volume's name, which must be unique and use only valid characters. + /// - labels: Labels to add to the volume. + /// - options: Driver options for the volume. + /// - sizeInBytes: The volume's size, or `nil` for the default size. + /// - Returns: The new volume. + /// - Throws: An error if the name isn't valid, a volume with that name exists, or the volume can't be + /// created. @discardableResult public func create( name: String, @@ -116,12 +126,14 @@ public final class VolumeManager { return volume } + /// Returns every volume. public func list() async throws -> [Volume] { let store = try await getStore() return try await store.list() } + /// Returns every volume, with whether a container uses it. public func summaries() async throws -> [VolumeSummary] { let store = try await getStore() let service = try await runtime.getContainersService() @@ -132,6 +144,12 @@ public final class VolumeManager { } } + /// Deletes volumes, along with their data and any reports about them. + /// + /// A volume that a container uses isn't deleted. + /// + /// - Parameter volumes: The volumes to delete. + /// - Throws: An error that lists each volume that couldn't be deleted. public func delete(volumes: [Volume]) async throws { let store = try await getStore() let service = try await runtime.getContainersService() @@ -170,7 +188,7 @@ public final class VolumeManager { } } - await ReportManager(runtime: runtime).remove(named: deleted, ofKind: [.volume]) + try await runtime.getReportsService().delete(named: deleted, ofKind: [.volume]) if !failed.isEmpty { throw ContainerizationError( @@ -200,8 +218,13 @@ public final class VolumeManager { } extension VolumeManager { - /// The volume of that name, created if it does not exist yet. An empty - /// name gets a fresh anonymous one. + /// Returns the volume with a name, creating it if it doesn't exist yet. + /// + /// - Parameters: + /// - name: The volume's name. An empty name creates a new anonymous volume. + /// - existing: The volumes that exist, to look the name up in. + /// - Returns: The existing or new volume. + /// - Throws: An error if the volume can't be created. public func volume(named name: String, among existing: [Volume]) async throws -> Volume { if !name.isEmpty, let match = existing.first(where: { $0.name == name }) { return match diff --git a/ContainerSystem/ContainerRuntime+Plugins.swift b/ContainerSystem/Runtime/ContainerRuntime+Plugins.swift similarity index 100% rename from ContainerSystem/ContainerRuntime+Plugins.swift rename to ContainerSystem/Runtime/ContainerRuntime+Plugins.swift diff --git a/ContainerSystem/ContainerRuntime+Prerequisites.swift b/ContainerSystem/Runtime/ContainerRuntime+Prerequisites.swift similarity index 100% rename from ContainerSystem/ContainerRuntime+Prerequisites.swift rename to ContainerSystem/Runtime/ContainerRuntime+Prerequisites.swift diff --git a/ContainerSystem/ContainerRuntime.swift b/ContainerSystem/Runtime/ContainerRuntime.swift similarity index 88% rename from ContainerSystem/ContainerRuntime.swift rename to ContainerSystem/Runtime/ContainerRuntime.swift index d595aa8..a25b42d 100644 --- a/ContainerSystem/ContainerRuntime.swift +++ b/ContainerSystem/Runtime/ContainerRuntime.swift @@ -13,15 +13,19 @@ import ContainerizationOCI import Foundation import Logging -/// Container runtime lifecycle and services. -/// Owns all services and provides factory methods for creating managers. +/// `ContainerRuntime` manages the lifecycle of the in-process container system, and owns +/// the services that run it. +/// +/// The services are created when the system starts and released when it stops. Managers +/// reach them through the `get…Service()` accessors, which throw while the system is stopped. +/// The runtime also holds the state the app observes, such as the system's status and its reports. @Observable @MainActor class ContainerRuntime { - /// Shared runtime instance - internal to ContainerSystem module + /// The runtime every manager uses, unless a test provides its own. static let shared = ContainerRuntime() - /// Private initializer - forces use of singleton in production + /// Creates the shared runtime. private init() { _ = Self._bootstrapLogging var l = Logger(label: "app.containers.system") @@ -34,7 +38,7 @@ class ContainerRuntime { } #if DEBUG - /// Internal initializer for testing - allows subclassing + /// Creates a runtime for tests, which subclass it to provide services of their own. init(forTesting: Bool) { _ = Self._bootstrapLogging var l = Logger(label: "app.containers.system.test") @@ -64,9 +68,6 @@ class ContainerRuntime { /// What a first start is fetching, while it fetches it. var setupProgress: Progress? - - @ObservationIgnored var reportStore: ReportStore? - var pluginProcesses: [String: PluginProcessInfo] = [:] // Current configuration @@ -80,6 +81,7 @@ class ContainerRuntime { private var containersService: ContainersService? private var imagesService: ImagesService? private var kernelService: KernelService? + private var reportsService: ReportsService? private var contentStore: ContentStore? let logger: Logger @@ -123,6 +125,17 @@ class ContainerRuntime { return service } + func getReportsService() throws -> ReportsService { + guard let service = reportsService else { + throw ContainerizationError( + .internalError, + message: "Reports service not initialized" + ) + } + + return service + } + func getAppRoot() throws -> URL { guard let appRoot = appRoot else { throw ContainerizationError( @@ -281,6 +294,10 @@ class ContainerRuntime { self.kernelService = kernel + let reportsService = try ReportsService(appRoot: appRoot, log: logger) + + self.reportsService = reportsService + servicesInitialized = true logger.info("Services initialized successfully") @@ -291,6 +308,10 @@ class ContainerRuntime { self.lastContainerStateChange = Date() } + + await reportsService.addChangeCallback { @MainActor [weak self] reports in + self?.reports = reports + } } /// Shutdown all services @@ -321,6 +342,7 @@ class ContainerRuntime { containersService = nil imagesService = nil kernelService = nil + reportsService = nil contentStore = nil pluginLoader = nil servicesInitialized = false diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService+Configuration.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService+Configuration.swift new file mode 100644 index 0000000..a149dd3 --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService+Configuration.swift @@ -0,0 +1,194 @@ +// +// ContainersService+Configuration.swift +// Containers +// +// Turns a container configuration into the virtual machine and process LinuxContainer runs. +// +// Created by Axel Martinez on 2026/10/24. +// + +import Containerization +import ContainerizationError +import ContainerizationOCI +import ContainerizationOS +import Foundation +import SystemPackage + +extension Filesystem { + var asMount: Containerization.Mount { + switch self.type { + case .tmpfs: + return .any( + type: "tmpfs", + source: self.source, + destination: self.destination, + options: self.options + ) + case .virtiofs: + return .share( + source: self.source, + destination: self.destination, + options: self.options + ) + case .block(let format, _, _): + return .block( + format: format, + source: self.source, + destination: self.destination, + options: self.options + ) + case .volume(_, let format, _, _): + return .block( + format: format, + source: self.source, + destination: self.destination, + options: self.options + ) + } + } + + func isSocket() throws -> Bool { + if !self.isVirtiofs { + return false + } + let info = try File.info(self.source) + + return info.isSocket + } +} + +extension ContainersService { + static func configureContainer( + czConfig: inout LinuxContainer.Configuration, + config: ContainerConfiguration, + precomputedMounts: [Containerization.Mount], + precomputedSockets: [UnixSocketConfiguration] + ) throws { + czConfig.cpus = config.resources.cpus + czConfig.memoryInBytes = config.resources.memoryInBytes + czConfig.sysctl = config.sysctls + czConfig.virtualization = config.virtualization + + czConfig.mounts.append(contentsOf: precomputedMounts) + czConfig.sockets.append(contentsOf: precomputedSockets) + + for publishedSocket in config.publishedSockets { + let socketConfig = UnixSocketConfiguration( + source: publishedSocket.containerPath, + destination: publishedSocket.hostPath, + permissions: publishedSocket.permissions, + direction: .outOf + ) + czConfig.sockets.append(socketConfig) + } + + if config.ssh, let sshSocket = Foundation.ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] { + let socketUrl = URL(fileURLWithPath: sshSocket) + let socketPath = socketUrl.path(percentEncoded: false) + let attrs = try? FileManager.default.attributesOfItem(atPath: socketPath) + let permissions = (attrs?[.posixPermissions] as? NSNumber) + .map { FilePermissions(rawValue: mode_t($0.intValue)) } + let socketConfig = UnixSocketConfiguration( + source: socketUrl, + destination: URL(fileURLWithPath: "/run/host-services/ssh-auth.sock"), + permissions: permissions, + direction: .into + ) + czConfig.sockets.append(socketConfig) + } + + czConfig.hostname = config.id + + // Only set DNS if explicitly provided by container configuration + // Setting DNS causes the framework to write /etc/resolv.conf which fails on read-only rootfs + // If not set, containers will use the host's DNS via the VM network + if let dns = config.dns, !dns.nameservers.isEmpty { + czConfig.dns = DNS( + nameservers: dns.nameservers, + domain: dns.domain, + searchDomains: dns.searchDomains, + options: dns.options + ) + } + + try Self.configureInitialProcess(czConfig: &czConfig, config: config) + } + + private static func configureInitialProcess( + czConfig: inout LinuxContainer.Configuration, + config: ContainerConfiguration + ) throws { + let process = config.initProcess + + czConfig.process.arguments = [process.executable] + process.arguments + czConfig.process.environmentVariables = process.environment + czConfig.process.capabilities = try capabilities(from: config.capabilities) + + if config.ssh, Foundation.ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] != nil { + let sshEnvVar = "SSH_AUTH_SOCK" + let sshGuestPath = "/run/host-services/ssh-auth.sock" + + if !czConfig.process.environmentVariables.contains(where: { + $0.starts(with: "\(sshEnvVar)=") + }) { + czConfig.process.environmentVariables.append("\(sshEnvVar)=\(sshGuestPath)") + } + } + + czConfig.process.terminal = process.terminal + czConfig.process.workingDirectory = process.workingDirectory + czConfig.process.rlimits = process.rlimits.compactMap { + guard let kind = try? LinuxRLimit.Kind($0.limit) else { return nil } + return .init(kind: kind, hard: $0.hard, soft: $0.soft) + } + + switch process.user { + case .raw(let name): + czConfig.process.user = .init( + uid: 0, + gid: 0, + umask: nil, + additionalGids: process.supplementalGroups, + username: name + ) + case .id(let uid, let gid): + czConfig.process.user = .init( + uid: uid, + gid: gid, + umask: nil, + additionalGids: process.supplementalGroups, + username: "" + ) + } + } + + private static func capabilities(from names: [String]) throws -> Containerization.LinuxCapabilities { + let capabilities = try capabilitySet(from: names) + + guard !capabilities.isEmpty else { + return .allCapabilities + } + + return Containerization.LinuxCapabilities(capabilities: Array(capabilities)) + } + + private static func capabilitySet(from names: [String]) throws -> Set { + var capabilities: Set = [] + + for name in names { + let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) + + guard !trimmedName.isEmpty else { + continue + } + + if trimmedName.uppercased() == "ALL" { + capabilities.formUnion(CapabilityName.allCases) + } else { + capabilities.insert(try CapabilityName(rawValue: trimmedName)) + } + } + + return capabilities + } +} diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService+Lifecycle.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService+Lifecycle.swift new file mode 100644 index 0000000..389ab0f --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService+Lifecycle.swift @@ -0,0 +1,375 @@ +// +// ContainersService+Lifecycle.swift +// Containers +// +// Booting, starting, stopping and deleting containers, and handling their exits. +// +// Created by Axel Martinez on 2026/10/24. +// + +import Containerization +import ContainerizationError +import ContainerizationExtras +import ContainerizationOS +import Foundation +import Logging + +extension ContainersService { + func bootstrap(id: String, stdio: [FileHandle?]) async throws { + try await lock(for: id).withLock { _ in + try await self._bootstrap(id: id, stdio: stdio) + } + } + + private func _bootstrap(id: String, stdio: [FileHandle?]) async throws { + var state = try containerState(for: id) + + // Already bootstrapped + if state.container != nil { + return + } + + let previousStatus = state.snapshot.status + var hasBooted = false + + // Shown while the virtual machine boots, which is most of a start. + state.snapshot.status = .starting + containers[id] = state + notifyStateChange() + + defer { + if !hasBooted { + containers[id]?.snapshot.status = previousStatus + notifyStateChange() + } + } + + let bundle = state.bundle ?? Bundle(path: bundlePath(for: id)) + + let config = try bundle.configuration + let bundleKernel = try bundle.kernel + let initMount = await MainActor.run { + bundle.initialFilesystem.asMount + } + let vmm = VZVirtualMachineManager( + kernel: bundleKernel, + initialFilesystem: initMount, + rosetta: config.rosetta, + logger: self.log + ) + + // Create the log file for container stdio + let containerLogURL = bundle.path.appendingPathComponent("stdio.log") + + do { + let fd = Darwin.open(containerLogURL.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644) + guard fd >= 0 else { + throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) + } + Darwin.close(fd) + } + + // Set up stdio writers, each copying into the container log. A terminal + // carries stderr on stdout. + let containerLog = try FileHandle(forWritingTo: containerLogURL) + let stdout = MultiWriter(handles: [stdio[1], containerLog].compactMap { $0 }) + let stderr = + config.initProcess.terminal + ? nil : MultiWriter(handles: [stdio[2], containerLog].compactMap { $0 }) + let stdin = stdio[0].map(FileHandleReader.init(handle:)) + + let rootfs = try await MainActor.run { + try bundle.containerRootfs.asMount + } + + // Precompute mounts and sockets + var precomputedMounts: [Containerization.Mount] = [] + var precomputedSockets: [UnixSocketConfiguration] = [] + + for mount in config.mounts { + if try await MainActor.run(body: { try mount.isSocket() }) { + let socket = UnixSocketConfiguration( + source: URL(filePath: mount.source), + destination: URL(filePath: mount.destination) + ) + precomputedSockets.append(socket) + } else { + let mnt = await MainActor.run { mount.asMount } + precomputedMounts.append(mnt) + } + } + + // Allocate IP before the closure (actor-isolated state) + let (ip, gw) = try allocateIP(for: id) + + let container = try LinuxContainer(id, rootfs: rootfs, vmm: vmm, logger: self.log) { czConfig in + try Self.configureContainer( + czConfig: &czConfig, + config: config, + precomputedMounts: precomputedMounts, + precomputedSockets: precomputedSockets + ) + + // Configure NATInterface (IsolatedInterfaceStrategy pattern) + czConfig.interfaces = [try NATInterface(ipv4Address: CIDRv4(ip), ipv4Gateway: IPv4Address(gw))] + + // Do not set hosts configuration - causes I/O errors when framework tries to write /etc/hosts + // The framework will handle hosts automatically + + czConfig.process.stdout = stdout + czConfig.process.stderr = stderr + czConfig.process.stdin = stdin + + // The console is the only account of a boot that never reaches the + // container process, which is when stdio stays empty. + czConfig.bootLog = .file(path: bundle.bootLog, append: true) + } + + do { + try await container.create() + + state.container = container + state.bundle = bundle + state.snapshot.networks = [ + Attachment( + network: "nat", + hostname: id, + ipv4Address: try CIDRv4(ip), + ipv4Gateway: try IPv4Address(gw), + ipv6Address: CIDRv6?.none, + macAddress: MACAddress?.none + ) + ] + containers[id] = state + hasBooted = true + + // Notify observers that networks have been assigned + notifyStateChange() + } catch { + log.error("Failed to bootstrap container \(id): \(error)") + releaseIP(for: id) + throw error + } + } + + func startProcess(id: String, processID: String) async throws { + // A stop that lands between boot and start waits for the start to + // finish, or goes first and leaves no virtual machine to start. + try await lock(for: id).withLock { _ in + try await self._startProcess(id: id, processID: processID) + } + } + + private func _startProcess(id: String, processID: String) async throws { + var state = try containerState(for: id) + + let isInit = id == processID + if state.snapshot.status == .running && isInit { + return + } + + guard let container = state.container else { + throw ContainerizationError(.invalidState, message: "container not bootstrapped: \(id)") + } + + do { + try await container.start() + } catch { + if isInit { + // Booted, but it never got as far as running. A failed start + // leaves the virtual machine errored, and stopping it again only + // rethrows that error, so it's let go here. Kept, it would hold + // the IP address and log handle, and block a delete or restart. + try? await container.stop() + await markStopped(id: id)?.stopAll() + } + + throw error + } + // Container init process started + + if isInit { + let startedDate = Date() + + state.snapshot.status = .running + state.snapshot.startedDate = startedDate + + // Kept on disk so the container still reports when it last ran + // after the app has been quit and reopened. + do { + try state.bundle?.setState(Bundle.State(startedDate: startedDate)) + } catch { + log.warning("Failed to record start date for container \(id): \(error)") + } + + // Start port forwarding for published ports + let config = state.snapshot.configuration + if !config.publishedPorts.isEmpty { + let forwarder = PortForwarder(log: self.log) + for port in config.publishedPorts { + do { + try await forwarder.startForwarding(publishPort: port, container: container) + } catch { + log.warning("Failed to start port forwarding for \(port.hostPort) -> \(port.containerPort): \(error)") + } + } + portForwarders[id] = forwarder + } + + // Monitor container exit in background + let logger = self.log + + state.exitMonitorTask = Task { [weak self] in + var exitCode: Int32 = 0 + do { + exitCode = try await container.wait().exitCode + } catch { + logger.error("Error waiting for container \(id): \(error)") + } + await self?.handleContainerExit(id: id, exitCode: exitCode) + return exitCode + } + + containers[id] = state + + // Notify observers that container started + notifyStateChange() + } + } + + /// Waits for the container's init process to exit and returns its code. + func wait(id: String) async throws -> Int32 { + let state = try containerState(for: id) + + // A container that exited before anyone waited on it has already torn + // down its monitor, so the code it left behind is all there is. + guard let monitor = state.exitMonitorTask else { + return state.lastExitCode ?? 0 + } + + return try await ExitWaiter().wait(for: monitor) + } + + func stop(id: String, options: ContainerStopOptions) async throws { + try await lock(for: id).withLock { _ in + try await self._stop(id: id, options: options) + } + } + + private func _stop(id: String, options: ContainerStopOptions) async throws { + let initialState = try containerState(for: id) + + if let container = initialState.container { + // Shown while the container winds down, which can last until the stop timeout. + containers[id]?.snapshot.status = .stopping + notifyStateChange() + + do { + try await gracefulStopContainer(container, stopOpts: options) + } catch let err as ContainerizationError { + if err.code != .interrupted { + // It is still running, as far as anyone can tell. + containers[id]?.snapshot.status = initialState.snapshot.status + notifyStateChange() + throw err + } + } catch { + log.error("Error during graceful stop of container \(id): \(error)") + } + } + + // Stop port forwarding, once the state no longer depends on it. + await markStopped(id: id)?.stopAll() + } + + func delete(id: String) async throws { + // Waits for a boot, start or stop of the same container to finish. + try await lock(for: id).withLock { _ in + try await self._delete(id: id) + } + } + + private func _delete(id: String) throws { + let state = try containerState(for: id) + + // A container booted but not yet started still has a virtual machine, + // which deleting it now would leave running with nothing to stop it. + if state.snapshot.status == .running || state.container != nil { + throw ContainerizationError(.invalidState, message: "cannot delete running container") + } + + removeContainer(id: id) + notifyStateChange() + } + + // MARK: - Exit Handling + + private func handleContainerExit(id: String, exitCode: Int32) { + if let forwarder = markStopped(id: id, exitCode: exitCode) { + Task { await forwarder.stopAll() } + } + } + + /// Records that a container's virtual machine is gone, whether stopped or + /// exited, and deletes it if it auto-removes. Hands back its port forwarder + /// for the caller to stop. + /// + /// Reads the container's state afresh: a stop runs this after waiting out + /// the exit, by which time `handleContainerExit` may have kept the exit + /// code or deleted the container. + private func markStopped(id: String, exitCode: Int32? = nil) -> PortForwarder? { + let forwarder = portForwarders.removeValue(forKey: id) + + if var state = containers[id] { + if let exitCode { + state.lastExitCode = exitCode + } + + state.exitMonitorTask?.cancel() + state.exitMonitorTask = nil + state.snapshot.status = .stopped + state.snapshot.networks = [] + state.container = nil + releaseIP(for: id) + + containers[id] = state + + if autoRemoves(state) { + removeContainer(id: id) + } + } + + notifyStateChange() + return forwarder + } + + private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws { + // Try to gracefully shut down the process, then force-stop the VM. + do { + _ = try await withThrowingTaskGroup(of: ExitStatus.self) { group in + group.addTask { + try await lc.wait() + } + group.addTask { + try await lc.kill(Signal(rawValue: stopOpts.signal)) + try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds)) + try await lc.kill(Signal(rawValue: SIGKILL)) + return ExitStatus(exitCode: 137) + } + guard let code = try await group.next() else { + throw ContainerizationError( + .internalError, + message: "failed to get exit code from gracefully stopping container" + ) + } + group.cancelAll() + return code + } + } catch { + log.notice("graceful stop failed, forcing: \(error)") + } + + // Bring down the VM + try await lc.stop() + } +} diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService+Networking.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService+Networking.swift new file mode 100644 index 0000000..c386c33 --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService+Networking.swift @@ -0,0 +1,27 @@ +// +// ContainersService+Networking.swift +// Containers +// +// IP addresses for containers on the NAT network. +// +// Created by Axel Martinez on 2026/10/24. +// + +import ContainerizationError + +extension ContainersService { + func allocateIP(for id: String) throws -> (address: String, gateway: String) { + let hostNumber = ipAllocations[id] ?? (UInt8(2)...254).first { !ipAllocations.values.contains($0) } + + guard let hostNumber else { + throw ContainerizationError(.internalError, message: "no available IP addresses") + } + + ipAllocations[id] = hostNumber + return (address: "192.168.64.\(hostNumber)/24", gateway: "192.168.64.1") + } + + func releaseIP(for id: String) { + ipAllocations.removeValue(forKey: id) + } +} diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService+Processes.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService+Processes.swift new file mode 100644 index 0000000..8387578 --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService+Processes.swift @@ -0,0 +1,83 @@ +// +// ContainersService+Processes.swift +// Containers +// +// Running commands in, connecting to, and measuring running containers. +// +// Created by Axel Martinez on 2026/10/24. +// + +import Containerization +import ContainerizationError +import Foundation + +extension ContainersService { + /// What each running container is using right now. A container that + /// cannot say, because it is on its way down, is left out. + func resourceUsage() async -> [ContainerResourceUsage] { + // Taken before the first await: the actor can change underneath it. + let running = containers.compactMap { id, state in + state.snapshot.status == .running + ? state.container.map { (id, $0) } : nil + } + + var usage: [ContainerResourceUsage] = [] + + for (id, container) in running { + guard + let stats = try? await container.statistics(categories: [.memory, .cpu]) + else { + continue + } + + let entry = ContainerResourceUsage( + id: id, + memoryBytes: stats.memory?.usageBytes ?? 0, + cpuUsageMicroseconds: stats.cpu?.usageUsec ?? 0 + ) + + usage.append(entry) + } + + return usage + } + + /// Execute a command in a running container and return its output (uses vsock, no networking needed). + func exec(id: String, arguments: [String]) async throws -> String { + let container = try runningContainer(id: id) + + let outputURL = containerRoot.appendingPathComponent("\(id)-exec-output.tmp") + + FileManager.default.createFile(atPath: outputURL.path, contents: nil) + + let outputHandle = try FileHandle(forWritingTo: outputURL) + let writer = MultiWriter(handles: [outputHandle]) + + let process = try await container.exec("exec-\(UUID().uuidString)") { config in + config.arguments = arguments + config.stdout = writer + config.stderr = writer + } + + try await process.start() + + let exitStatus = try await process.wait() + + try? writer.close() + + let output = (try? String(contentsOf: outputURL, encoding: .utf8)) ?? "" + + try? FileManager.default.removeItem(at: outputURL) + + if exitStatus.exitCode != 0 { + let message = "command failed with exit code \(exitStatus.exitCode): \(output)" + throw ContainerizationError(.internalError, message: message) + } + + return output + } + + func dial(id: String, port: UInt32) async throws -> FileHandle { + try await runningContainer(id: id).dialVsock(port: port) + } +} diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService+Streams.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService+Streams.swift new file mode 100644 index 0000000..0a43713 --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService+Streams.swift @@ -0,0 +1,96 @@ +// +// ContainersService+Streams.swift +// Containers +// +// The stdio plumbing between containers and files, and waiting on a container to exit. +// +// Created by Axel Martinez on 2026/10/24. +// + +import Containerization +import Foundation + +extension ContainersService { + struct MultiWriter: Writer { + let handles: [FileHandle] + + func close() throws { + for handle in handles { + try handle.close() + } + } + + func write(_ data: Data) throws { + for handle in handles { + try handle.write(contentsOf: data) + } + } + } + + /// Answers a wait once, with whichever comes first: the container's exit, or the caller giving up on it. + final class ExitWaiter: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var answered = false + + func wait(for monitor: Task) async throws -> Int32 { + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { continuation in + lock.lock() + + // Cancelled before the wait even began. + guard !answered else { + lock.unlock() + continuation.resume(throwing: CancellationError()) + return + } + + self.continuation = continuation + + lock.unlock() + + Task { + let exitCode = await monitor.value + self.answer(with: .success(exitCode)) + } + } + } onCancel: { + answer(with: .failure(CancellationError())) + } + } + + private func answer(with result: Result) { + lock.lock() + + guard !answered else { + lock.unlock() + return + } + + answered = true + let continuation = self.continuation + self.continuation = nil + lock.unlock() + + continuation?.resume(with: result) + } + } + + struct FileHandleReader: ReaderStream { + let handle: FileHandle + + func stream() -> AsyncStream { + .init { cont in + self.handle.readabilityHandler = { handle in + let data = handle.availableData + if data.isEmpty { + handle.readabilityHandler = nil + cont.finish() + return + } + cont.yield(data) + } + } + } + } +} diff --git a/ContainerSystem/Runtime/Services/Containers/ContainersService.swift b/ContainerSystem/Runtime/Services/Containers/ContainersService.swift new file mode 100644 index 0000000..943e1db --- /dev/null +++ b/ContainerSystem/Runtime/Services/Containers/ContainersService.swift @@ -0,0 +1,269 @@ +// +// ContainersService.swift +// Containers +// +// A containers service that runs LinuxContainer. +// +// Created by Axel Martinez on 2026/02/04. +// + +import Containerization +import ContainerizationError +import ContainerizationExtras +import ContainerizationOCI +import Foundation +import Logging + +/// A sandbox-compatible containers service that runs LinuxContainer in-process. +actor ContainersService { + struct ContainerState { + var snapshot: ContainerSnapshot + var container: LinuxContainer? + var bundle: Bundle? + var exitMonitorTask: Task? + var lastExitCode: Int32? + } + + let log: Logger + let appRoot: URL + let containerRoot: URL + let imagesService: ImagesService + var containers: [String: ContainerState] = [:] + var ipAllocations: [String: UInt8] = [:] + var portForwarders: [String: PortForwarder] = [:] + /// One lock per container, so booting or stopping one never waits on another. + /// They're kept after a container is deleted: dropping a lock while a call + /// waits on it would let a new one be made for the same ID. + var containerLocks: [String: AsyncLock] = [:] + + /// Callbacks to invoke when container state changes + var stateChangeCallbacks: [@Sendable @MainActor () -> Void] = [] + + /// Register a callback to be invoked when container state changes + func addStateChangeCallback(_ callback: @escaping @Sendable @MainActor () -> Void) { + stateChangeCallbacks.append(callback) + } + + init(appRoot: URL, imagesService: ImagesService, log: Logger) throws { + let containerRoot = appRoot.appendingPathComponent("containers") + + try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true) + + self.appRoot = appRoot + self.containerRoot = containerRoot + self.imagesService = imagesService + self.log = log + self.containers = Self.loadAtBoot(root: containerRoot, log: log) + + let count = containers.count + + log.info("ContainersService initialized with \(count) existing container(s)") + } + + private static func loadAtBoot(root: URL, log: Logger) -> [String: ContainerState] { + var results = [String: ContainerState]() + + guard + let directories = try? FileManager.default.contentsOfDirectory( + at: root, + includingPropertiesForKeys: [.isDirectoryKey] + ) + else { + return results + } + + for dir in directories where dir.isDirectory { + do { + let bundle = Bundle(path: dir) + let config = try bundle.configuration + + if (try? bundle.createOptions)?.autoRemove ?? false { + log.info("Reaping auto-remove container \(config.id)") + try? bundle.delete() + continue + } + + results[config.id] = ContainerState( + snapshot: ContainerSnapshot( + configuration: config, + status: .stopped, + networks: [], + startedDate: bundle.state.startedDate + ), + container: LinuxContainer?.none, + bundle: bundle + ) + // Container restored from disk + } catch { + log.warning("Failed to load container bundle at \(dir.path): \(error)") + } + } + return results + } + + // MARK: - Internal API + + /// List containers with optional filters. + func list( + status: ContainerStatus? = nil, + labelFilter: [String: String]? = nil, + namePattern: String? = nil + ) async -> [ContainerSnapshot] { + var results = containers.values.map { $0.snapshot } + + if let status { + results = results.filter { $0.status == status } + } + + if let labelFilter { + results = results.filter { snapshot in + labelFilter.allSatisfy { key, value in + snapshot.configuration.labels[key] == value + } + } + } + + if let namePattern, !namePattern.isEmpty { + results = results.filter { snapshot in + snapshot.id.localizedCaseInsensitiveContains(namePattern) + } + } + + return results.sorted { $0.configuration.id < $1.configuration.id } + } + + func create( + configuration: ContainerConfiguration, + kernel: Kernel, + options: ContainerCreateOptions + ) async throws { + // Creating container + + guard containers[configuration.id] == nil else { + throw ContainerizationError(.exists, message: "container already exists: \(configuration.id)") + } + + let path = bundlePath(for: configuration.id) + let systemPlatform = kernel.platform + + // Get init filesystem + let initFs = try await getInitBlock(for: systemPlatform.ociPlatform()) + + // Create container bundle + let bundle = try Bundle.create( + path: path, + initialFilesystem: initFs, + kernel: kernel, + containerConfiguration: configuration, + options: options + ) + + do { + // Get container image filesystem via in-process ImagesService (no XPC) + let imageFs = try await imagesService.getImageSnapshot( + description: configuration.image, + platform: configuration.platform + ) + try bundle.cloneContainerRootFs(cloning: imageFs, readonly: configuration.readOnly) + + let snapshot = ContainerSnapshot(configuration: configuration, status: .stopped, networks: []) + + containers[configuration.id] = ContainerState( + snapshot: snapshot, + container: LinuxContainer?.none, + bundle: bundle + ) + + // Container created successfully + } catch { + log.error("Failed to create container: \(error)") + try? bundle.delete() + throw error + } + } + + // MARK: - Container State + + func containerState(for id: String) throws -> ContainerState { + guard let state = containers[id] else { + throw ContainerizationError(.notFound, message: "container with ID \(id) not found") + } + + return state + } + + /// The container's virtual machine, which only a booted container has. + func runningContainer(id: String) throws -> LinuxContainer { + guard let container = containers[id]?.container else { + throw ContainerizationError(.invalidState, message: "container not running: \(id)") + } + + return container + } + + func bundlePath(for id: String) -> URL { + containerRoot.appendingPathComponent(id) + } + + /// The lock that keeps a container's boot and stop from overlapping, which + /// would let both copy its state, wait, and write back over each other. + func lock(for id: String) -> AsyncLock { + if let lock = containerLocks[id] { + return lock + } + + let lock = AsyncLock() + containerLocks[id] = lock + return lock + } + + /// Takes the container off disk and out of the list. The caller decides + /// whether removing it is allowed and when observers hear about it. + func removeContainer(id: String) { + try? FileManager.default.removeItem(at: bundlePath(for: id)) + + releaseIP(for: id) + containers.removeValue(forKey: id) + } + + /// Whether the container asked at create time to be taken away as soon as + /// it stops, which is answered by the options kept in its bundle. + func autoRemoves(_ state: ContainerState) -> Bool { + guard let bundle = state.bundle else { return false } + + return (try? bundle.createOptions)?.autoRemove ?? false + } + + private func getInitBlock(for platform: Platform) async throws -> Filesystem { + let initImageRef: String = DefaultsStore.get(key: .defaultInitImage) + let initDescription = try await imagesService.pull( + reference: initImageRef, + platform: platform, + insecure: false, + progressUpdate: nil + ) + + try await imagesService.unpack( + description: initDescription, + platform: platform, + progressUpdate: nil + ) + + var fs = try await imagesService.getImageSnapshot( + description: initDescription, + platform: platform + ) + + fs.options = ["ro"] + return fs + } + + /// Notify all registered callbacks that container state changed + func notifyStateChange() { + for callback in stateChangeCallbacks { + Task { @MainActor in + callback() + } + } + } +} diff --git a/ContainerSystem/Services/ImagesService.swift b/ContainerSystem/Runtime/Services/ImagesService.swift similarity index 100% rename from ContainerSystem/Services/ImagesService.swift rename to ContainerSystem/Runtime/Services/ImagesService.swift diff --git a/ContainerSystem/Services/KernelService.swift b/ContainerSystem/Runtime/Services/KernelService.swift similarity index 100% rename from ContainerSystem/Services/KernelService.swift rename to ContainerSystem/Runtime/Services/KernelService.swift diff --git a/ContainerSystem/Runtime/Services/ReportsService.swift b/ContainerSystem/Runtime/Services/ReportsService.swift new file mode 100644 index 0000000..c2741af --- /dev/null +++ b/ContainerSystem/Runtime/Services/ReportsService.swift @@ -0,0 +1,109 @@ +// +// ReportsService.swift +// Containers +// +// Keeps the reports of failed work. +// +// Created by Axel Martinez on 24/10/2026. +// + +import Foundation +import Logging + +/// Service for the reports generated from tasks, kept in a `ReportStore` under the app root. +actor ReportsService { + private static let folderName = "reports" + + private let log: Logger + private let store: ReportStore + + /// Callbacks to invoke with the reports, most recent first, whenever they change. + private var changeCallbacks: [@Sendable @MainActor ([Report]) -> Void] = [] + + init(appRoot: URL, log: Logger) throws { + self.log = log + self.store = try ReportStore(root: appRoot.appendingPathComponent(Self.folderName)) + } + + @discardableResult + func record( + level: Report.Level, + kind: Report.Kind, + name: String, + message: String, + body: String, + startedAt: Date? + ) async throws -> Report { + let report = try await store.record( + level: level, + kind: kind, + name: name, + message: message, + body: body, + startedAt: startedAt + ) + + await notifyChange() + + return report + } + + /// Register a callback to be invoked with the reports whenever they change. + func addChangeCallback(_ callback: @escaping @Sendable @MainActor ([Report]) -> Void) { + changeCallbacks.append(callback) + } + + /// Most recent first. + func list() async -> [Report] { + await store.list() + } + + func get(id: String) async -> Report? { + await store.entry(for: id) + } + + func body(of id: String) async throws -> String { + try await store.body(of: id) + } + + func markRead(_ ids: [String]) async { + guard !ids.isEmpty else { return } + + await store.markRead(ids) + await notifyChange() + } + + func delete(ids: [String]) async { + guard !ids.isEmpty else { return } + + await store.remove(ids) + await notifyChange() + } + + /// Deletes the reports about things that no longer exist, such as deleted images. + /// + /// - Parameters: + /// - names: The names of what the work was on. + /// - kinds: Every kind of report they can have. + func delete(named names: [String], ofKind kinds: Set) async { + let names = Set(names) + let ids = await store.list() + .filter { kinds.contains($0.kind) && names.contains($0.name) } + .map(\.id) + + await delete(ids: ids) + } + + nonisolated func url(for id: String) -> URL { + store.url(for: id) + } + + /// Awaited rather than scheduled, so callers find the reports updated as soon as a change returns. + private func notifyChange() async { + let reports = await store.list() + + for callback in changeCallbacks { + await callback(reports) + } + } +} diff --git a/ContainerSystem/Services/ContainersService.swift b/ContainerSystem/Services/ContainersService.swift deleted file mode 100644 index 0c83046..0000000 --- a/ContainerSystem/Services/ContainersService.swift +++ /dev/null @@ -1,975 +0,0 @@ -// -// ContainersService.swift -// Containers -// -// A containers service that runs LinuxContainer. -// -// Created by Axel Martinez on 2026/02/04. -// - -import Containerization -import ContainerizationError -import ContainerizationExtras -import ContainerizationOCI -import ContainerizationOS -import Foundation -import Logging -import SystemPackage - -private struct MultiWriter: Writer { - let handles: [FileHandle] - - func close() throws { - for handle in handles { - try handle.close() - } - } - - func write(_ data: Data) throws { - for handle in handles { - try handle.write(contentsOf: data) - } - } -} - -/// Answers a wait once, with whichever comes first: the container's exit, or the caller giving up on it. -private final class ExitWaiter: @unchecked Sendable { - private let lock = NSLock() - private var continuation: CheckedContinuation? - private var answered = false - - func wait(for monitor: Task) async throws -> Int32 { - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { continuation in - lock.lock() - - // Cancelled before the wait even began. - guard !answered else { - lock.unlock() - continuation.resume(throwing: CancellationError()) - return - } - - self.continuation = continuation - - lock.unlock() - - Task { - let exitCode = await monitor.value - self.answer(with: .success(exitCode)) - } - } - } onCancel: { - answer(with: .failure(CancellationError())) - } - } - - private func answer(with result: Result) { - lock.lock() - - guard !answered else { - lock.unlock() - return - } - - answered = true - let continuation = self.continuation - self.continuation = nil - lock.unlock() - - continuation?.resume(with: result) - } -} - -private struct FileHandleReader: ReaderStream { - let handle: FileHandle - - func stream() -> AsyncStream { - .init { cont in - self.handle.readabilityHandler = { handle in - let data = handle.availableData - if data.isEmpty { - handle.readabilityHandler = nil - cont.finish() - return - } - cont.yield(data) - } - } - } -} - -extension Filesystem { - fileprivate var asMount: Containerization.Mount { - switch self.type { - case .tmpfs: - return .any( - type: "tmpfs", - source: self.source, - destination: self.destination, - options: self.options - ) - case .virtiofs: - return .share( - source: self.source, - destination: self.destination, - options: self.options - ) - case .block(let format, _, _): - return .block( - format: format, - source: self.source, - destination: self.destination, - options: self.options - ) - case .volume(_, let format, _, _): - return .block( - format: format, - source: self.source, - destination: self.destination, - options: self.options - ) - } - } - - fileprivate func isSocket() throws -> Bool { - if !self.isVirtiofs { - return false - } - let info = try File.info(self.source) - - return info.isSocket - } -} - -/// A sandbox-compatible containers service that runs LinuxContainer in-process. -actor ContainersService { - private struct ContainerState { - var snapshot: ContainerSnapshot - var container: LinuxContainer? - var bundle: Bundle? - var exitMonitorTask: Task? - var lastExitCode: Int32? - } - - private let log: Logger - private let appRoot: URL - private let containerRoot: URL - private let imagesService: ImagesService - private var containers: [String: ContainerState] = [:] - private var ipAllocations: [String: UInt8] = [:] - private var portForwarders: [String: PortForwarder] = [:] - private let containerLock = AsyncLock() - - /// Callbacks to invoke when container state changes - private var stateChangeCallbacks: [@Sendable @MainActor () -> Void] = [] - - /// Register a callback to be invoked when container state changes - func addStateChangeCallback(_ callback: @escaping @Sendable @MainActor () -> Void) { - stateChangeCallbacks.append(callback) - } - - init(appRoot: URL, imagesService: ImagesService, log: Logger) throws { - let containerRoot = appRoot.appendingPathComponent("containers") - - try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true) - - self.appRoot = appRoot - self.containerRoot = containerRoot - self.imagesService = imagesService - self.log = log - self.containers = Self.loadAtBoot(root: containerRoot, log: log) - - let count = containers.count - - log.info("ContainersService initialized with \(count) existing container(s)") - } - - private static func loadAtBoot(root: URL, log: Logger) -> [String: ContainerState] { - var results = [String: ContainerState]() - - guard - let directories = try? FileManager.default.contentsOfDirectory( - at: root, - includingPropertiesForKeys: [.isDirectoryKey] - ) - else { - return results - } - - for dir in directories where dir.isDirectory { - do { - let bundle = Bundle(path: dir) - let config = try bundle.configuration - - if (try? bundle.createOptions)?.autoRemove ?? false { - log.info("Reaping auto-remove container \(config.id)") - try? bundle.delete() - continue - } - - results[config.id] = ContainerState( - snapshot: ContainerSnapshot( - configuration: config, - status: .stopped, - networks: [], - startedDate: bundle.state.startedDate - ), - container: LinuxContainer?.none, - bundle: bundle - ) - // Container restored from disk - } catch { - log.warning("Failed to load container bundle at \(dir.path): \(error)") - } - } - return results - } - - // MARK: - Internal API - - func list() async -> [ContainerSnapshot] { - containers.values.map { $0.snapshot }.sorted { - $0.configuration.id < $1.configuration.id - } - } - - /// List containers with optional filters. - func list( - status: ContainerStatus? = nil, - labelFilter: [String: String]? = nil, - namePattern: String? = nil - ) async -> [ContainerSnapshot] { - var results = containers.values.map { $0.snapshot } - - if let status { - results = results.filter { $0.status == status } - } - - if let labelFilter { - results = results.filter { snapshot in - labelFilter.allSatisfy { key, value in - snapshot.configuration.labels[key] == value - } - } - } - - if let namePattern, !namePattern.isEmpty { - results = results.filter { snapshot in - snapshot.id.localizedCaseInsensitiveContains(namePattern) - } - } - - return results.sorted { $0.configuration.id < $1.configuration.id } - } - - func create( - configuration: ContainerConfiguration, - kernel: Kernel, - options: ContainerCreateOptions - ) async throws { - // Creating container - - guard containers[configuration.id] == nil else { - throw ContainerizationError(.exists, message: "container already exists: \(configuration.id)") - } - - let path = containerRoot.appendingPathComponent(configuration.id) - let systemPlatform = kernel.platform - - // Get init filesystem - let initFs = try await getInitBlock(for: systemPlatform.ociPlatform()) - - // Create container bundle - let bundle = try Bundle.create( - path: path, - initialFilesystem: initFs, - kernel: kernel, - containerConfiguration: configuration, - options: options - ) - - do { - // Get container image filesystem via in-process ImagesService (no XPC) - let imageFs = try await imagesService.getImageSnapshot( - description: configuration.image, - platform: configuration.platform - ) - try bundle.cloneContainerRootFs(cloning: imageFs, readonly: configuration.readOnly) - - let snapshot = ContainerSnapshot(configuration: configuration, status: .stopped, networks: []) - - containers[configuration.id] = ContainerState( - snapshot: snapshot, - container: LinuxContainer?.none, - bundle: bundle - ) - - // Container created successfully - } catch { - log.error("Failed to create container: \(error)") - try? bundle.delete() - throw error - } - } - - func bootstrap(id: String, stdio: [FileHandle?]) async throws { - try await containerLock.withLock { _ in - try await self._bootstrap(id: id, stdio: stdio) - } - } - - private func _bootstrap(id: String, stdio: [FileHandle?]) async throws { - guard var state = containers[id] else { - throw ContainerizationError(.notFound, message: "container with ID \(id) not found") - } - - // Already bootstrapped - if state.container != nil { - return - } - - let previousStatus = state.snapshot.status - var hasBooted = false - - // Shown while the virtual machine boots, which is most of a start. - state.snapshot.status = .starting - containers[id] = state - notifyStateChange() - - defer { - if !hasBooted { - containers[id]?.snapshot.status = previousStatus - notifyStateChange() - } - } - - let bundle: ContainerSystem.Bundle - - if let existingBundle = state.bundle { - bundle = existingBundle - } else { - let path = containerRoot.appendingPathComponent(id) - bundle = Bundle(path: path) - } - - let config = try bundle.configuration - let bundleKernel = try bundle.kernel - let initMount = await MainActor.run { - bundle.initialFilesystem.asMount - } - let vmm = VZVirtualMachineManager( - kernel: bundleKernel, - initialFilesystem: initMount, - rosetta: config.rosetta, - logger: self.log - ) - - // Create the log file for container stdio - let containerLogURL = bundle.path.appendingPathComponent("stdio.log") - - do { - let fd = Darwin.open(containerLogURL.path, O_CREAT | O_RDONLY | O_TRUNC, 0o644) - guard fd >= 0 else { - throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO) - } - Darwin.close(fd) - } - - // Set up stdio writers - let containerLog = try FileHandle(forWritingTo: containerLogURL) - let stdout: MultiWriter = { - if let h = stdio[1] { - return MultiWriter(handles: [h, containerLog]) - } - return MultiWriter(handles: [containerLog]) - }() - - let stderr: MultiWriter? = { - if !config.initProcess.terminal { - if let h = stdio[2] { - return MultiWriter(handles: [h, containerLog]) - } - return MultiWriter(handles: [containerLog]) - } - return nil - }() - - let stdin: FileHandleReader? = { - if let handle = stdio[0] { - return FileHandleReader(handle: handle) - } - return nil - }() - - let rootfs = try await MainActor.run { - try bundle.containerRootfs.asMount - } - - // Precompute mounts and sockets - var precomputedMounts: [Containerization.Mount] = [] - var precomputedSockets: [UnixSocketConfiguration] = [] - - for mount in config.mounts { - if try await MainActor.run(body: { try mount.isSocket() }) { - let socket = UnixSocketConfiguration( - source: URL(filePath: mount.source), - destination: URL(filePath: mount.destination) - ) - precomputedSockets.append(socket) - } else { - let mnt = await MainActor.run { mount.asMount } - precomputedMounts.append(mnt) - } - } - - // Allocate IP before the closure (actor-isolated state) - let (ip, gw) = try allocateIP(for: id) - - let container = try LinuxContainer(id, rootfs: rootfs, vmm: vmm, logger: self.log) { czConfig in - try Self.configureContainer( - czConfig: &czConfig, - config: config, - precomputedMounts: precomputedMounts, - precomputedSockets: precomputedSockets - ) - - // Configure NATInterface (IsolatedInterfaceStrategy pattern) - czConfig.interfaces = [try NATInterface(ipv4Address: CIDRv4(ip), ipv4Gateway: IPv4Address(gw))] - - // Do not set hosts configuration - causes I/O errors when framework tries to write /etc/hosts - // The framework will handle hosts automatically - - czConfig.process.stdout = stdout - czConfig.process.stderr = stderr - czConfig.process.stdin = stdin - - // The console is the only account of a boot that never reaches the - // container process, which is when stdio stays empty. - czConfig.bootLog = .file(path: bundle.bootLog, append: true) - } - - do { - try await container.create() - - state.container = container - state.bundle = bundle - state.snapshot.networks = [ - Attachment( - network: "nat", - hostname: id, - ipv4Address: try CIDRv4(ip), - ipv4Gateway: try IPv4Address(gw), - ipv6Address: CIDRv6?.none, - macAddress: MACAddress?.none - ) - ] - containers[id] = state - hasBooted = true - - // Notify observers that networks have been assigned - notifyStateChange() - } catch { - log.error("Failed to bootstrap container \(id): \(error)") - releaseIP(for: id) - throw error - } - } - - func startProcess(id: String, processID: String) async throws { - // Starting process in container - - guard var state = containers[id] else { - throw ContainerizationError(.notFound, message: "container with ID \(id) not found") - } - - let isInit = id == processID - if state.snapshot.status == .running && isInit { - return - } - - guard let container = state.container else { - throw ContainerizationError(.invalidState, message: "container not bootstrapped: \(id)") - } - - do { - try await container.start() - } catch { - if isInit { - // Booted, but it never got as far as running. - containers[id]?.snapshot.status = .stopped - notifyStateChange() - } - - throw error - } - // Container init process started - - if isInit { - let startedDate = Date() - - state.snapshot.status = .running - state.snapshot.startedDate = startedDate - - // Kept on disk so the container still reports when it last ran - // after the app has been quit and reopened. - do { - try state.bundle?.setState(Bundle.State(startedDate: startedDate)) - } catch { - log.warning("Failed to record start date for container \(id): \(error)") - } - - // Start port forwarding for published ports - let config = state.snapshot.configuration - if !config.publishedPorts.isEmpty { - let forwarder = PortForwarder(log: self.log) - for port in config.publishedPorts { - do { - try await forwarder.startForwarding(publishPort: port, container: container) - } catch { - log.warning("Failed to start port forwarding for \(port.hostPort) -> \(port.containerPort): \(error)") - } - } - portForwarders[id] = forwarder - } - - // Monitor container exit in background - let logger = self.log - - state.exitMonitorTask = Task { [weak self] in - var exitCode: Int32 = 0 - do { - exitCode = try await container.wait().exitCode - } catch { - logger.error("Error waiting for container \(id): \(error)") - } - await self?.handleContainerExit(id: id, exitCode: exitCode) - return exitCode - } - - containers[id] = state - - // Notify observers that container started - notifyStateChange() - } - } - - /// Waits for the container's init process to exit and returns its code. - func wait(id: String) async throws -> Int32 { - guard let state = containers[id] else { - throw ContainerizationError(.notFound, message: "container with ID \(id) not found") - } - - // A container that exited before anyone waited on it has already torn - // down its monitor, so the code it left behind is all there is. - guard let monitor = state.exitMonitorTask else { - return state.lastExitCode ?? 0 - } - - return try await ExitWaiter().wait(for: monitor) - } - - /// What each running container is using right now. A container that - /// cannot say, because it is on its way down, is left out. - func resourceUsage() async -> [ContainerResourceUsage] { - // Taken before the first await: the actor can change underneath it. - let running = containers.compactMap { id, state in - state.snapshot.status == .running - ? state.container.map { (id, $0) } : nil - } - - var usage: [ContainerResourceUsage] = [] - - for (id, container) in running { - guard - let stats = try? await container.statistics(categories: [.memory, .cpu]) - else { - continue - } - - let entry = ContainerResourceUsage( - id: id, - memoryBytes: stats.memory?.usageBytes ?? 0, - cpuUsageMicroseconds: stats.cpu?.usageUsec ?? 0 - ) - - usage.append(entry) - } - - return usage - } - - func stop(id: String, options: ContainerStopOptions) async throws { - try await containerLock.withLock { _ in - try await self._stop(id: id, options: options) - } - } - - private func _stop(id: String, options: ContainerStopOptions) async throws { - guard var state = containers[id] else { - throw ContainerizationError(.notFound, message: "container with ID \(id) not found") - } - - if let container = state.container { - // Shown while the container winds down, which can last until the stop timeout. - containers[id]?.snapshot.status = .stopping - notifyStateChange() - - do { - try await gracefulStopContainer(container, stopOpts: options) - } catch let err as ContainerizationError { - if err.code != .interrupted { - // It is still running, as far as anyone can tell. - containers[id]?.snapshot.status = state.snapshot.status - notifyStateChange() - throw err - } - } catch { - log.error("Error during graceful stop of container \(id): \(error)") - } - } - - state.exitMonitorTask?.cancel() - state.exitMonitorTask = nil - state.snapshot.status = .stopped - state.snapshot.networks = [] - state.container = nil - releaseIP(for: id) - - // Stop port forwarding - if let forwarder = portForwarders.removeValue(forKey: id) { - await forwarder.stopAll() - } - - containers[id] = state - - if autoRemoves(state) { - removeContainer(id: id) - } - - // Notify observers that container stopped - notifyStateChange() - } - - func delete(id: String) async throws { - guard let state = containers[id] else { - throw ContainerizationError(.notFound, message: "container with ID \(id) not found") - } - - if state.snapshot.status == .running { - throw ContainerizationError(.invalidState, message: "cannot delete running container") - } - - removeContainer(id: id) - notifyStateChange() - } - - /// Takes the container off disk and out of the list. The caller decides - /// whether removing it is allowed and when observers hear about it. - private func removeContainer(id: String) { - let path = containerRoot.appendingPathComponent(id) - try? FileManager.default.removeItem(at: path) - - releaseIP(for: id) - containers.removeValue(forKey: id) - } - - /// Whether the container asked at create time to be taken away as soon as - /// it stops, which is answered by the options kept in its bundle. - private func autoRemoves(_ state: ContainerState) -> Bool { - guard let bundle = state.bundle else { return false } - - return (try? bundle.createOptions)?.autoRemove ?? false - } - - /// Execute a command in a running container and return its output (uses vsock, no networking needed). - func exec(id: String, arguments: [String]) async throws -> String { - guard let state = containers[id], let container = state.container else { - throw ContainerizationError(.invalidState, message: "container not running: \(id)") - } - - let outputURL = containerRoot.appendingPathComponent("\(id)-exec-output.tmp") - - FileManager.default.createFile(atPath: outputURL.path, contents: nil) - - let outputHandle = try FileHandle(forWritingTo: outputURL) - let writer = MultiWriter(handles: [outputHandle]) - - let process = try await container.exec("exec-\(UUID().uuidString)") { config in - config.arguments = arguments - config.stdout = writer - config.stderr = writer - } - - try await process.start() - - let exitStatus = try await process.wait() - - try? writer.close() - - let output = (try? String(contentsOf: outputURL, encoding: .utf8)) ?? "" - - try? FileManager.default.removeItem(at: outputURL) - - if exitStatus.exitCode != 0 { - let message = "command failed with exit code \(exitStatus.exitCode): \(output)" - throw ContainerizationError(.internalError, message: message) - } - - return output - } - - func dial(id: String, port: UInt32) async throws -> FileHandle { - guard let state = containers[id], let container = state.container else { - throw ContainerizationError(.invalidState, message: "container not running: \(id)") - } - - // Dialing vsock port - return try await container.dialVsock(port: port) - } - - // MARK: - IP Allocation - - private func allocateIP(for id: String) throws -> (address: String, gateway: String) { - if let existing = ipAllocations[id] { - return (address: "192.168.64.\(existing)/24", gateway: "192.168.64.1") - } - for i: UInt8 in 2...254 { - if !ipAllocations.values.contains(i) { - ipAllocations[id] = i - return (address: "192.168.64.\(i)/24", gateway: "192.168.64.1") - } - } - throw ContainerizationError(.internalError, message: "no available IP addresses") - } - - private func releaseIP(for id: String) { - ipAllocations.removeValue(forKey: id) - } - - // MARK: - Private Methods - - private func handleContainerExit(id: String, exitCode: Int32) { - guard var state = containers[id] else { - log.warning("Container \(id) not found during exit handling") - return - } - state.lastExitCode = exitCode - state.snapshot.status = .stopped - state.snapshot.networks = [] - state.container = nil - state.exitMonitorTask?.cancel() - state.exitMonitorTask = nil - releaseIP(for: id) - - // Stop port forwarding - if let forwarder = portForwarders.removeValue(forKey: id) { - Task { await forwarder.stopAll() } - } - - containers[id] = state - - if autoRemoves(state) { - removeContainer(id: id) - } - - notifyStateChange() - } - - private func gracefulStopContainer(_ lc: LinuxContainer, stopOpts: ContainerStopOptions) async throws { - // Try to gracefully shut down the process, then force-stop the VM. - do { - _ = try await withThrowingTaskGroup(of: ExitStatus.self) { group in - group.addTask { - try await lc.wait() - } - group.addTask { - try await lc.kill(Signal(rawValue: stopOpts.signal)) - try await Task.sleep(for: .seconds(stopOpts.timeoutInSeconds)) - try await lc.kill(Signal(rawValue: SIGKILL)) - return ExitStatus(exitCode: 137) - } - guard let code = try await group.next() else { - throw ContainerizationError( - .internalError, - message: "failed to get exit code from gracefully stopping container" - ) - } - group.cancelAll() - return code - } - } catch { - log.notice("graceful stop failed, forcing: \(error)") - } - - // Bring down the VM - try await lc.stop() - } - - private static func configureContainer( - czConfig: inout LinuxContainer.Configuration, - config: ContainerConfiguration, - precomputedMounts: [Containerization.Mount], - precomputedSockets: [UnixSocketConfiguration] - ) throws { - czConfig.cpus = config.resources.cpus - czConfig.memoryInBytes = config.resources.memoryInBytes - czConfig.sysctl = config.sysctls - czConfig.virtualization = config.virtualization - - czConfig.mounts.append(contentsOf: precomputedMounts) - czConfig.sockets.append(contentsOf: precomputedSockets) - - for publishedSocket in config.publishedSockets { - let socketConfig = UnixSocketConfiguration( - source: publishedSocket.containerPath, - destination: publishedSocket.hostPath, - permissions: publishedSocket.permissions, - direction: .outOf - ) - czConfig.sockets.append(socketConfig) - } - - if config.ssh, let sshSocket = Foundation.ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] { - let socketUrl = URL(fileURLWithPath: sshSocket) - let socketPath = socketUrl.path(percentEncoded: false) - let attrs = try? FileManager.default.attributesOfItem(atPath: socketPath) - let permissions = (attrs?[.posixPermissions] as? NSNumber) - .map { FilePermissions(rawValue: mode_t($0.intValue)) } - let socketConfig = UnixSocketConfiguration( - source: socketUrl, - destination: URL(fileURLWithPath: "/run/host-services/ssh-auth.sock"), - permissions: permissions, - direction: .into - ) - czConfig.sockets.append(socketConfig) - } - - czConfig.hostname = config.id - - // Only set DNS if explicitly provided by container configuration - // Setting DNS causes the framework to write /etc/resolv.conf which fails on read-only rootfs - // If not set, containers will use the host's DNS via the VM network - if let dns = config.dns, !dns.nameservers.isEmpty { - czConfig.dns = DNS( - nameservers: dns.nameservers, - domain: dns.domain, - searchDomains: dns.searchDomains, - options: dns.options - ) - } - - try Self.configureInitialProcess(czConfig: &czConfig, config: config) - } - - private static func configureInitialProcess( - czConfig: inout LinuxContainer.Configuration, - config: ContainerConfiguration - ) throws { - let process = config.initProcess - - czConfig.process.arguments = [process.executable] + process.arguments - czConfig.process.environmentVariables = process.environment - czConfig.process.capabilities = try capabilities(from: config.capabilities) - - if config.ssh, Foundation.ProcessInfo.processInfo.environment["SSH_AUTH_SOCK"] != nil { - let sshEnvVar = "SSH_AUTH_SOCK" - let sshGuestPath = "/run/host-services/ssh-auth.sock" - - if !czConfig.process.environmentVariables.contains(where: { - $0.starts(with: "\(sshEnvVar)=") - }) { - czConfig.process.environmentVariables.append("\(sshEnvVar)=\(sshGuestPath)") - } - } - - czConfig.process.terminal = process.terminal - czConfig.process.workingDirectory = process.workingDirectory - czConfig.process.rlimits = process.rlimits.compactMap { - guard let kind = try? LinuxRLimit.Kind($0.limit) else { return nil } - return .init(kind: kind, hard: $0.hard, soft: $0.soft) - } - - switch process.user { - case .raw(let name): - czConfig.process.user = .init( - uid: 0, - gid: 0, - umask: nil, - additionalGids: process.supplementalGroups, - username: name - ) - case .id(let uid, let gid): - czConfig.process.user = .init( - uid: uid, - gid: gid, - umask: nil, - additionalGids: process.supplementalGroups, - username: "" - ) - } - } - - private static func capabilities(from names: [String]) throws -> Containerization.LinuxCapabilities { - let capabilities = try capabilitySet(from: names) - - guard !capabilities.isEmpty else { - return .allCapabilities - } - - return Containerization.LinuxCapabilities(capabilities: Array(capabilities)) - } - - private static func capabilitySet(from names: [String]) throws -> Set { - var capabilities: Set = [] - - for name in names { - let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines) - - guard !trimmedName.isEmpty else { - continue - } - - if trimmedName.uppercased() == "ALL" { - capabilities.formUnion(CapabilityName.allCases) - } else { - capabilities.insert(try CapabilityName(rawValue: trimmedName)) - } - } - - return capabilities - } - - private func getInitBlock(for platform: Platform) async throws -> Filesystem { - let initImageRef: String = DefaultsStore.get(key: .defaultInitImage) - let initDescription = try await imagesService.pull( - reference: initImageRef, - platform: platform, - insecure: false, - progressUpdate: nil - ) - - try await imagesService.unpack( - description: initDescription, - platform: platform, - progressUpdate: nil - ) - - var fs = try await imagesService.getImageSnapshot( - description: initDescription, - platform: platform - ) - - fs.options = ["ro"] - return fs - } - - /// Notify all registered callbacks that container state changed - private func notifyStateChange() { - for callback in stateChangeCallbacks { - Task { @MainActor in - callback() - } - } - } -} diff --git a/ContainerSystemTests/Mocks/MockContainerRuntime.swift b/ContainerSystemTests/Mocks/MockContainerRuntime.swift index ddac28b..def05be 100644 --- a/ContainerSystemTests/Mocks/MockContainerRuntime.swift +++ b/ContainerSystemTests/Mocks/MockContainerRuntime.swift @@ -28,6 +28,7 @@ final class MockContainerRuntime: ContainerRuntime { private var mockContainersService: ContainersService? private var mockImagesService: ImagesService? private var mockKernelService: KernelService? + private var mockReportsService: ReportsService? private var mockContentStore: ContentStore? init() { @@ -69,6 +70,17 @@ final class MockContainerRuntime: ContainerRuntime { return service } + override func getReportsService() throws -> ReportsService { + guard let service = mockReportsService else { + throw ContainerizationError( + .internalError, + message: "Reports service not initialized" + ) + } + + return service + } + override func getContentStore() throws -> ContentStore { guard let store = mockContentStore else { throw ContainerizationError( @@ -104,6 +116,14 @@ final class MockContainerRuntime: ContainerRuntime { // Set appRoot so getAppRoot() works self.appRoot = appRoot + let reports = try ReportsService(appRoot: appRoot, log: logger) + + await reports.addChangeCallback { @MainActor [weak self] reports in + self?.reports = reports + } + + self.mockReportsService = reports + // Create stores — these are filesystem-only and safe in test hosts let localContentStore = try LocalContentStore( path: imagesRoot.appendingPathComponent("content") @@ -152,6 +172,7 @@ final class MockContainerRuntime: ContainerRuntime { mockContainersService = nil mockImagesService = nil mockKernelService = nil + mockReportsService = nil mockContentStore = nil isRunning = false diff --git a/ContainerSystemTests/ReportManagerTests.swift b/ContainerSystemTests/ReportManagerTests.swift new file mode 100644 index 0000000..71debca --- /dev/null +++ b/ContainerSystemTests/ReportManagerTests.swift @@ -0,0 +1,74 @@ +// +// ReportManagerTests.swift +// ContainerSystemTests +// +// Recording reports, and keeping the runtime's list in step with the store. +// + +import Foundation +import Testing + +@testable import ContainerSystem + +@Suite("Report manager") +@MainActor +struct ReportManagerTests { + private struct Failure: Error {} + + private func makeManager(in directory: TemporaryDirectory) async throws -> ReportManager { + let runtime = MockContainerRuntime() + + try await SystemManager(testRuntime: runtime).start(appRoot: directory.url) + + return ReportManager(testRuntime: runtime) + } + + @Test("Recorded report comes first") + func recordedReportComesFirst() async throws { + let directory = try TemporaryDirectory() + + defer { directory.remove() } + + let manager = try await makeManager(in: directory) + + await manager.record(kind: .image, name: "alpine", message: "The pull failed.", error: Failure()) + let latest = try #require( + await manager.record(kind: .build, name: "nginx", message: "The build failed.", error: Failure()) + ) + + #expect(manager.reports.first == latest) + #expect(manager.reports.count == 2) + #expect(manager.unreadCount == 2) + } + + @Test("Marking read updates the list and the store") + func markingReadUpdatesListAndStore() async throws { + let directory = try TemporaryDirectory() + + defer { directory.remove() } + + let manager = try await makeManager(in: directory) + let report = try #require( + await manager.record(kind: .container, name: "web", message: "The container stopped.", error: Failure()) + ) + + await manager.markRead([report.id]) + + #expect(manager.isRead(report.id)) + #expect(manager.unreadCount == 0) + + await manager.refresh() + + #expect(manager.isRead(report.id)) + } + + @Test("Stopped system records nothing") + func stoppedSystemRecordsNothing() async { + let manager = ReportManager(testRuntime: MockContainerRuntime()) + + let report = await manager.record(kind: .image, name: "alpine", message: "The pull failed.", error: Failure()) + + #expect(report == nil) + #expect(manager.reports.isEmpty) + } +} diff --git a/ContainerSystemTests/VolumeManagerTests.swift b/ContainerSystemTests/VolumeManagerTests.swift index 2ccb674..c6eb386 100644 --- a/ContainerSystemTests/VolumeManagerTests.swift +++ b/ContainerSystemTests/VolumeManagerTests.swift @@ -168,4 +168,28 @@ struct VolumeManagerTests { let volumes = try await manager.list() #expect(!volumes.contains(where: { $0.name == volumeName })) } + + @Test("Delete removes the volume's reports") + @MainActor + func deleteRemovesVolumeReports() async throws { + struct Failure: Error {} + + let (_, testRuntime) = try await setupTestSystem() + + let volumeName = "test-volume-\(UUID().uuidString)" + let manager = VolumeManager(testRuntime: testRuntime) + let reportManager = ReportManager(testRuntime: testRuntime) + + let volume = try await manager.create( + name: volumeName, + labels: [], + options: [], + sizeInBytes: 1024 * 1024 + ) + + await reportManager.record(kind: .volume, name: volumeName, message: "The volume failed.", error: Failure()) + try await manager.delete(volumes: [volume]) + + #expect(reportManager.reports.isEmpty) + } } diff --git a/Containers/Controllers/DashboardToolbarController.swift b/Containers/Controllers/DashboardToolbarController.swift index aef444a..5abb4c3 100644 --- a/Containers/Controllers/DashboardToolbarController.swift +++ b/Containers/Controllers/DashboardToolbarController.swift @@ -44,6 +44,22 @@ final class DashboardToolbarController: NSObject { /// Shown under the toolbar, in the titlebar. var accessory: AnyView? + /// The handlers and views capture the view that keeps this controller in + /// its state, so they have to go once that view does, or neither is ever freed. + func releaseHandlers() { + onDeleteSearchTokens = { _ in } + onChooseSearchTokenOption = { _, _ in } + onSubmitSearch = nil + onToggleFilter = { _ in } + onAdd = {} + onClear = {} + onSelectionItem = { _ in } + onSearch = { _ in } + addTip = nil + runTip = nil + accessory = nil + } + static let filterIdentifier = NSToolbarItem.Identifier("filter") static let addIdentifier = NSToolbarItem.Identifier("add") static let clearIdentifier = NSToolbarItem.Identifier("clear") diff --git a/Containers/Controllers/DetailToolbarController.swift b/Containers/Controllers/DetailToolbarController.swift index 888c174..209a922 100644 --- a/Containers/Controllers/DetailToolbarController.swift +++ b/Containers/Controllers/DetailToolbarController.swift @@ -61,20 +61,28 @@ final class DetailToolbarController: NSObject, NSToolbarDelegate { window.toolbarStyle = .unified // Labels are usually wider than the icons, so the tabs are rebuilt. + // Weak: the observation is kept on this controller. displayModeObservation = toolbar.observe( \.displayMode, options: [.initial, .new] - ) { toolbar, _ in + ) { [weak self] toolbar, _ in MainActor.assumeIsolated { UserDefaults.standard.set( toolbar.displayMode.rawValue, forKey: Self.displayModeKey ) - self.scheduleTabRebuild() + self?.scheduleTabRebuild() } } } + /// The handlers capture the view that keeps this controller in its state, + /// so they have to go once that view does, or neither is ever freed. + func releaseHandlers() { + items = [] + onSelectTab = { _ in } + } + /// Returns once the toolbar is installed and done resizing, or on timeout. /// It lands a turn after the view, so sizing earlier leaves the window short. func whenSettled(timeout: Duration) async { diff --git a/Containers/Controllers/ReportToolbarController.swift b/Containers/Controllers/ReportToolbarController.swift index c97793f..8f92573 100644 --- a/Containers/Controllers/ReportToolbarController.swift +++ b/Containers/Controllers/ReportToolbarController.swift @@ -32,6 +32,12 @@ final class ReportToolbarController: NSObject, NSToolbarDelegate { window.toolbarStyle = .unified } + /// The handler captures the view that keeps this controller in its state, + /// so it has to go once that view does, or neither is ever freed. + func releaseHandlers() { + onSearch = { _ in } + } + private var identifiers: [NSToolbarItem.Identifier] { [.flexibleSpace, Self.searchIdentifier] } diff --git a/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift b/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift index e5ddd77..e56405b 100644 --- a/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift +++ b/Containers/Extensions/ContainerSystem/SystemManager.Status+Message.swift @@ -23,11 +23,11 @@ extension SystemManager.Status { /// Names the system, since the menu bar has no window around it to say which. var menuMessage: String { switch self { - case .running: "Container System is running" - case .starting: "Container System is starting…" - case .stopping: "Container System is stopping…" - case .notStarted: "Container System is stopped" - case .failed: "Container System failed to start" + case .running: "Container system is running" + case .starting: "Container system is starting…" + case .stopping: "Container system is stopping…" + case .notStarted: "Container system is stopped" + case .failed: "Container system failed to start" } } diff --git a/Containers/Extensions/SwiftUI/TextField+Suggestions.swift b/Containers/Extensions/SwiftUI/TextField+Suggestions.swift index 2d92a4d..3b9f5d4 100644 --- a/Containers/Extensions/SwiftUI/TextField+Suggestions.swift +++ b/Containers/Extensions/SwiftUI/TextField+Suggestions.swift @@ -5,34 +5,43 @@ // Created by Axel Martinez on 01/08/2026. // -import Combine import SwiftUI extension TextField { - /// Suggests completions for `text` once typing stops; `nil` cancels and closes the menu. + /// Suggests completions for `text` once typing stops, while `isEnabled`, such as while the field has focus. /// On `TextField`, so it must come first in the modifier chain. func suggestions( - for text: String?, + for text: String, + isEnabled: Bool, fetch: @escaping @Sendable (String) async throws -> [String] ) -> some View { - modifier(TextFieldSuggestions(text: text, fetch: fetch)) + modifier(TextFieldSuggestions(text: text, isEnabled: isEnabled, fetch: fetch)) } } private struct TextFieldSuggestions: ViewModifier { - let text: String? + private static let debounce: Duration = .milliseconds(300) + + let text: String + let isEnabled: Bool let fetch: @Sendable (String) async throws -> [String] - @SwiftUI.State private var resolver = SuggestionResolver() + @SwiftUI.State private var suggestions: [String] = [] + @SwiftUI.State private var isLoading = false + + /// Set when the last lookup failed, as opposed to matching nothing. + @SwiftUI.State private var failure: String? + + @SwiftUI.State private var cache = SuggestionCache() func body(content: Content) -> some View { content .overlay(alignment: .trailing) { - if resolver.isLoading { + if isLoading { ProgressView() .controlSize(.small) .padding(.trailing, 6) - } else if let failure = resolver.failure { + } else if let failure { // An empty menu otherwise reads as "nothing matched". Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) @@ -42,83 +51,32 @@ private struct TextFieldSuggestions: ViewModifier { } } .textInputSuggestions { - ForEach(resolver.suggestions, id: \.self) { suggestion in + ForEach(suggestions, id: \.self) { suggestion in Text(suggestion) .textInputCompletion(suggestion) } } - .onChange(of: text) { _, newText in - // Text matching a suggestion was just picked from the menu. - guard let newText, !newText.isEmpty, - !resolver.suggestions.contains(newText) - else { - resolver.reset() - return - } - - resolver.send(newText, using: fetch) - } - .onDisappear { - resolver.reset() + // A new text cancels the lookup for the previous one. + .task(id: text) { + await lookUp() } } -} - -/// Debounces typing into at most one lookup, skipping text already loaded. -@Observable -private final class SuggestionResolver { - private(set) var suggestions: [String] = [] - private(set) var isLoading = false - - /// Set when the last lookup failed, as opposed to matching nothing. - private(set) var failure: String? - - private let queries = PassthroughSubject() - - /// Cleared on reset, so the text alone can be the key. - @ObservationIgnored private var cache = SuggestionCache() - @ObservationIgnored private var fetch: (@Sendable (String) async throws -> [String])? - @ObservationIgnored private var subscription: AnyCancellable? - @ObservationIgnored private var fetchTask: Task? - @ObservationIgnored private var loadedText: String? - - init(debounce: DispatchQueue.SchedulerTimeType.Stride = .milliseconds(300)) { - self.subscription = - queries - .debounce(for: debounce, scheduler: DispatchQueue.main) - .sink { [weak self] text in - MainActor.assumeIsolated { - guard let text else { return } - self?.load(text) - } - } - } - - /// Takes the lookup every time, so it never goes stale against the view. - func send( - _ text: String, - using fetch: @escaping @Sendable (String) async throws -> [String] - ) { - self.fetch = fetch - queries.send(text) - } - - func reset() { - queries.send(nil) - fetchTask?.cancel() - fetchTask = nil - loadedText = nil - suggestions = [] - failure = nil - isLoading = false - cache.removeAll() - } - private func load(_ text: String) { - guard text != loadedText, let fetch else { return } + private func lookUp() async { + // Picking a suggestion sets the text to it, and looking that up would open the menu again. + // Losing focus clears nothing, since the system hides the menu, and picking can move focus. + guard isEnabled, !text.isEmpty, !suggestions.contains(text) else { + suggestions = [] + failure = nil + isLoading = false + return + } - fetchTask?.cancel() - loadedText = text + do { + try await Task.sleep(for: Self.debounce) + } catch { + return + } if let cached = cache.values(for: text) { suggestions = cached @@ -129,27 +87,24 @@ private final class SuggestionResolver { isLoading = true - fetchTask = Task { - do { - let results = try await fetch(text) - - // The newer text owns `isLoading` now. - guard !Task.isCancelled else { return } - - cache.store(results, for: text) - suggestions = results - failure = nil - isLoading = false - } catch { - guard !Task.isCancelled else { return } - - // Not cached, so retyping retries. - loadedText = nil - suggestions = [] - failure = error.localizedDescription - isLoading = false - } + do { + let results = try await fetch(text) + + // URL loading reports cancellation as its own error, or not at all. + guard !Task.isCancelled else { return } + + cache.store(results, for: text) + suggestions = results + failure = nil + } catch { + guard !Task.isCancelled else { return } + + // Not cached, so retyping retries. + suggestions = [] + failure = error.localizedDescription } + + isLoading = false } } @@ -199,8 +154,4 @@ private struct SuggestionCache { entries[entry.key] = nil } } - - mutating func removeAll() { - entries.removeAll() - } } diff --git a/Containers/Models/Shared/AppLink.swift b/Containers/Models/Shared/AppLink.swift index 31c4422..f93bec1 100644 --- a/Containers/Models/Shared/AppLink.swift +++ b/Containers/Models/Shared/AppLink.swift @@ -10,6 +10,9 @@ import Foundation /// A link into the app, such as `containers://reports?name=redis-test`, which /// the dashboard opens: from a detail window, or from outside the app. enum AppLink: Equatable { + /// The Containers section. + case containers + /// The Reports section, narrowed to what was reported against `name`. case reports(name: String) @@ -20,6 +23,8 @@ enum AppLink: Equatable { components.scheme = Self.scheme switch self { + case .containers: + components.host = "containers" case .reports(let name): components.host = "reports" components.queryItems = [URLQueryItem(name: "name", value: name)] @@ -38,6 +43,8 @@ enum AppLink: Equatable { let query = components.queryItems ?? [] switch components.host { + case "containers": + self = .containers case "reports": guard let name = query.first(where: { $0.name == "name" })?.value, !name.isEmpty else { return nil diff --git a/Containers/Views/Components/RowProgressIndicator.swift b/Containers/Views/Components/RowProgressIndicator.swift index c5b71ce..0caa0f6 100644 --- a/Containers/Views/Components/RowProgressIndicator.swift +++ b/Containers/Views/Components/RowProgressIndicator.swift @@ -153,7 +153,7 @@ struct ActivityMenuItems: View { ) { for activity in ended { activityCenter.remove(activity.id) } - Task { await reportManager.remove(reported) } + Task { await reportManager.delete(ids: reported) } } } } diff --git a/Containers/Views/Containers/ContainersView.swift b/Containers/Views/Containers/ContainersView.swift index 63204d8..c8034b0 100644 --- a/Containers/Views/Containers/ContainersView.swift +++ b/Containers/Views/Containers/ContainersView.swift @@ -24,6 +24,8 @@ struct ContainersView: View { var refreshTrigger: Int @State private var containers: [ContainerItem] = [] + @State private var refreshTask: Task? + @State private var needsRefresh = false private var trimmedText: String { self.searchText.trimmingCharacters(in: .whitespacesAndNewlines) @@ -266,8 +268,26 @@ struct ContainersView: View { } } + /// Refreshes run one at a time. Several containers changing at once fire + /// overlapping refreshes, and an older list landing last would leave the + /// state dots behind. A call made mid-refresh reruns it once that's done, + /// and every caller waits for a list fetched after it asked. private func refreshContainers() async throws { - containers = try await containerManager.list().map(ContainerItem.init) + needsRefresh = true + + let task = + refreshTask + ?? Task { + defer { refreshTask = nil } + + while needsRefresh { + needsRefresh = false + containers = try await containerManager.list().map(ContainerItem.init) + } + } + + refreshTask = task + try await task.value } } diff --git a/Containers/Views/Containers/CreateContainerView.swift b/Containers/Views/Containers/CreateContainerView.swift index 4eb454a..8c515f1 100644 --- a/Containers/Views/Containers/CreateContainerView.swift +++ b/Containers/Views/Containers/CreateContainerView.swift @@ -59,6 +59,7 @@ struct CreateContainerView: View { @Environment(VolumeManager.self) private var volumeManager @Environment(ActivityCenter.self) private var activityCenter @Environment(\.dismiss) private var dismiss + @Environment(\.openURL) private var openURL let mode: Mode @@ -706,6 +707,11 @@ struct CreateContainerView: View { dismiss() + // The start is followed on the container's dashboard row, which a detail window doesn't show. + if mode == .run { + openURL(AppLink.containers.url) + } + return } catch is CancellationError { // The sheet was closed on purpose; there is nothing to report. diff --git a/Containers/Views/Dashboard/DashboardToolbarBinder.swift b/Containers/Views/Dashboard/DashboardToolbarBinder.swift index 66ce62e..29862b0 100644 --- a/Containers/Views/Dashboard/DashboardToolbarBinder.swift +++ b/Containers/Views/Dashboard/DashboardToolbarBinder.swift @@ -62,6 +62,10 @@ struct DashboardToolbarBinder: NSViewRepresentable { controller.update() } + static func dismantleNSView(_ nsView: NSView, coordinator: Void) { + (nsView as? BindingView)?.controller.releaseHandlers() + } + private final class BindingView: NSView { let controller: DashboardToolbarController diff --git a/Containers/Views/Dashboard/DashboardView.swift b/Containers/Views/Dashboard/DashboardView.swift index d1cd9d9..5e87fc9 100644 --- a/Containers/Views/Dashboard/DashboardView.swift +++ b/Containers/Views/Dashboard/DashboardView.swift @@ -206,13 +206,20 @@ struct DashboardView: View { .onChange(of: selectedTab) { _, newTab in UserDefaults.lastSelectedTab = newTab.rawValue } - // Replaces the current filters and any typed search. .onOpenURL { url in - guard case .reports(let name) = AppLink(url) else { return } - - selectedTab = .reports - reportFilters = [.name(name)] - searchText = "" + switch AppLink(url) { + case .containers: + // A typed search could hide the row the link leads to. + selectedTab = .containers + searchText = "" + case .reports(let name): + // Replaces the current filters and any typed search. + selectedTab = .reports + reportFilters = [.name(name)] + searchText = "" + case nil: + break + } } // Follows a new container to the tab its row appears in. .onChange(of: containersBeingMade) { before, now in diff --git a/Containers/Views/Images/Create/PullImageView.swift b/Containers/Views/Images/Create/PullImageView.swift index d1b144b..23d55e2 100644 --- a/Containers/Views/Images/Create/PullImageView.swift +++ b/Containers/Views/Images/Create/PullImageView.swift @@ -201,7 +201,7 @@ struct PullImageView: View { ) { EmptyView() } - .suggestions(for: isImageNameFieldFocused ? imageName : nil) { + .suggestions(for: imageName, isEnabled: isImageNameFieldFocused) { [registryLookup, registry] text in try await registryLookup.images(matching: text, on: registry) } @@ -232,7 +232,7 @@ struct PullImageView: View { ) { EmptyView() } - .suggestions(for: isTagFieldFocused ? tag : nil) { + .suggestions(for: tag, isEnabled: isTagFieldFocused) { [registryLookup, registry, imageName] text in try await registryLookup.tags( for: imageName, diff --git a/Containers/Views/Reports/ReportDetailWindow.swift b/Containers/Views/Reports/ReportDetailWindow.swift index 56e4cfc..78758ae 100644 --- a/Containers/Views/Reports/ReportDetailWindow.swift +++ b/Containers/Views/Reports/ReportDetailWindow.swift @@ -59,7 +59,7 @@ struct ReportDetailWindow: View { } private func load() async { - entry = await reportManager.entry(for: id) + entry = await reportManager.get(id: id) text = await reportManager.body(of: id) ?? "" await reportManager.markRead([id]) diff --git a/Containers/Views/Reports/ReportToolbarBinder.swift b/Containers/Views/Reports/ReportToolbarBinder.swift index 68a93a6..459fc37 100644 --- a/Containers/Views/Reports/ReportToolbarBinder.swift +++ b/Containers/Views/Reports/ReportToolbarBinder.swift @@ -21,6 +21,10 @@ struct ReportToolbarBinder: NSViewRepresentable { controller.onSearch = onSearch } + static func dismantleNSView(_ nsView: NSView, coordinator: Void) { + (nsView as? BindingView)?.controller.releaseHandlers() + } + private final class BindingView: NSView { let controller: ReportToolbarController diff --git a/Containers/Views/Reports/ReportsView.swift b/Containers/Views/Reports/ReportsView.swift index 74e1f12..38fc432 100644 --- a/Containers/Views/Reports/ReportsView.swift +++ b/Containers/Views/Reports/ReportsView.swift @@ -154,7 +154,7 @@ struct ReportsView: View { let ids = entries.map(\.id) Task { - await reportManager.remove(ids) + await reportManager.delete(ids: ids) activityCenter.forgetFailures(reportedAs: Set(ids)) selection.subtract(ids) } diff --git a/Containers/Views/Shared/Detail/DetailToolbarBinder.swift b/Containers/Views/Shared/Detail/DetailToolbarBinder.swift index e161764..da9b51b 100644 --- a/Containers/Views/Shared/Detail/DetailToolbarBinder.swift +++ b/Containers/Views/Shared/Detail/DetailToolbarBinder.swift @@ -24,6 +24,10 @@ struct DetailToolbarAttacher: NSViewRepresentable { } func updateNSView(_ nsView: NSView, context: Context) {} + + static func dismantleNSView(_ nsView: NSView, coordinator: Void) { + (nsView as? DetailToolbarBinder.BindingView)?.controller.releaseHandlers() + } } /// Hands the controller its window, and the current state on every update. @@ -46,6 +50,10 @@ struct DetailToolbarBinder: NSViewRepresentable { controller.update() } + static func dismantleNSView(_ nsView: NSView, coordinator: Void) { + (nsView as? BindingView)?.controller.releaseHandlers() + } + final class BindingView: NSView { let controller: DetailToolbarController diff --git a/Containers/Views/Shared/ErrorAlert.swift b/Containers/Views/Shared/ErrorAlert.swift index 96ada3e..db08daf 100644 --- a/Containers/Views/Shared/ErrorAlert.swift +++ b/Containers/Views/Shared/ErrorAlert.swift @@ -72,11 +72,13 @@ extension View { private struct ErrorAlertModifier: ViewModifier { @Binding var alert: ErrorAlert? - @SwiftUI.State private var window: NSWindow? + @SwiftUI.State private var windowReference = WindowReference() + + private var window: NSWindow? { windowReference.window } func body(content: Content) -> some View { content - .background(AlertWindowBinder(window: $window)) + .background(AlertWindowBinder(reference: windowReference)) .onChange(of: alert) { _, alert in guard let alert else { return } present(alert) @@ -185,13 +187,19 @@ private final class ErrorDetailsView: NSView { } } +/// Weak, because the state that holds it lives inside the window: a strong +/// reference would keep a closed window, and everything in it, alive. +private final class WindowReference { + weak var window: NSWindow? +} + /// The window the alert hangs off, so it arrives as a sheet on the window the /// error came from rather than in the middle of the screen. private struct AlertWindowBinder: NSViewRepresentable { - @Binding var window: NSWindow? + let reference: WindowReference func makeNSView(context: Context) -> NSView { - BindingView { window = $0 } + BindingView { [reference] in reference.window = $0 } } func updateNSView(_ nsView: NSView, context: Context) {}