-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathSystemStart.swift
More file actions
258 lines (232 loc) · 10.9 KB
/
Copy pathSystemStart.swift
File metadata and controls
258 lines (232 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the container project authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===----------------------------------------------------------------------===//
import ArgumentParser
import ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import ContainerXPC
import ContainerizationError
import Foundation
import MachineAPIClient
import SystemPackage
import TerminalProgress
extension Application {
public struct SystemStart: AsyncLoggableCommand {
public static let configuration = CommandConfiguration(
commandName: "start",
abstract: "Start `container` services"
)
@Option(
name: .shortAndLong,
help: "Path to the root directory for application data",
transform: { FilePath(FileManager.default.currentDirectoryPath).resolve($0, defaultPath: FilePath($0)) })
var appRoot = ApplicationRoot.defaultPath
@Option(
name: .long,
help: "Path to the root directory for application executables and plugins",
transform: { FilePath(FileManager.default.currentDirectoryPath).resolve($0, defaultPath: FilePath($0)) })
var installRoot = InstallRoot.defaultPath
@Option(
name: .long,
help: "Path to the root directory for log data, using macOS log facility if not set",
transform: { FilePath(FileManager.default.currentDirectoryPath).resolve($0, defaultPath: FilePath($0)) })
var logRoot: FilePath? = nil
@Flag(
name: .long,
inversion: .prefixedEnableDisable,
help: "Specify whether the default kernel should be installed or not (default: prompt user)")
var kernelInstall: Bool?
@Option(
help: "Number of seconds to wait for API service to become responsive",
transform: {
guard let timeoutSeconds = Double($0) else {
throw ValidationError("Invalid timeout value: \($0)")
}
return .seconds(timeoutSeconds)
}
)
var timeout: Duration = XPCClient.xpcRegistrationTimeout
@OptionGroup
public var logOptions: Flags.Logging
public init() {}
public func run() async throws {
do {
try ConfigurationLoader.copyConfigurationToReadOnly(to: appRoot)
} catch {
throw ContainerizationError(
.invalidArgument,
message:
"cannot prepare configuration under app-root \(appRoot): path must be writable (\(error.localizedDescription))"
)
}
// Pass appRoot before installRoot: ConfigurationLoader uses first-match-wins
// precedence, so user-provided config in appRoot overrides the defaults
// shipped under installRoot. Both layers are passed explicitly because
// users can override --app-root and --install-root from the CLI, and the
// loader's default search would otherwise ignore those overrides.
let containerSystemConfig: ContainerSystemConfig = try await ConfigurationLoader.load(
configurationFiles: [
ConfigurationLoader.configurationFile(in: appRoot, of: .appRoot),
ConfigurationLoader.configurationFile(in: installRoot, of: .installRoot),
])
// Without the true path to the binary in the plist, `container-apiserver` won't launch properly.
// Resolve the symlink to get the true binary path before writing the launchd plist.
// Gatekeeper / amfid validates code signatures relative to the enclosing .app bundle
// hierarchy; launching via a symlink outside the bundle fails that check.
// TODO: Can we use the plugin loader to bootstrap the API server?
let executablePath = try CommandLine.executablePath
.removingLastComponent()
.appending(FilePath.Component("container-apiserver"))
.resolvingSymlinks()
var args = [executablePath.string]
args.append("start")
if logOptions.debug {
args.append("--debug")
}
let apiServerDataPath = appRoot.appending(FilePath.Component("apiserver"))
try Self.ensureWritableDirectory(at: apiServerDataPath)
var env = PluginLoader.filterEnvironment()
env[ApplicationRoot.environmentName] = appRoot.string
env[InstallRoot.environmentName] = installRoot.string
if let logRoot {
env[LogRoot.environmentName] = logRoot.string
}
let plist = LaunchPlist(
label: "com.apple.container.apiserver",
arguments: args,
environment: env,
limitLoadToSessionType: [.Aqua, .Background, .System],
runAtLoad: true,
machServices: ["com.apple.container.apiserver"]
)
let plistPath = apiServerDataPath.appending(FilePath.Component("apiserver.plist"))
let plistURL = URL(fileURLWithPath: plistPath.string)
let data = try plist.encode()
do {
try data.write(to: plistURL)
} catch {
throw ContainerizationError(
.invalidArgument,
message:
"cannot write apiserver launchd plist at \(plistPath): app-root must be writable (\(error.localizedDescription))"
)
}
log.info("Launching container-apiserver...")
try ServiceManager.register(plistPath: plistURL.path)
// Now ping our friendly daemon. Fail if we don't get a response.
do {
log.info("Testing access to container-apiserver...")
_ = try await ClientHealthCheck.ping(timeout: timeout)
} catch {
throw ContainerizationError(
.internalError,
message: "failed to get a response from apiserver: \(error)"
)
}
do {
log.info("Verifying machine API server is running...")
_ = try await MachineClient().list()
} catch {
throw ContainerizationError(
.internalError,
message: "failed to get a response from machine API server: \(error)"
)
}
if await !initImageExists(containerSystemConfig: containerSystemConfig) {
try? await installInitialFilesystem(initImage: containerSystemConfig.vminit.image)
}
guard await !kernelExists() else {
return
}
try await installDefaultKernel(
kernelURL: containerSystemConfig.kernel.url,
kernelBinaryPath: containerSystemConfig.kernel.binaryPath,
kernelDigest: containerSystemConfig.kernel.digest)
}
private func installInitialFilesystem(initImage: String) async throws {
var pullCommand = try ImagePull.parse()
pullCommand.reference = initImage
log.info("Installing base container filesystem...")
do {
try await pullCommand.run()
} catch {
log.error("failed to install base container filesystem", metadata: ["error": "\(error)"])
}
}
private func installDefaultKernel(kernelURL: URL, kernelBinaryPath: String, kernelDigest: String) async throws {
var shouldInstallKernel = false
if kernelInstall == nil {
log.warning("No default kernel configured.")
print("Install the recommended default kernel from [\(kernelURL)]? [Y/n]: ", terminator: "")
guard let read = readLine(strippingNewline: true) else {
throw ContainerizationError(.internalError, message: "failed to read user input")
}
guard read.lowercased() == "y" || read.count == 0 else {
log.info("Please use the `container system kernel set --recommended` command to configure the default kernel")
return
}
shouldInstallKernel = true
} else {
shouldInstallKernel = kernelInstall ?? false
}
guard shouldInstallKernel else {
return
}
log.info("Installing kernel...")
try await KernelSet.downloadAndInstallWithProgressBar(
tarRemoteURL: kernelURL,
kernelFilePath: kernelBinaryPath,
expectedDigest: kernelDigest,
force: true)
}
private func initImageExists(containerSystemConfig: ContainerSystemConfig) async -> Bool {
do {
let img = try await ClientImage.get(
reference: containerSystemConfig.vminit.image,
containerSystemConfig: containerSystemConfig
)
let _ = try await img.getSnapshot(platform: .current)
return true
} catch {
return false
}
}
private func kernelExists() async -> Bool {
do {
try await ClientKernel.getDefaultKernel(for: .current)
return true
} catch {
return false
}
}
/// Create `path` if needed, surfacing a clear error when the app-root is not writable.
///
/// Prefer this over a bare `FileManager` call so permission failures become a normal
/// CLI error instead of an opaque Cocoa error (see apple/container#1802).
static func ensureWritableDirectory(at path: FilePath) throws {
let url = URL(fileURLWithPath: path.string)
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
} catch {
throw ContainerizationError(
.invalidArgument,
message:
"cannot create application data directory at \(path): app-root must be writable (\(error.localizedDescription))"
)
}
}
}
}