|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// Copyright © 2026 Apple Inc. and the container project authors. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | +//===----------------------------------------------------------------------===// |
| 16 | + |
| 17 | +import ContainerResource |
| 18 | +import ContainerXPC |
| 19 | +import ContainerizationError |
| 20 | +import ContainerizationExtras |
| 21 | +import ContainerizationOS |
| 22 | +import Foundation |
| 23 | + |
| 24 | +/// A client for managing virtual networks through the container API server. |
| 25 | +/// |
| 26 | +/// `NetworkClient` communicates with `container-apiserver` over XPC to create, |
| 27 | +/// list, inspect, and delete networks. Each instance holds a dedicated XPC |
| 28 | +/// connection; create one client and reuse it across related operations. |
| 29 | +/// |
| 30 | +/// ```swift |
| 31 | +/// let client = NetworkClient() |
| 32 | +/// let state = try await client.create(configuration: config) |
| 33 | +/// let networks = try await client.list() |
| 34 | +/// try await client.delete(id: state.id) |
| 35 | +/// ``` |
| 36 | +public struct NetworkClient: Sendable { |
| 37 | + /// The Mach service name used to locate the container API server. |
| 38 | + /// |
| 39 | + /// Pass a different value to ``init(serviceIdentifier:)`` to connect to an |
| 40 | + /// alternative service endpoint, for example during testing. |
| 41 | + public static let defaultServiceIdentifier = "com.apple.container.apiserver" |
| 42 | + |
| 43 | + /// The name of the default network created automatically on first use. |
| 44 | + public static let defaultNetworkName = "default" |
| 45 | + |
| 46 | + /// The reserved name that indicates a container should have no network attachment. |
| 47 | + public static let noNetworkName = "none" |
| 48 | + |
| 49 | + private let xpcClient: XPCClient |
| 50 | + |
| 51 | + /// Creates a new network client connected to the given service endpoint. |
| 52 | + /// |
| 53 | + /// - Parameter serviceIdentifier: The Mach service name of the API server. |
| 54 | + /// Defaults to ``defaultServiceIdentifier``. |
| 55 | + public init(serviceIdentifier: String = Self.defaultServiceIdentifier) { |
| 56 | + self.xpcClient = XPCClient(service: serviceIdentifier) |
| 57 | + } |
| 58 | + |
| 59 | + @discardableResult |
| 60 | + private func xpcSend( |
| 61 | + message: XPCMessage, |
| 62 | + timeout: Duration? = XPCClient.xpcRegistrationTimeout |
| 63 | + ) async throws -> XPCMessage { |
| 64 | + try await xpcClient.send(message, responseTimeout: timeout) |
| 65 | + } |
| 66 | + |
| 67 | + /// Creates a new network with the given configuration. |
| 68 | + /// |
| 69 | + /// The API server launches a network plugin instance for the new network and |
| 70 | + /// returns a ``NetworkState`` reflecting the network once it is running. |
| 71 | + /// |
| 72 | + /// - Parameter configuration: The configuration describing the network to create. |
| 73 | + /// - Returns: The running state of the newly created network. |
| 74 | + /// - Throws: ``ContainerizationError`` if the server does not return a valid |
| 75 | + /// network state, or if the underlying XPC call fails. |
| 76 | + public func create(configuration: NetworkConfiguration) async throws -> NetworkState { |
| 77 | + let request = XPCMessage(route: .networkCreate) |
| 78 | + request.set(key: .networkId, value: configuration.id) |
| 79 | + |
| 80 | + let data = try JSONEncoder().encode(configuration) |
| 81 | + request.set(key: .networkConfig, value: data) |
| 82 | + |
| 83 | + let response = try await xpcSend(message: request) |
| 84 | + let responseData = response.dataNoCopy(key: .networkState) |
| 85 | + guard let responseData else { |
| 86 | + throw ContainerizationError(.invalidArgument, message: "network configuration not received") |
| 87 | + } |
| 88 | + let state = try JSONDecoder().decode(NetworkState.self, from: responseData) |
| 89 | + return state |
| 90 | + } |
| 91 | + |
| 92 | + /// Returns the current state of all networks known to the API server. |
| 93 | + /// |
| 94 | + /// - Returns: An array of ``NetworkState`` values, or an empty array if no |
| 95 | + /// networks exist or the server returns no data. |
| 96 | + /// - Throws: ``ContainerizationError`` if the underlying XPC call fails. |
| 97 | + public func list() async throws -> [NetworkState] { |
| 98 | + let request = XPCMessage(route: .networkList) |
| 99 | + |
| 100 | + let response = try await xpcSend(message: request, timeout: .seconds(1)) |
| 101 | + let responseData = response.dataNoCopy(key: .networkStates) |
| 102 | + guard let responseData else { |
| 103 | + return [] |
| 104 | + } |
| 105 | + let states = try JSONDecoder().decode([NetworkState].self, from: responseData) |
| 106 | + return states |
| 107 | + } |
| 108 | + |
| 109 | + /// Returns the network with the given identifier. |
| 110 | + /// |
| 111 | + /// - Parameter id: The identifier of the network to look up. |
| 112 | + /// - Returns: The ``NetworkState`` for the matching network. |
| 113 | + /// - Throws: ``ContainerizationError/notFound`` if no network with the given |
| 114 | + /// identifier exists, or a communication error if the XPC call fails. |
| 115 | + public func get(id: String) async throws -> NetworkState { |
| 116 | + let networks = try await list() |
| 117 | + guard let network = networks.first(where: { $0.id == id }) else { |
| 118 | + throw ContainerizationError(.notFound, message: "network \(id) not found") |
| 119 | + } |
| 120 | + return network |
| 121 | + } |
| 122 | + |
| 123 | + /// Deletes the network with the given identifier. |
| 124 | + /// |
| 125 | + /// Deletion succeeds only when no containers are currently attached to the |
| 126 | + /// network. The default network cannot be deleted. |
| 127 | + /// |
| 128 | + /// - Parameter id: The identifier of the network to delete. |
| 129 | + /// - Throws: ``ContainerizationError`` if the network has active attachments, |
| 130 | + /// if the network is the built-in default, or if the XPC call fails. |
| 131 | + public func delete(id: String) async throws { |
| 132 | + let request = XPCMessage(route: .networkDelete) |
| 133 | + request.set(key: .networkId, value: id) |
| 134 | + try await xpcSend(message: request) |
| 135 | + } |
| 136 | + |
| 137 | + /// The built-in network, if one exists. |
| 138 | + /// |
| 139 | + /// The built-in network is created automatically on first use and cannot be |
| 140 | + /// deleted. Returns `nil` if the API server cannot find a network with the |
| 141 | + /// built-in resource labels. |
| 142 | + /// |
| 143 | + /// - Throws: ``ContainerizationError`` if the underlying XPC call fails. |
| 144 | + public var builtin: NetworkState? { |
| 145 | + get async throws { |
| 146 | + try await list().first { $0.isBuiltin } |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments