-
Notifications
You must be signed in to change notification settings - Fork 703
Expand file tree
/
Copy pathAPIServer+Start.swift
More file actions
328 lines (283 loc) · 13.9 KB
/
APIServer+Start.swift
File metadata and controls
328 lines (283 loc) · 13.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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//===----------------------------------------------------------------------===//
// 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 ContainerAPIService
import ContainerNetworkService
import ContainerPlugin
import ContainerResource
import ContainerXPC
import DNSServer
import Foundation
import Logging
extension APIServer {
struct Start: AsyncParsableCommand {
static let configuration = CommandConfiguration(
commandName: "start",
abstract: "Start helper for the API server"
)
static let listenAddress = "127.0.0.1"
static let localhostDNSPort = 1053
static let dnsPort = 2053
@Flag(name: .long, help: "Enable debug logging")
var debug = false
var appRoot = ApplicationRoot.url
var installRoot = InstallRoot.url
func run() async throws {
let commandName = Self.configuration.commandName ?? "container-apiserver"
let log = APIServer.setupLogger(debug: debug)
log.info("starting \(commandName)")
defer {
log.info("stopping \(commandName)")
}
do {
log.info("configuring XPC server")
var routes = [XPCRoute: XPCServer.RouteHandler]()
let pluginLoader = try initializePluginLoader(log: log)
try await initializePlugins(pluginLoader: pluginLoader, log: log, routes: &routes)
let containersService = try initializeContainerService(
pluginLoader: pluginLoader,
log: log,
routes: &routes
)
let networkService = try await initializeNetworkService(
pluginLoader: pluginLoader,
containersService: containersService,
log: log,
routes: &routes
)
initializeHealthCheckService(log: log, routes: &routes)
try initializeKernelService(log: log, routes: &routes)
let volumesService = try initializeVolumeService(containersService: containersService, log: log, routes: &routes)
try initializeDiskUsageService(
containersService: containersService,
volumesService: volumesService,
log: log,
routes: &routes
)
let server = XPCServer(
identifier: "com.apple.container.apiserver",
routes: routes.reduce(
into: [String: XPCServer.RouteHandler](),
{
$0[$1.key.rawValue] = $1.value
}), log: log)
await withThrowingTaskGroup(of: Void.self) { group in
group.addTask {
log.info("starting XPC server")
try await server.listen()
}
// start up host table DNS
group.addTask {
let hostsResolver = ContainerDNSHandler(networkService: networkService)
let nxDomainResolver = NxDomainResolver()
let compositeResolver = CompositeResolver(handlers: [hostsResolver, nxDomainResolver])
let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)
let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)
log.info(
"starting DNS resolver for container hostnames",
metadata: [
"host": "\(Self.listenAddress)",
"port": "\(Self.dnsPort)",
]
)
try await dnsServer.run(host: Self.listenAddress, port: Self.dnsPort)
}
// start up realhost DNS
/*
group.addTask {
let localhostResolver = LocalhostDNSHandler(log: log)
try localhostResolver.monitorResolvers()
let nxDomainResolver = NxDomainResolver()
let compositeResolver = CompositeResolver(handlers: [localhostResolver, nxDomainResolver])
let hostsQueryValidator = StandardQueryValidator(handler: compositeResolver)
let dnsServer: DNSServer = DNSServer(handler: hostsQueryValidator, log: log)
log.info(
"starting DNS resolver for localhost",
metadata: [
"host": "\(Self.listenAddress)",
"port": "\(Self.localhostDNSPort)",
]
)
try await dnsServer.run(host: Self.listenAddress, port: Self.localhostDNSPort)
}
*/
}
} catch {
log.error("\(commandName) failed", metadata: ["error": "\(error)"])
APIServer.exit(withError: error)
}
}
private func initializePluginLoader(log: Logger) throws -> PluginLoader {
log.info(
"initializing plugin loader",
metadata: [
"installRoot": "\(installRoot.path(percentEncoded: false))"
])
let pluginsURL = PluginLoader.userPluginsDir(installRoot: installRoot)
log.info("detecting user plugins directory", metadata: ["path": "\(pluginsURL.path(percentEncoded: false))"])
var directoryExists: ObjCBool = false
_ = FileManager.default.fileExists(atPath: pluginsURL.path, isDirectory: &directoryExists)
let userPluginsURL = directoryExists.boolValue ? pluginsURL : nil
// plugins built into the application installed as a macOS app bundle
let appBundlePluginsURL = Bundle.main.resourceURL?.appending(path: "plugins")
// plugins built into the application installed as a Unix-like application
let installRootPluginsURL =
installRoot
.appendingPathComponent("libexec")
.appendingPathComponent("container")
.appendingPathComponent("plugins")
.standardized
let pluginDirectories = [
userPluginsURL,
appBundlePluginsURL,
installRootPluginsURL,
].compactMap { $0 }
let pluginFactories: [PluginFactory] = [
DefaultPluginFactory(),
AppBundlePluginFactory(),
]
for pluginDirectory in pluginDirectories {
log.info("discovered plugin directory", metadata: ["path": "\(pluginDirectory.path(percentEncoded: false))"])
}
return try PluginLoader(
appRoot: appRoot,
installRoot: installRoot,
pluginDirectories: pluginDirectories,
pluginFactories: pluginFactories,
log: log
)
}
// First load all of the plugins we can find. Then just expose
// the handlers for clients to do whatever they want.
private func initializePlugins(
pluginLoader: PluginLoader,
log: Logger,
routes: inout [XPCRoute: XPCServer.RouteHandler]
) async throws {
log.info("initializing plugins")
let bootPlugins = pluginLoader.findPlugins().filter { $0.shouldBoot }
let service = PluginsService(pluginLoader: pluginLoader, log: log)
try await service.loadAll(bootPlugins)
let harness = PluginsHarness(service: service, log: log)
routes[XPCRoute.pluginGet] = harness.get
routes[XPCRoute.pluginList] = harness.list
routes[XPCRoute.pluginLoad] = harness.load
routes[XPCRoute.pluginUnload] = harness.unload
routes[XPCRoute.pluginRestart] = harness.restart
}
private func initializeHealthCheckService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) {
log.info("initializing health check service")
let svc = HealthCheckHarness(appRoot: appRoot, installRoot: installRoot, log: log)
routes[XPCRoute.ping] = svc.ping
}
private func initializeKernelService(log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws {
log.info("initializing kernel service")
let svc = try KernelService(log: log, appRoot: appRoot)
let harness = KernelHarness(service: svc, log: log)
routes[XPCRoute.installKernel] = harness.install
routes[XPCRoute.getDefaultKernel] = harness.getDefaultKernel
}
private func initializeContainerService(pluginLoader: PluginLoader, log: Logger, routes: inout [XPCRoute: XPCServer.RouteHandler]) throws -> ContainersService {
log.info("initializing container service")
let service = try ContainersService(
appRoot: appRoot,
pluginLoader: pluginLoader,
log: log
)
let harness = ContainersHarness(service: service, log: log)
routes[XPCRoute.containerList] = harness.list
routes[XPCRoute.containerCreate] = harness.create
routes[XPCRoute.containerDelete] = harness.delete
routes[XPCRoute.containerLogs] = harness.logs
routes[XPCRoute.containerBootstrap] = harness.bootstrap
routes[XPCRoute.containerDial] = harness.dial
routes[XPCRoute.containerStop] = harness.stop
routes[XPCRoute.containerStartProcess] = harness.startProcess
routes[XPCRoute.containerCreateProcess] = harness.createProcess
routes[XPCRoute.containerResize] = harness.resize
routes[XPCRoute.containerWait] = harness.wait
routes[XPCRoute.containerKill] = harness.kill
routes[XPCRoute.containerStats] = harness.stats
routes[XPCRoute.containerDiskUsage] = harness.diskUsage
routes[XPCRoute.containerCopyIn] = harness.copyIn
routes[XPCRoute.containerCopyOut] = harness.copyOut
return service
}
private func initializeNetworkService(
pluginLoader: PluginLoader,
containersService: ContainersService,
log: Logger,
routes: inout [XPCRoute: XPCServer.RouteHandler]
) async throws -> NetworksService {
log.info("initializing network service")
let resourceRoot = appRoot.appendingPathComponent("networks")
let service = try await NetworksService(
pluginLoader: pluginLoader,
resourceRoot: resourceRoot,
containersService: containersService,
log: log
)
let defaultNetwork = try await service.list()
.filter { $0.isBuiltin }
.first
if defaultNetwork == nil {
let config = try NetworkConfiguration(
id: ClientNetwork.defaultNetworkName,
mode: .nat,
labels: [ResourceLabelKeys.role: ResourceRoleValues.builtin]
)
_ = try await service.create(configuration: config)
}
let harness = NetworksHarness(service: service, log: log)
routes[XPCRoute.networkCreate] = harness.create
routes[XPCRoute.networkDelete] = harness.delete
routes[XPCRoute.networkList] = harness.list
return service
}
private func initializeVolumeService(
containersService: ContainersService,
log: Logger,
routes: inout [XPCRoute: XPCServer.RouteHandler]
) throws -> VolumesService {
log.info("initializing volume service")
let resourceRoot = appRoot.appendingPathComponent("volumes")
let service = try VolumesService(resourceRoot: resourceRoot, containersService: containersService, log: log)
let harness = VolumesHarness(service: service, log: log)
routes[XPCRoute.volumeCreate] = harness.create
routes[XPCRoute.volumeDelete] = harness.delete
routes[XPCRoute.volumeList] = harness.list
routes[XPCRoute.volumeInspect] = harness.inspect
routes[XPCRoute.volumeDiskUsage] = harness.diskUsage
return service
}
private func initializeDiskUsageService(
containersService: ContainersService,
volumesService: VolumesService,
log: Logger,
routes: inout [XPCRoute: XPCServer.RouteHandler]
) throws {
log.info("initializing disk usage service")
let service = DiskUsageService(
containersService: containersService,
volumesService: volumesService,
log: log
)
let harness = DiskUsageHarness(service: service, log: log)
routes[XPCRoute.systemDiskUsage] = harness.get
}
}
}