-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathContainersService.swift
More file actions
1206 lines (1079 loc) · 43.1 KB
/
Copy pathContainersService.swift
File metadata and controls
1206 lines (1079 loc) · 43.1 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 CVersion
import ContainerAPIClient
import ContainerPersistence
import ContainerPlugin
import ContainerResource
import ContainerRuntimeClient
import ContainerXPC
import Containerization
import ContainerizationEXT4
import ContainerizationError
import ContainerizationExtras
import ContainerizationOCI
import ContainerizationOS
import Foundation
import Logging
import SystemPackage
public actor ContainersService {
struct ContainerState {
var snapshot: ContainerSnapshot
var client: RuntimeClient? = nil
func getClient() throws -> RuntimeClient {
guard let client else {
var message = "no runtime client exists"
if snapshot.status == .stopped {
message += ": container is stopped"
}
throw ContainerizationError(.invalidState, message: message)
}
return client
}
}
private static let machServicePrefix = "com.apple.container"
private static let launchdDomainString = try! ServiceManager.getDomainString()
private let log: Logger
private let debugHelpers: Bool
private let containerRoot: URL
private let pluginLoader: PluginLoader
private let runtimePlugins: [Plugin]
private let exitMonitor: ExitMonitor
private let containerSystemConfig: ContainerSystemConfig
private let lock: AsyncLock
private var containers: [String: ContainerState]
// FIXME: Find a better mechanism for services running on the APIServer to work with each other
private weak var networksService: NetworksService?
public init(
appRoot: URL,
pluginLoader: PluginLoader,
containerSystemConfig: ContainerSystemConfig,
log: Logger,
debugHelpers: Bool = false
) throws {
let containerRoot = appRoot.appendingPathComponent("containers")
try FileManager.default.createDirectory(at: containerRoot, withIntermediateDirectories: true)
self.exitMonitor = ExitMonitor(log: log)
self.lock = AsyncLock(log: log)
self.containerRoot = containerRoot
self.pluginLoader = pluginLoader
self.containerSystemConfig = containerSystemConfig
self.log = log
self.debugHelpers = debugHelpers
self.runtimePlugins = pluginLoader.findPlugins().filter { $0.hasType(.runtime) }
self.containers = try Self.loadAtBoot(root: containerRoot, loader: pluginLoader, log: log)
}
public func setNetworksService(_ service: NetworksService) async {
self.networksService = service
}
static func loadAtBoot(root: URL, loader: PluginLoader, log: Logger) throws -> [String: ContainerState] {
var directories = try FileManager.default.contentsOfDirectory(
at: root,
includingPropertiesForKeys: [.isDirectoryKey]
)
directories = directories.filter {
$0.isDirectory
}
let runtimePlugins = loader.findPlugins().filter { $0.hasType(.runtime) }
var results = [String: ContainerState]()
for dir in directories {
do {
let (config, options) = try Self.getContainerConfiguration(at: dir)
if options?.autoRemove ?? false {
log.info(
"reap auto-remove container",
metadata: [
"id": "\(config.id)"
])
let label = Self.fullLaunchdServiceLabel(
runtimeName: config.runtimeHandler,
instanceId: config.id)
var status: Int32 = -1
try? ServiceManager.deregister(fullServiceLabel: label, status: &status)
if status != 0 {
log.warning(
"failed to deregister service",
metadata: [
"id": "\(config.id)",
"service": "\(label)",
"status": "\(status)",
]
)
}
let bundle = ContainerResource.Bundle(path: dir)
try? bundle.delete()
continue
}
let state = ContainerState(
snapshot: .init(
configuration: config,
status: .stopped,
networks: [],
startedDate: nil
),
)
results[config.id] = state
guard runtimePlugins.first(where: { $0.name == config.runtimeHandler }) != nil else {
throw ContainerizationError(
.internalError,
message: "failed to find runtime plugin \(config.runtimeHandler)"
)
}
} catch {
try? FileManager.default.removeItem(at: dir)
log.warning(
"failed to load container",
metadata: [
"path": "\(dir.path)",
"error": "\(error)",
])
}
}
return results
}
/// List containers matching the given filters.
public func list(filters: ContainerListFilters = .all) async throws -> [ContainerSnapshot] {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)"
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)"
]
)
}
let labelPatterns: [(key: String, regex: Regex<AnyRegexOutput>)] = try filters.labels.map { key, pattern in
do {
return (key: key, regex: try Regex(pattern))
} catch {
throw ContainerizationError(
.invalidArgument, message: "failed to compile regex '\(pattern)' for \(key)",
cause: error)
}
}
return self.containers.values.compactMap { state -> ContainerSnapshot? in
let snapshot = state.snapshot
if !filters.ids.isEmpty {
guard filters.ids.contains(snapshot.id) else {
return nil
}
}
if let status = filters.status {
guard snapshot.status == status else {
return nil
}
}
for (key, regex) in labelPatterns {
let label = snapshot.configuration.labels[key] ?? ""
guard label.contains(regex) else {
return nil
}
}
return snapshot
}
}
/// Execute an operation with the current container list while maintaining atomicity
/// This prevents race conditions where containers are created during the operation
public func withContainerList<T: Sendable>(
logMetadata: Logger.Metadata? = nil,
_ operation: @Sendable @escaping ([ContainerSnapshot]) async throws -> T
) async throws -> T {
try await lock.withLock(logMetadata: logMetadata) { context in
let snapshots = await self.containers.values.map { $0.snapshot }
return try await operation(snapshots)
}
}
/// Calculate disk usage for containers
/// - Returns: Tuple of (total count, active count, total size, reclaimable size)
public func calculateDiskUsage() async -> (Int, Int, UInt64, UInt64) {
await lock.withLock(logMetadata: ["acquirer": "\(#function)"]) { _ in
var totalSize: UInt64 = 0
var reclaimableSize: UInt64 = 0
var activeCount = 0
for (id, state) in await self.containers {
let bundlePath = self.containerRoot.appendingPathComponent(id)
let containerSize = FileManager.default.allocatedSize(of: bundlePath)
totalSize += containerSize
if state.snapshot.status == .running {
activeCount += 1
} else {
// Stopped containers are reclaimable
reclaimableSize += containerSize
}
}
return (await self.containers.count, activeCount, totalSize, reclaimableSize)
}
}
/// Get set of image references used by containers (for disk usage calculation)
/// - Returns: Set of image references currently in use
public func getActiveImageReferences() async -> Set<String> {
await lock.withLock(logMetadata: ["acquirer": "\(#function)"]) { _ in
var imageRefs = Set<String>()
for (_, state) in await self.containers {
imageRefs.insert(state.snapshot.configuration.image.reference)
}
return imageRefs
}
}
/// Create a new container from the provided id and configuration.
public func create(configuration: ContainerConfiguration, kernel: Kernel, options: ContainerCreateOptions, initImage: String? = nil, runtimeData: Data? = nil) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(configuration.id)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(configuration.id)",
]
)
}
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(configuration.id)"]) { context in
guard await self.containers[configuration.id] == nil else {
throw ContainerizationError(
.exists,
message: "container already exists: \(configuration.id)"
)
}
var allHostnames = Set<String>()
for container in await self.containers.values {
for attachmentConfiguration in container.snapshot.configuration.networks {
allHostnames.insert(attachmentConfiguration.options.hostname)
}
}
var conflictingHostnames = [String]()
for attachmentConfiguration in configuration.networks {
if allHostnames.contains(attachmentConfiguration.options.hostname) {
conflictingHostnames.append(attachmentConfiguration.options.hostname)
}
}
guard conflictingHostnames.isEmpty else {
throw ContainerizationError(
.exists,
message: "hostname(s) already exist: \(conflictingHostnames)"
)
}
guard self.runtimePlugins.first(where: { $0.name == configuration.runtimeHandler }) != nil else {
throw ContainerizationError(
.notFound,
message: "unable to locate runtime plugin \(configuration.runtimeHandler)"
)
}
// Protect against a user providing a memory amount that will cause us to not be able
// to boot. We can go lower, but this is a somewhat safe threshold. Containerization
// also gives a little bit extra than the user asked for to account for guest agent overhead.
//
// NOTE: We could potentially leave this validation to the runtime service(s), as
// it's possible there could be an implementation that can get away with a lower
// amount and be perfectly safe.
let minimumMemory: UInt64 = 200.mib()
guard configuration.resources.memoryInBytes >= minimumMemory else {
throw ContainerizationError(
.invalidArgument,
message: "minimum memory amount allowed is 200 MiB (got \(configuration.resources.memoryInBytes) bytes)"
)
}
let path = self.containerRoot.appendingPathComponent(configuration.id)
let systemPlatform = kernel.platform
// Fetch init image (custom or default)
self.log.debug(
"ContainersService: get init block",
metadata: [
"id": "\(configuration.id)"
]
)
let initFilesystem = try await self.getInitBlock(for: systemPlatform.ociPlatform(), imageRef: initImage)
do {
self.log.debug(
"create snapshot",
metadata: [
"id": "\(configuration.id)",
"ref": "\(configuration.image.reference)",
])
let containerImage = ClientImage(description: configuration.image)
let imageFs = try await options.rootFsOverride == nil ? containerImage.getCreateSnapshot(platform: configuration.platform) : nil
self.log.debug(
"configure runtime",
metadata: [
"id": "\(configuration.id)",
"kernel": "\(kernel.path)",
"initfs": "\(initImage ?? self.containerSystemConfig.vminit.image)",
])
let runtimeConfig = RuntimeConfiguration(
path: path,
initialFilesystem: initFilesystem,
kernel: kernel,
containerConfiguration: configuration,
containerRootFilesystem: imageFs,
options: options,
runtimeData: runtimeData
)
try runtimeConfig.writeRuntimeConfiguration()
let snapshot = ContainerSnapshot(
configuration: configuration,
status: .stopped,
networks: [],
startedDate: nil
)
await self.setContainerState(configuration.id, ContainerState(snapshot: snapshot), context: context)
} catch {
throw error
}
}
}
/// Bootstrap the init process of the container.
public func bootstrap(id: String, stdio: [FileHandle?], dynamicEnv: [String: String]) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"env": "\(dynamicEnv)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(id)"]) { context in
var state = try await self.getContainerState(id: id, context: context)
// We've already bootstrapped this container. Ideally we should be able to
// return some sort of error code from the sandbox svc to check here, but this
// is also a very simple check and faster than doing an rpc to get the same result.
if state.client != nil {
return
}
let path = self.containerRoot.appendingPathComponent(id)
let (config, _) = try Self.getContainerConfiguration(at: path)
var networkBootstrapInfos = [NetworkBootstrapInfo]()
for n in config.networks {
guard let plugin = try await self.networksService?.plugin(for: n.network) else {
throw ContainerizationError(.internalError, message: "failed to get plugin for network \(n.network)")
}
networkBootstrapInfos.append(NetworkBootstrapInfo(plugin: plugin))
}
do {
try Self.registerService(
plugin: self.runtimePlugins.first { $0.name == config.runtimeHandler }!,
loader: self.pluginLoader,
configuration: config,
path: path,
debug: self.debugHelpers
)
let runtime = state.snapshot.configuration.runtimeHandler
let runtimeClient = try await RuntimeClient.create(
id: id,
runtime: runtime
)
try await runtimeClient.bootstrap(stdio: stdio, networkBootstrapInfos: networkBootstrapInfos, dynamicEnv: dynamicEnv)
try await self.exitMonitor.registerProcess(
id: id,
onExit: self.handleContainerExit
)
state.client = runtimeClient
await self.setContainerState(id, state, context: context)
} catch {
let label = Self.fullLaunchdServiceLabel(
runtimeName: config.runtimeHandler,
instanceId: id
)
await self.exitMonitor.stopTracking(id: id)
try? ServiceManager.deregister(fullServiceLabel: label)
throw error
}
}
}
/// Create a new process in the container.
public func createProcess(
id: String,
processID: String,
config: ProcessConfiguration,
stdio: [FileHandle?]
) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
"command": "\(config.arguments.isEmpty ? "" : config.arguments[0])",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
try await client.createProcess(
processID,
config: config,
stdio: stdio
)
}
/// Start a process in a container. This can either be a process created via
/// createProcess, or the init process of the container which requires
/// id == processID.
public func startProcess(id: String, processID: String) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
}
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(id)", "processId": "\(processID)"]) { context in
var state = try await self.getContainerState(id: id, context: context)
let isInit = Self.isInitProcess(id: id, processID: processID)
if state.snapshot.status == .running && isInit {
return
}
let client = try state.getClient()
try await client.startProcess(processID)
guard isInit else {
return
}
do {
let log = self.log
let waitFunc: ExitMonitor.WaitHandler = {
log.info("registering container with exit monitor")
let code = try await client.wait(id)
log.info(
"container finished in exit monitor",
metadata: [
"id": "\(id)",
"rc": "\(code)",
])
return code
}
try await self.exitMonitor.track(id: id, waitingOn: waitFunc)
let sandboxSnapshot = try await client.state()
state.snapshot.status = .running
state.snapshot.networks = sandboxSnapshot.networks
state.snapshot.startedDate = Date()
await self.setContainerState(id, state, context: context)
} catch {
await self.exitMonitor.stopTracking(id: id)
try? await client.stop(options: ContainerStopOptions.default)
throw error
}
}
}
/// Send a signal to the container.
public func kill(id: String, processID: String, signal: String) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
"signal": "\(signal)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
try await client.kill(processID, signal: signal)
// SIGKILL is guaranteed to terminate the target. When directed at the
// container's init process, follow up with the same API-server cleanup
// that `stop` performs.
if processID == id, (try? Signal(signal)) == .kill {
try await handleContainerExit(id: id)
}
}
/// Stop all containers inside the sandbox, aborting any processes currently
/// executing inside the container, before stopping the underlying sandbox.
public func stop(id: String, options: ContainerStopOptions) async throws {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
let state = try self._getContainerState(id: id)
// Stop should be idempotent.
let client: RuntimeClient
do {
client = try state.getClient()
} catch {
return
}
var resolvedOptions = options
if resolvedOptions.signal == nil, let stopSignal = state.snapshot.configuration.stopSignal {
resolvedOptions.signal = stopSignal
}
do {
try await client.stop(options: resolvedOptions)
} catch let err as ContainerizationError {
if err.code != .interrupted {
throw err
}
}
try await handleContainerExit(id: id)
}
public func dial(id: String, port: UInt32) async throws -> FileHandle {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"port": "\(port)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"port": "\(port)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
return try await client.dial(port)
}
/// Wait waits for the container's init process or exec to exit and returns the
/// exit status.
public func wait(id: String, processID: String) async throws -> ExitStatus {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
return try await client.wait(processID)
}
/// Resize resizes the container's PTY if one exists.
public func resize(id: String, processID: String, size: Terminal.Size) async throws {
log.trace(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
defer {
log.trace(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"processId": "\(processID)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
try await client.resize(processID, size: size)
}
// Get the logs for the container.
public func logs(id: String) async throws -> [FileHandle] {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
// Logs doesn't care if the container is running or not, just that
// the bundle is there, and that the files actually exist. We do
// first try and get the container state so we get a nicer error message
// (container foo not found) however.
do {
_ = try _getContainerState(id: id)
let path = self.containerRoot.appendingPathComponent(id)
let bundle = ContainerResource.Bundle(path: path)
return [
try FileHandle(forReadingFrom: bundle.containerLog),
try FileHandle(forReadingFrom: bundle.bootlog),
]
} catch {
throw ContainerizationError(
.internalError,
message: "failed to open container logs: \(error)"
)
}
}
/// Copy a file or directory from the host into the container.
public func copyIn(id: String, source: String, destination: String, mode: UInt32, createParents: Bool = true) async throws {
self.log.debug("\(#function)")
let state = try self._getContainerState(id: id)
guard state.snapshot.status == .running else {
throw ContainerizationError(.invalidState, message: "container \(id) is not running")
}
let client = try state.getClient()
try await client.copyIn(source: source, destination: destination, mode: mode, createParents: createParents)
}
/// Copy a file or directory from the container to the host.
public func copyOut(id: String, source: String, destination: String, createParents: Bool = true) async throws {
self.log.debug("\(#function)")
let state = try self._getContainerState(id: id)
guard state.snapshot.status == .running else {
throw ContainerizationError(.invalidState, message: "container \(id) is not running")
}
let client = try state.getClient()
try await client.copyOut(source: source, destination: destination, createParents: createParents)
}
/// Get statistics for the container.
public func stats(id: String) async throws -> ContainerStats {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
let state = try self._getContainerState(id: id)
let client = try state.getClient()
return try await client.statistics()
}
/// Delete a container and its resources.
public func delete(id: String, force: Bool) async throws {
log.info(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
"force": "\(force)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
let state = try self._getContainerState(id: id)
switch state.snapshot.status {
case .running:
if !force {
throw ContainerizationError(
.invalidState,
message: "container \(id) is \(state.snapshot.status) and can not be deleted"
)
}
let opts = ContainerStopOptions(
timeoutInSeconds: 5,
signal: "SIGKILL"
)
let client = try state.getClient()
try await client.stop(options: opts)
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(id)"]) { context in
self.log.info(
"ContainersService: attempt cleanup",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
try await self.cleanUp(id: id, context: context)
self.log.info(
"ContainersService: successful cleanup",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
case .stopping:
throw ContainerizationError(
.invalidState,
message: "container \(id) is \(state.snapshot.status) and can not be deleted"
)
default:
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(id)"]) { context in
try await self.cleanUp(id: id, context: context)
}
}
}
public func containerDiskUsage(id: String) async throws -> UInt64 {
log.debug(
"ContainersService: enter",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
defer {
log.debug(
"ContainersService: exit",
metadata: [
"func": "\(#function)",
"id": "\(id)",
]
)
}
let containerPath = self.containerRoot.appendingPathComponent(id).path
return FileManager.default.allocatedSize(of: URL(fileURLWithPath: containerPath))
}
public func exportRootfs(id: String, archive: URL, live: Bool = false) async throws {
self.log.debug("\(#function)")
let state = try self._getContainerState(id: id)
guard state.snapshot.status == .stopped || (live && state.snapshot.status == .running) else {
throw ContainerizationError(.invalidState, message: "container is not stopped")
}
let path = self.containerRoot.appendingPathComponent(id)
let bundle = ContainerResource.Bundle(path: path)
let rootfs = bundle.containerRootfsBlock
if live {
let client = try state.getClient()
let snapshot = rootfs.appendingPathExtension("snapshot")
defer { try? FileManager.default.removeItem(at: snapshot) }
try await client.snapshotDisk(imagePath: rootfs.path, destinationPath: snapshot.path)
try EXT4.EXT4Reader(blockDevice: FilePath(snapshot)).export(archive: FilePath(archive))
return
}
try EXT4.EXT4Reader(blockDevice: FilePath(rootfs)).export(archive: FilePath(archive))
}
private func handleContainerExit(id: String, code: ExitStatus? = nil) async throws {
try await self.lock.withLock(logMetadata: ["acquirer": "\(#function)", "id": "\(id)"]) { [self] context in
try await handleContainerExit(id: id, code: code, context: context)
}
}
private func handleContainerExit(id: String, code: ExitStatus?, context: AsyncLock.Context) async throws {
if let code {
self.log.info(
"handling container exit",
metadata: [
"id": "\(id)",
"rc": "\(code)",
])
}
var state: ContainerState
do {
state = try self.getContainerState(id: id, context: context)
if state.snapshot.status == .stopped {
return
}
} catch {
// Was auto removed by the background thread, nothing for us to do.
return
}
await self.exitMonitor.stopTracking(id: id)
// Shutdown and deregister the runtime service
self.log.info("shutting down runtime service", metadata: ["id": "\(id)"])
let path = self.containerRoot.appendingPathComponent(id)
let bundle = ContainerResource.Bundle(path: path)
let config = try bundle.configuration
let label = Self.fullLaunchdServiceLabel(
runtimeName: config.runtimeHandler,
instanceId: id
)
// Try to shutdown the client gracefully, but if the runtime service
// is already dead (e.g., killed externally), we should still continue
// with state cleanup.
if let client = state.client {
do {
try await client.shutdown()
} catch {
self.log.error(
"failed to shutdown runtime service",
metadata: [
"id": "\(id)",
"error": "\(error)",
])
}
}
// Deregister the service, launchd will terminate the process.
// This may also fail if the service was already deregistered or
// the process was killed externally.
do {
try ServiceManager.deregister(fullServiceLabel: label)
self.log.info("deregistered runtime service", metadata: ["id": "\(id)"])
} catch {
self.log.error(
"failed to deregister runtime service",
metadata: [
"id": "\(id)",
"error": "\(error)",
])
}
state.snapshot.status = .stopped
state.snapshot.networks = []
state.client = nil
await self.setContainerState(id, state, context: context)
let options = try getContainerCreationOptions(id: id)