-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathRuntimeService.swift
More file actions
1640 lines (1460 loc) · 60.9 KB
/
Copy pathRuntimeService.swift
File metadata and controls
1640 lines (1460 loc) · 60.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
// Copyright © 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 ContainerNetworkClient
import ContainerOS
import ContainerPersistence
import ContainerResource
import ContainerRuntimeClient
import ContainerXPC
import Containerization
import ContainerizationError
import ContainerizationExtras
import ContainerizationOCI
import ContainerizationOS
import Foundation
import Logging
import NIO
import NIOFoundationCompat
import SocketForwarder
import Synchronization
import SystemPackage
import struct ContainerizationOCI.Mount
import struct ContainerizationOCI.Process
/// An XPC service that manages the lifecycle of a single VM-backed container.
public actor RuntimeService {
private let connection: xpc_connection_t
private let root: URL
private let interfaceStrategies: [NetworkInterfaceKey: InterfaceStrategy]
private var container: ContainerInfo?
private let monitor: ExitMonitor
private let eventLoopGroup: any EventLoopGroup
private var waiters: [String: ExitWaiter] = [:]
private let lock: AsyncLock = AsyncLock()
private let log: Logging.Logger
private var state: State = .created
private var processes: [String: ProcessInfo] = [:]
private var socketForwarders: [SocketForwarderResult] = []
private var networkSessions: [XPCClientSession] = []
private static let sshAuthSocketGuestPath = "/var/host-services/ssh-auth.sock"
private static let sshAuthSocketEnvVar = "SSH_AUTH_SOCK"
class ExitWaiter {
public var exitStatus: ExitStatus? = nil
public var continuations: [CheckedContinuation<ExitStatus, Never>] = []
public func wait(_ cc: CheckedContinuation<ExitStatus, Never>) {
if let exitStatus = exitStatus {
// `doExit` has already been called for this waiter
cc.resume(returning: exitStatus)
return
}
continuations.append(cc)
}
public func doExit(exitStatus: ExitStatus) {
for cc in continuations {
cc.resume(returning: exitStatus)
}
self.exitStatus = exitStatus
}
}
private static func sshAuthSocketHostUrl(
config: ContainerConfiguration,
dynamicEnv: [String: String] = [:],
log: Logger? = nil
) -> URL? {
guard config.ssh else {
return nil
}
guard let sshSocket = dynamicEnv[Self.sshAuthSocketEnvVar] else {
log?.warning("ssh forwarding requested but no \(Self.sshAuthSocketEnvVar) found")
return nil
}
return URL(fileURLWithPath: sshSocket)
}
public init(
root: URL,
interfaceStrategies: [NetworkInterfaceKey: InterfaceStrategy],
eventLoopGroup: any EventLoopGroup,
connection: xpc_connection_t,
log: Logger
) {
self.root = root
self.interfaceStrategies = interfaceStrategies
self.log = log
self.monitor = ExitMonitor(log: log)
self.eventLoopGroup = eventLoopGroup
self.connection = connection
}
/// Returns an endpoint from an anonymous xpc connection.
///
/// - Parameters:
/// - message: An XPC message with no parameters.
///
/// - Returns: An XPC message with the following parameters:
/// - endpoint: An XPC endpoint that can be used to communicate
/// with the runtime service.
@Sendable
public func createEndpoint(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
let endpoint = xpc_endpoint_create(self.connection)
let reply = message.reply()
reply.set(key: RuntimeKeys.runtimeServiceEndpoint.rawValue, value: endpoint)
return reply
}
/// Start the VM and the guest agent process for a container.
///
/// - Parameters:
/// - message: An XPC message with no parameters.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func bootstrap(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
// Create the bundle if it doesn't exist yet
if !self.bundleExists(at: self.root) {
try self.createBundle()
}
return try await self.lock.withLock { _ in
guard await self.state == .created else {
throw ContainerizationError(
.invalidState,
message: "container expected to be in created state, got: \(await self.state)"
)
}
let dynamicEnv = try message.dynamicEnv()
let bundle = ContainerResource.Bundle(path: self.root)
try bundle.createLogFile()
var config = try bundle.configuration
var kernel = try bundle.kernel
kernel.commandLine.kernelArgs.append("oops=panic")
kernel.commandLine.kernelArgs.append("lsm=lockdown,capability,landlock,yama,apparmor")
let vmm = VZVirtualMachineManager(
kernel: kernel,
initialFilesystem: bundle.initialFilesystem.asMount,
rosetta: config.rosetta,
logger: self.log
)
let networkBootstrapInfos = try message.networkBootstrapInfos()
var sessions: [XPCClientSession] = []
var attachments: [Attachment] = []
var interfaces: [Interface] = []
do {
for (index, info) in networkBootstrapInfos.enumerated() {
let attachmentConfig = config.networks[index]
let client = ContainerNetworkClient.NetworkClient(id: attachmentConfig.network, plugin: info.plugin)
let session = client.connect()
sessions.append(session)
var (attachment, additionalData) = try await client.allocate(
hostname: attachmentConfig.options.hostname,
macAddress: attachmentConfig.options.macAddress,
on: session
)
if let mtu = attachmentConfig.options.mtu {
attachment = Attachment(
network: attachment.network,
hostname: attachment.hostname,
ipv4Address: attachment.ipv4Address,
ipv4Gateway: attachment.ipv4Gateway,
ipv6Address: attachment.ipv6Address,
macAddress: attachment.macAddress,
mtu: mtu,
variant: attachment.variant
)
}
guard let iStrategy = self.interfaceStrategies[NetworkInterfaceKey(plugin: info.plugin, variant: attachment.variant)] else {
throw ContainerizationError(
.internalError,
message: "no available interface strategy for network \(attachment.network), plugin=\(info.plugin) variant=\(attachment.variant ?? "nil")")
}
let interface = try iStrategy.toInterface(
attachment: attachment,
interfaceIndex: index,
additionalData: additionalData
)
attachments.append(attachment)
interfaces.append(interface)
}
} catch {
for session in sessions { session.close() }
throw error
}
// Dynamically configure the DNS nameserver from a network if no explicit configuration
if let dns = config.dns, dns.nameservers.isEmpty {
let defaultNameservers = self.getDefaultNameservers(from: attachments)
if !defaultNameservers.isEmpty {
config.dns = ContainerConfiguration.DNSConfiguration(
nameservers: defaultNameservers,
domain: dns.domain,
searchDomains: dns.searchDomains,
options: dns.options
)
}
}
let stdio = message.stdio()
let containerLog = try FileHandle(forWritingTo: bundle.containerLog)
let stdout = {
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 = {
stdio[0] ?? nil
}()
let id = config.id
let rootfs = try bundle.containerRootfs.asMount
let container = try LinuxContainer(id, rootfs: rootfs, vmm: vmm, logger: self.log) { czConfig in
try Self.configureContainer(czConfig: &czConfig, config: config, dynamicEnv: dynamicEnv, log: self.log)
czConfig.interfaces = interfaces
czConfig.process.stdout = stdout
czConfig.process.stderr = stderr
czConfig.process.stdin = stdin
// NOTE: We can support a user providing new entries eventually, but for now craft
// a default /etc/hosts.
var hostsEntries = [Hosts.Entry.localHostIPV4()]
if !interfaces.isEmpty {
let primaryIfaceAddr = interfaces[0].ipv4Address
hostsEntries.append(
Hosts.Entry(
ipAddress: primaryIfaceAddr.address.description,
hostnames: [czConfig.hostname ?? id],
))
}
czConfig.hosts = Hosts(entries: hostsEntries)
czConfig.bootLog = BootLog.file(path: bundle.bootlog, append: true)
}
let ctrInfo = ContainerInfo(
container: container,
config: config,
attachments: attachments,
bundle: bundle,
io: (in: stdin, out: stdout, err: stderr)
)
await self.setContainer(ctrInfo)
await self.setNetworkSessions(sessions)
do {
try await container.create()
try await self.initializeWaiters(for: id)
try await self.monitor.registerProcess(id: config.id, onExit: self.onContainerExit)
if !container.interfaces.isEmpty {
try await self.startSocketForwarders(attachment: attachments[0], publishedPorts: config.publishedPorts)
}
await self.setState(.booted)
} catch {
do {
try await self.cleanUpContainer(containerInfo: ctrInfo)
await self.setState(.stopped)
} catch {
self.log.error("failed to clean up container", metadata: ["error": "\(error)"])
}
throw error
}
return message.reply()
}
}
/// Start the container workload inside the virtual machine.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: A client identifier for the process.
/// - stdio: An array of file handles for standard input, output, and error.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func startProcess(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
return try await self.lock.withLock { lock in
let id = try message.id()
let containerInfo = try await self.getContainer()
let containerId = containerInfo.container.id
if id == containerId {
try await self.startInitProcess(lock: lock)
await self.setState(.running)
} else {
try await self.startExecProcess(processId: id, lock: lock)
}
return message.reply()
}
}
/// Get statistics for the container.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: A client identifier for the process.
/// - stdio: An array of file handles for standard input, output, and error.
///
/// - Returns: An XPC message with the following parameters:
/// - statistics: JSON serialization of the `ContainerStats`.
@Sendable
public func statistics(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
return try await self.lock.withLock { lock in
let containerInfo = try await self.getContainer()
let stats = try await containerInfo.container.statistics()
let containerStats = ContainerStats(
id: stats.id,
memoryUsageBytes: stats.memory?.usageBytes,
memoryLimitBytes: stats.memory?.limitBytes,
cpuUsageUsec: stats.cpu?.usageUsec,
networkRxBytes: stats.networks?.reduce(0) { $0 + $1.receivedBytes },
networkTxBytes: stats.networks?.reduce(0) { $0 + $1.transmittedBytes },
blockReadBytes: stats.blockIO?.devices.reduce(0) { $0 + $1.readBytes },
blockWriteBytes: stats.blockIO?.devices.reduce(0) { $0 + $1.writeBytes },
numProcesses: stats.process?.current
)
let reply = message.reply()
let data = try JSONEncoder().encode(containerStats)
reply.set(key: RuntimeKeys.statistics.rawValue, value: data)
return reply
}
}
/// Shutdown the RuntimeService.
///
/// - Parameters:
/// - message: An XPC message with no parameters.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func shutdown(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
return try await self.lock.withLock { _ in
switch await self.state {
case .created, .stopped, .stopping:
await self.setState(.shuttingDown)
default:
throw ContainerizationError(
.invalidState,
message: "cannot shutdown: container is not stopped"
)
}
return message.reply()
}
}
/// Create a process inside the virtual machine for the container.
///
/// Use this procedure to run ad hoc processes in the virtual
/// machine (`container exec`).
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: A client identifier for the process.
/// - processConfig: JSON serialization of the `ProcessConfiguration`
/// containing the process attributes.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func createProcess(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
return try await self.lock.withLock { [self] _ in
switch await self.state {
case .running, .booted:
let id = try message.id()
let config = try message.processConfig()
let stdio = message.stdio()
try await self.addNewProcess(id, config, stdio)
try await self.initializeWaiters(for: id)
do {
try await self.monitor.registerProcess(
id: id,
onExit: { id, exitStatus in
await self.releaseWaiters(for: id, status: exitStatus)
guard let process = await self.processes[id]?.process else {
throw ContainerizationError(
.invalidState,
message: "ProcessInfo missing for process \(id)"
)
}
try await process.delete()
try await self.setProcessState(id: id, state: .stopped)
}
)
} catch {
await self.releaseWaiters(for: id, status: ExitStatus(exitCode: -1))
throw error
}
return message.reply()
default:
throw ContainerizationError(
.invalidState,
message: "cannot exec: container is not running"
)
}
}
}
/// Return the state for the sandbox and its containers.
///
/// - Parameters:
/// - message: An XPC message with no parameters.
///
/// - Returns: An XPC message with the following parameters:
/// - snapshot: The JSON serialization of the `SandboxSnapshot`
/// that contains the state information.
@Sendable
public func state(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
var status: RuntimeStatus = .unknown
var networks: [Attachment] = []
var cs: ContainerSnapshot?
switch state {
case .created, .stopped, .booted, .shuttingDown:
status = .stopped
case .stopping:
status = .stopping
case .running:
let ctr = try getContainer()
status = .running
networks = ctr.attachments
cs = ContainerSnapshot(
configuration: ctr.config,
status: RuntimeStatus.running,
networks: networks
)
}
let reply = message.reply()
try reply.setState(
.init(
status: status,
networks: networks,
containers: cs != nil ? [cs!] : []
)
)
return reply
}
/// Stop the container workload, any ad hoc processes, and the underlying
/// virtual machine.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - stopOptions: JSON serialization of `ContainerStopOptions`
/// that modify stop behavior.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func stop(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
let stopOptions = try message.stopOptions()
let signal = try Signal(stopOptions.signal ?? "SIGTERM")
let timeout: Duration = .seconds(stopOptions.timeoutInSeconds)
return try await self.lock.withLock { _ in
switch await self.state {
case .running, .booted:
await self.setState(.stopping)
let ctr = try await self.getContainer()
let exitStatus = try await self.gracefulStopContainer(
ctr.container,
signal: signal,
timeout: timeout
)
do {
if case .stopped = await self.state {
return message.reply()
}
try await self.cleanUpContainer(containerInfo: ctr, exitStatus: exitStatus)
} catch {
self.log.error("failed to clean up container", metadata: ["error": "\(error)"])
}
await self.setState(.stopped)
default:
break
}
return message.reply()
}
}
/// Signal a process running in the virtual machine.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: The process identifier.
/// - signal: The signal value.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func kill(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
let id = try message.id()
let signal = try Signal(message.signal())
try await self.lock.withLock { [self] _ in
switch await self.state {
case .running:
let ctr = try await getContainer()
if id != ctr.container.id {
guard let processInfo = await self.processes[id] else {
throw ContainerizationError(.invalidState, message: "process \(id) does not exist")
}
guard let proc = processInfo.process else {
throw ContainerizationError(.invalidState, message: "process \(id) not started")
}
try await proc.kill(signal)
return
}
try await ctr.container.kill(signal)
default:
throw ContainerizationError(
.invalidState,
message: "cannot kill: container is not running"
)
}
}
// SIGKILL is guaranteed by the kernel to terminate the target, so block
// until we observe the exit.
if signal == .kill {
_ = await withCheckedContinuation { cc in
self.waitForExit(id: id, cont: cc)
}
}
return message.reply()
}
/// Resize the terminal for a process.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: The process identifier.
/// - width: The terminal width.
/// - height: The terminal height.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func resize(_ message: XPCMessage) async throws -> XPCMessage {
self.log.trace("enter", metadata: ["func": "\(#function)"])
defer { self.log.trace("exit", metadata: ["func": "\(#function)"]) }
switch self.state {
case .running:
let id = try message.id()
let ctr = try getContainer()
let width = message.uint64(key: RuntimeKeys.width.rawValue)
let height = message.uint64(key: RuntimeKeys.height.rawValue)
if id != ctr.container.id {
guard let processInfo = self.processes[id] else {
throw ContainerizationError(
.invalidState,
message: "process \(id) does not exist"
)
}
guard let proc = processInfo.process else {
throw ContainerizationError(
.invalidState,
message: "process \(id) not started"
)
}
try await proc.resize(
to: .init(
width: UInt16(width),
height: UInt16(height))
)
} else {
try await ctr.container.resize(
to: .init(
width: UInt16(width),
height: UInt16(height))
)
}
return message.reply()
default:
throw ContainerizationError(
.invalidState,
message: "cannot resize: container is not running"
)
}
}
/// Wait for a process.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - id: The process identifier.
///
/// - Returns: An XPC message with the following parameters:
/// - exitCode: The exit code for the process.
@Sendable
public func wait(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
guard let id = message.string(key: RuntimeKeys.id.rawValue) else {
throw ContainerizationError(.invalidArgument, message: "missing id in wait xpc message")
}
let exitStatus = await withCheckedContinuation { cc in
self.waitForExit(id: id, cont: cc)
}
let reply = message.reply()
reply.set(key: RuntimeKeys.exitCode.rawValue, value: Int64(exitStatus.exitCode))
reply.set(key: RuntimeKeys.exitedAt.rawValue, value: exitStatus.exitedAt)
return reply
}
/// Copy a file or directory from the host into the container.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - sourcePath: The host path to copy from.
/// - destinationPath: The container path to copy to.
/// - fileMode: The file permissions mode (UInt64).
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func copyIn(_ message: XPCMessage) async throws -> XPCMessage {
self.log.info("`copyIn` xpc handler")
switch self.state {
case .running, .booted:
guard let source = message.string(key: RuntimeKeys.sourcePath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no source path supplied for copyIn"
)
}
guard let destination = message.string(key: RuntimeKeys.destinationPath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no destination path supplied for copyIn"
)
}
let mode = UInt32(message.uint64(key: RuntimeKeys.fileMode.rawValue))
let createParents = message.bool(key: RuntimeKeys.createParents.rawValue)
let ctr = try getContainer()
try await ctr.container.copyIn(
from: URL(fileURLWithPath: source),
to: URL(fileURLWithPath: destination),
mode: mode,
createParents: createParents
)
return message.reply()
default:
throw ContainerizationError(
.invalidState,
message: "cannot copyIn: container is not running"
)
}
}
/// Copy a file or directory from the container to the host.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - sourcePath: The container path to copy from.
/// - destinationPath: The host path to copy to.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func copyOut(_ message: XPCMessage) async throws -> XPCMessage {
self.log.info("`copyOut` xpc handler")
switch self.state {
case .running, .booted:
guard let source = message.string(key: RuntimeKeys.sourcePath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no source path supplied for copyOut"
)
}
guard let destination = message.string(key: RuntimeKeys.destinationPath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no destination path supplied for copyOut"
)
}
let createParents = message.bool(key: RuntimeKeys.createParents.rawValue)
let ctr = try getContainer()
try await ctr.container.copyOut(
from: URL(fileURLWithPath: source),
to: URL(fileURLWithPath: destination),
createParents: createParents
)
return message.reply()
default:
throw ContainerizationError(
.invalidState,
message: "cannot copyOut: container is not running"
)
}
}
/// Snapshot the container's root filesystem by freezing it, cloning it to a destination image,
/// and then thawing it. This ensures the filesystem is frozen for the minimal duration.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - imagePath: The path to the source filesystem image.
/// - destinationPath: The path where the snapshot will be written.
///
/// - Returns: An XPC message with no parameters.
@Sendable
public func snapshotDisk(_ message: XPCMessage) async throws -> XPCMessage {
self.log.info("`snapshotDisk` xpc handler")
switch self.state {
case .running, .booted:
guard let imagePath = message.string(key: RuntimeKeys.imagePath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no image path supplied for snapshotDisk"
)
}
guard let destinationPath = message.string(key: RuntimeKeys.destinationPath.rawValue) else {
throw ContainerizationError(
.invalidArgument,
message: "no destination path supplied for snapshotDisk"
)
}
let ctr = try getContainer()
// Freeze the filesystem
try await ctr.container.filesystemOperation(operation: .freeze, path: "/")
do {
// Clone the filesystem image atomically while frozen
try FileManager.default.copyItem(atPath: imagePath, toPath: destinationPath)
} catch {
// Ensure we thaw even on error
do {
try await ctr.container.filesystemOperation(operation: .thaw, path: "/")
} catch {
self.log.error(
"failed to thaw filesystem after snapshotDisk error",
metadata: [
"error": "\(error)"
])
}
throw error
}
// Thaw the filesystem
try await ctr.container.filesystemOperation(operation: .thaw, path: "/")
return message.reply()
default:
throw ContainerizationError(
.invalidState,
message: "cannot snapshot disk: container is not running"
)
}
}
/// Dial a vsock port on the virtual machine.
///
/// - Parameters:
/// - message: An XPC message with the following parameters:
/// - port: The port number.
///
/// - Returns: An XPC message with the following parameters:
/// - fd: The file descriptor for the vsock.
@Sendable
public func dial(_ message: XPCMessage) async throws -> XPCMessage {
self.log.debug("enter", metadata: ["func": "\(#function)"])
defer { self.log.debug("exit", metadata: ["func": "\(#function)"]) }
switch self.state {
case .running, .booted:
let port = message.uint64(key: RuntimeKeys.port.rawValue)
guard port > 0 else {
throw ContainerizationError(
.invalidArgument,
message: "no vsock port supplied for dial"
)
}
let ctr = try getContainer()
let fh = try await ctr.container.dialVsock(port: UInt32(port))
let reply = message.reply()
reply.set(key: RuntimeKeys.fd.rawValue, value: fh)
return reply
default:
throw ContainerizationError(
.invalidState,
message: "cannot dial: container is not running"
)
}
}
private func startInitProcess(lock: AsyncLock.Context) async throws {
let info = try self.getContainer()
let container = info.container
let id = container.id
guard self.state == .booted else {
throw ContainerizationError(
.invalidState,
message: "container expected to be in booted state, got: \(self.state)"
)
}
do {
let io = info.io
try await container.start()
let waitFunc: ExitMonitor.WaitHandler = {
let code = try await container.wait()
if let out = io.out {
try out.close()
}
if let err = io.err {
try err.close()
}
return code
}
try await self.monitor.track(id: id, waitingOn: waitFunc)
} catch {
try? await self.cleanUpContainer(containerInfo: info)
self.setState(.stopped)
throw error
}
}
private func startExecProcess(processId id: String, lock: AsyncLock.Context) async throws {
let container = try self.getContainer().container
guard let processInfo = self.processes[id] else {
throw ContainerizationError(.notFound, message: "process with id \(id)")
}
let containerInfo = try self.getContainer()
let czConfig = try self.configureProcessConfig(
config: processInfo.config,
stdio: processInfo.io,
containerConfig: containerInfo.config,
)
let process = try await container.exec(id, configuration: czConfig)
try self.setUnderlyingProcess(id, process)
try await process.start()
let waitFunc: ExitMonitor.WaitHandler = {
let code = try await process.wait()
if let out = processInfo.io[1] {
try self.closeHandle(out.fileDescriptor)
}
if let err = processInfo.io[2] {
try self.closeHandle(err.fileDescriptor)
}
return code
}
try await self.monitor.track(id: id, waitingOn: waitFunc)
}
private func startSocketForwarders(attachment: Attachment, publishedPorts: [PublishPort]) async throws {
guard !publishedPorts.isEmpty else {
return
}
LocalNetworkPrivacy.triggerLocalNetworkPrivacyAlert()
var forwarders: [SocketForwarderResult] = []
guard !publishedPorts.hasOverlaps() else {
throw ContainerizationError(.invalidArgument, message: "host ports for different publish port specs may not overlap")
}
try await withThrowingTaskGroup(of: SocketForwarderResult.self) { group in
for publishedPort in publishedPorts {
for index in 0..<publishedPort.count {
let proxyAddress = try SocketAddress(ipAddress: publishedPort.hostAddress.description, port: Int(publishedPort.hostPort + index))
let containerIPAddress: String
switch publishedPort.hostAddress {
case .v4(_):
containerIPAddress = attachment.ipv4Address.address.description
case .v6(_):
guard let ipv6Address = attachment.ipv6Address else {
throw ContainerizationError(.invalidState, message: "cannot configure IPv6 port forwarding for container with unknown IPv6 address")
}
containerIPAddress = ipv6Address.address.description
}
let serverAddress = try SocketAddress(ipAddress: containerIPAddress, port: Int(publishedPort.containerPort + index))
log.info(
"creating forwarder for",
metadata: [
"proxy": "\(proxyAddress)",
"server": "\(serverAddress)",
"protocol": "\(publishedPort.proto)",
])
group.addTask {
let forwarder: SocketForwarder
switch publishedPort.proto {
case .tcp:
forwarder = try TCPForwarder(
proxyAddress: proxyAddress,
serverAddress: serverAddress,
eventLoopGroup: self.eventLoopGroup,
log: self.log
)
case .udp:
forwarder = try UDPForwarder(
proxyAddress: proxyAddress,
serverAddress: serverAddress,
eventLoopGroup: self.eventLoopGroup,
log: self.log
)
}
do {
return try await forwarder.run().get()
} catch let error as IOError where error.errnoCode == EACCES {
if let port = proxyAddress.port, port < 1024 {
throw ContainerizationError(
.invalidArgument,
message: "Permission denied while binding to host port \(port). Binding to ports below 1024 requires root privileges."
)
}
throw error
}
}