-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathComposeOrchestratorRuntimeSupport.swift
More file actions
954 lines (871 loc) · 40.8 KB
/
Copy pathComposeOrchestratorRuntimeSupport.swift
File metadata and controls
954 lines (871 loc) · 40.8 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
//===----------------------------------------------------------------------===//
// Copyright © 2026 container-compose 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 Foundation
struct ComposeRuntimeUnsupportedValue {
let composeName: String
let value: String
let reason: String
}
struct ComposeRuntimeUnsupportedField {
let composeName: String
let reason: String
}
private struct ComposeRuntimeUnsupportedOptionalValue {
let composeName: String
let value: String?
let reason: String
}
extension ComposeOrchestrator {
/// Validates all selected services before any runtime side effects occur.
func validateRuntimeSupport(
services: [ComposeService],
project: ComposeProject,
validateDependencies: Bool = true,
) throws {
for service in services {
try validateRuntimeSupport(service: service, project: project, validateDependencies: validateDependencies)
}
}
/// Returns unsupported string-valued fields that need missing runtime primitives.
func unsupportedRuntimeStringFields(service: ComposeService) -> [ComposeRuntimeUnsupportedValue] {
[
ComposeRuntimeUnsupportedOptionalValue(
composeName: "isolation",
value: service.isolation,
reason: "isolation support needs an apple/container runtime gap PR",
),
].compactMap { candidate in
guard let value = candidate.value, !value.isEmpty else {
return nil
}
return ComposeRuntimeUnsupportedValue(
composeName: candidate.composeName,
value: value,
reason: candidate.reason,
)
}
}
/// Returns the apple/container PID namespace argument for Docker-compatible
/// Compose PID modes. The runtime already creates a private PID namespace by
/// default, so only the explicit host mode needs an argument.
func runtimePIDArgument(service: ComposeService) throws -> String? {
try runtimeHostPrivateNamespaceArgument(service: service, value: service.pid, composeName: "pid")
}
/// Returns the apple/container cgroup namespace argument for Docker-compatible
/// Compose cgroup modes. The runtime already creates a private cgroup namespace
/// by default, so only the explicit host mode needs an argument.
func runtimeCgroupNamespaceArgument(service: ComposeService) throws -> String? {
try runtimeHostPrivateNamespaceArgument(service: service, value: service.cgroup, composeName: "cgroup")
}
/// Returns a safe relative cgroup parent for the generic Linux guest
/// runtime. The runtime owns `/container` and creates each service as a
/// leaf below that guest-only hierarchy.
func runtimeCgroupParentArgument(service: ComposeService) throws -> String? {
guard let parent = service.cgroupParent, !parent.isEmpty else {
return nil
}
let components = parent.split(separator: "/", omittingEmptySubsequences: false)
guard
!parent.hasPrefix("/"),
components.allSatisfy({ !$0.isEmpty && $0 != "." && $0 != ".." })
else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses invalid cgroup_parent '\(parent)'; expected a non-empty relative path without empty, '.' or '..' components",
)
}
return parent
}
/// Returns the apple/container IPC namespace argument for Docker-compatible
/// Compose IPC modes. The runtime already creates a private namespace by
/// default, so only the explicit host mode needs an argument. Namespace
/// sharing (`shareable` and `service:NAME`) remains unsupported.
func runtimeIPCNamespaceArgument(service: ComposeService) throws -> String? {
try runtimeHostPrivateNamespaceArgument(service: service, value: service.ipc, composeName: "ipc")
}
/// Returns the apple/container UTS namespace argument for Docker-compatible
/// Compose UTS modes. The runtime already creates a private namespace by
/// default, so only the explicit host mode needs an argument.
func runtimeUTSNamespaceArgument(service: ComposeService) throws -> String? {
try runtimeHostPrivateNamespaceArgument(service: service, value: service.uts, composeName: "uts")
}
/// Returns the guest user namespace argument for Docker Compose modes.
///
/// `host` accurately preserves the sandbox VM's existing user namespace.
/// `private` creates an identity-mapped namespace inside that guest. Neither
/// mode joins or exposes a macOS host user namespace.
func runtimeUserNamespaceArgument(service: ComposeService) throws -> String? {
guard let value = service.usernsMode, !value.isEmpty else {
return nil
}
switch value {
case "host":
return nil
case "private":
return "private"
default:
throw ComposeError.unsupported(
"service '\(service.name)' uses userns_mode '\(value)'; only host and private are supported by the local runtime",
)
}
}
private func runtimeHostPrivateNamespaceArgument(
service: ComposeService,
value: String?,
composeName: String,
) throws -> String? {
guard let value, !value.isEmpty else {
return nil
}
switch value {
case "host":
return "host"
case "private":
return nil
default:
throw ComposeError.unsupported(
"service '\(service.name)' uses \(composeName) '\(value)'; supported values are host and private",
)
}
}
/// Returns unsupported CPU scheduler fields beyond the supported `cpus`,
/// `cpuset`, and relative `cpu_shares` controls.
func unsupportedCPUResourceFields(service: ComposeService) -> [ComposeRuntimeUnsupportedValue] {
let reason = "advanced CPU resource support needs an apple/container runtime gap PR"
var fields: [ComposeRuntimeUnsupportedValue] = []
appendUnsupportedIntegerField("cpu_count", value: service.cpuCount, reason: reason, to: &fields)
appendUnsupportedFloatingPointField("cpu_percent", value: service.cpuPercent, reason: reason, to: &fields)
appendUnsupportedIntegerField("cpu_rt_period", value: service.cpuRealtimePeriod, reason: reason, to: &fields)
appendUnsupportedIntegerField("cpu_rt_runtime", value: service.cpuRealtimeRuntime, reason: reason, to: &fields)
return fields
}
/// Returns unsupported memory, OOM, and process resource controls beyond
/// `mem_limit`, `mem_reservation`, and `oom_score_adj`.
func unsupportedMemoryAndProcessResourceFields(service: ComposeService) -> [ComposeRuntimeUnsupportedValue] {
let reason = "memory, OOM, and process resource support needs an apple/container runtime gap PR"
var fields: [ComposeRuntimeUnsupportedValue] = []
appendUnsupportedStringField("mem_swappiness", value: service.memSwappiness, reason: reason, to: &fields)
if service.oomKillDisable == true {
fields.append(.init(composeName: "oom_kill_disable", value: "true", reason: reason))
}
return fields
}
/// Returns a Linux-compatible OOM score adjustment for the service process.
func runtimeOOMScoreAdj(service: ComposeService) throws -> Int? {
guard let oomScoreAdj = service.oomScoreAdj else {
return nil
}
guard (-1000 ... 1000).contains(oomScoreAdj) else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses oom_score_adj '\(oomScoreAdj)' outside the supported range -1000...1000",
)
}
return oomScoreAdj
}
/// Returns a Docker-compatible relative CPU scheduling weight. Zero leaves
/// the runtime default unchanged; non-zero weights start at two.
func runtimeCPUShares(service: ComposeService) throws -> UInt64? {
guard let cpuShares = service.cpuShares, cpuShares != 0 else {
return nil
}
guard cpuShares >= 2 else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses cpu_shares '\(cpuShares)'; cpu_shares must be 0 or at least 2",
)
}
return UInt64(cpuShares)
}
/// Returns a Docker-compatible soft memory reservation in bytes. Zero
/// leaves the runtime default unchanged; an explicit hard memory limit must
/// be strictly higher than the reservation.
func runtimeMemoryReservationInBytes(service: ComposeService) throws -> Int64? {
guard let reservation = service.memReservation, !reservation.isEmpty else {
return nil
}
guard let reservationInBytes = Int64(reservation), reservationInBytes >= 0 else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses invalid mem_reservation '\(reservation)'; expected a non-negative byte value",
)
}
guard reservationInBytes != 0 else {
return nil
}
if let memoryLimit = service.memLimit, !memoryLimit.isEmpty,
let memoryLimitInBytes = Int64(memoryLimit), reservationInBytes >= memoryLimitInBytes
{
throw ComposeError.invalidProject(
"service '\(service.name)' uses mem_reservation '\(reservation)'; mem_reservation must be lower than mem_limit '\(memoryLimit)'",
)
}
return reservationInBytes
}
/// Returns Docker-compatible combined memory and swap usage in bytes. A
/// zero value is treated as unset; when a hard memory limit is set without
/// an explicit swap value, Docker limits total memory plus swap to twice
/// the hard memory limit.
func runtimeMemorySwapLimitInBytes(service: ComposeService) throws -> Int64? {
let requestedLimit: Int64?
if let swapLimit = service.memSwapLimit, !swapLimit.isEmpty {
guard let parsedLimit = Int64(swapLimit), parsedLimit == -1 || parsedLimit >= 0 else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses invalid memswap_limit '\(swapLimit)'; expected -1, 0, or a positive byte value",
)
}
requestedLimit = parsedLimit == 0 ? nil : parsedLimit
} else {
requestedLimit = nil
}
guard let memoryLimit = service.memLimit, !memoryLimit.isEmpty else {
guard requestedLimit == nil else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses memswap_limit; memswap_limit requires a positive mem_limit",
)
}
return nil
}
guard let memoryLimitInBytes = Int64(memoryLimit), memoryLimitInBytes > 0 else {
guard requestedLimit == nil else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses memswap_limit; memswap_limit requires a positive mem_limit",
)
}
return nil
}
if let requestedLimit {
guard requestedLimit == -1 || requestedLimit >= memoryLimitInBytes else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses memswap_limit '\(requestedLimit)'; memswap_limit must be at least mem_limit '\(memoryLimit)'",
)
}
return requestedLimit
}
let (defaultLimit, overflow) = memoryLimitInBytes.multipliedReportingOverflow(by: 2)
guard !overflow else {
throw ComposeError.invalidProject(
"service '\(service.name)' uses mem_limit '\(memoryLimit)'; Docker-compatible default memswap_limit exceeds the runtime range",
)
}
return defaultLimit
}
/// Splits Compose supplemental groups into numeric IDs and guest-image group names.
func runtimeSupplementalGroups(service: ComposeService) throws -> (ids: [UInt32], names: [String]) {
var identifiers: [UInt32] = []
var names: [String] = []
var seenIdentifiers = Set<UInt32>()
var seenNames = Set<String>()
for group in service.groupAdd ?? [] {
guard !group.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
throw ComposeError.invalidProject("service '\(service.name)' uses an empty group_add value")
}
if let identifier = UInt32(group) {
if seenIdentifiers.insert(identifier).inserted {
identifiers.append(identifier)
}
} else if group.allSatisfy(\.isNumber) {
throw ComposeError.invalidProject("service '\(service.name)' uses group_add numeric ID '\(group)' outside the UInt32 range")
} else if seenNames.insert(group).inserted {
names.append(group)
}
}
return (identifiers, names)
}
/// Returns repeatable generic runtime arguments for numeric IDs and named groups.
func runtimeSupplementalGroupArguments(service: ComposeService) throws -> [String] {
let groups = try runtimeSupplementalGroups(service: service)
return groups.ids.map(String.init) + groups.names
}
/// Returns unsupported credential access fields.
func unsupportedDeviceAccessFields(service: ComposeService) -> [ComposeRuntimeUnsupportedField] {
var fields: [ComposeRuntimeUnsupportedField] = []
if service.credentialSpec != nil {
fields.append(.init(
composeName: "credential_spec",
reason: "credential spec support needs an apple/container runtime gap PR",
))
}
return fields
}
/// Returns the runtime gap that prevents a dependency condition.
func unsupportedDependencyConditionReason(_ condition: String) -> String {
switch condition {
case "service_healthy":
"health status support requires apple/container healthcheck runtime support"
case "service_completed_successfully":
"exit code and completion time need an apple/container runtime gap PR"
default:
"dependency condition support needs an apple/container runtime gap PR"
}
}
/// Returns logging and storage fields that need apple/container runtime primitives.
func unsupportedServiceMetadataAndLoggingFields(service: ComposeService) -> [ComposeRuntimeUnsupportedField] {
var fields: [ComposeRuntimeUnsupportedField] = []
let loggingReason = "service logging driver/options need an apple/container runtime gap PR"
if !options.runtimeCapabilities.supportsLoggingDriversV1,
!isSupportedRuntimeLogging(service.logging)
{
fields.append(.init(composeName: "logging", reason: loggingReason))
}
if !options.runtimeCapabilities.supportsLoggingDriversV1, service.logging == nil {
if let logDriver = service.logDriver,
!logDriver.isEmpty,
!isSupportedRuntimeLogDriver(logDriver)
{
fields.append(.init(composeName: "log_driver", reason: loggingReason))
}
if !isSupportedLegacyRuntimeLogOptions(service: service) {
fields.append(.init(composeName: "log_opt", reason: loggingReason))
}
}
if let storageOptions = service.storageOptions, !storageOptions.isEmpty {
fields.append(.init(
composeName: "storage_opt",
reason: "per-container storage options need an apple/container rootfs storage runtime gap PR",
))
}
return fields
}
/// Returns whether Compose logging maps to an apple/container runtime log policy.
func isSupportedRuntimeLogging(_ logging: ComposeLogConfiguration?) -> Bool {
guard let logging else {
return true
}
return isSupportedRuntimeLogDriver(logging.driver) &&
isSupportedRuntimeLogOptions(logging.options, driver: logging.driver)
}
/// Returns whether a logging driver can be represented by apple/container.
func isSupportedRuntimeLogDriver(_ driver: String?) -> Bool {
driver == nil || driver == "json-file" || driver == "local" || driver == "none"
}
/// Returns whether Compose logging options map to local apple/container options.
func isSupportedRuntimeLogOptions(_ options: [String: String], driver: String?) -> Bool {
if options.isEmpty {
return true
}
guard driver != "none" else {
return false
}
return options.keys.allSatisfy(isSupportedRuntimeLogOptionKey)
}
/// Returns whether legacy Compose log options map to local apple/container options.
func isSupportedLegacyRuntimeLogOptions(service: ComposeService) -> Bool {
guard let logOptions = service.logOptions, !logOptions.isEmpty else {
return true
}
guard isSupportedRuntimeLogDriver(service.logDriver), service.logDriver != "none" else {
return false
}
return logOptions.keys.allSatisfy(isSupportedRuntimeLogOptionKey)
}
/// Returns whether an option key is supported by apple/container local logging.
func isSupportedRuntimeLogOptionKey(_ key: String) -> Bool {
key == "max-size" || key == "max-file"
}
/// Returns the Compose-owned typed logging policy for service create/run.
func runtimeLogConfiguration(service: ComposeService) throws -> ComposeLogConfiguration {
ComposeLogConfiguration(
driver: runtimeLogDriver(service: service),
options: runtimeLogOptions(service: service),
)
}
/// Returns the runtime log driver name from Compose's legacy and structured fields.
func runtimeLogDriver(service: ComposeService) -> String? {
if let logging = service.logging {
return logging.driver
}
return service.logDriver
}
/// Returns normalized local logging options from Compose's legacy and structured fields.
func runtimeLogOptions(service: ComposeService) -> [String: String] {
if let logging = service.logging {
return logging.options
}
return service.logOptions ?? [:]
}
/// Returns the runtime log driver override needed for non-default Compose logging.
func runtimeLogDriverArgument(service: ComposeService) throws -> String? {
let configuration = try runtimeLogConfiguration(service: service)
if options.runtimeCapabilities.supportsLoggingDriversV1 {
return configuration.driver
}
try validateLegacyRuntimeLogConfiguration(configuration, serviceName: service.name)
return configuration.driver == "none" ? "none" : nil
}
/// Returns lossless negotiated options or the legacy local-only projection.
func runtimeLogOptionArguments(service: ComposeService) throws -> [String] {
let configuration = try runtimeLogConfiguration(service: service)
if !options.runtimeCapabilities.supportsLoggingDriversV1 {
try validateLegacyRuntimeLogConfiguration(configuration, serviceName: service.name)
}
return configuration.options.sorted(by: { $0.key < $1.key }).flatMap { key, value in
["--log-opt", "\(key)=\(value)"]
}
}
/// Validates the temporary v1 CLI projection without changing the
/// lossless request carried by the Compose plan.
func validateLegacyRuntimeLogConfiguration(
_ configuration: ComposeLogConfiguration,
serviceName: String,
) throws {
switch configuration.driver {
case nil, "", "json-file", "local":
break
case "none":
guard configuration.options.isEmpty else {
throw ComposeError.unsupported("service '\(serviceName)' uses logging options with driver 'none'; log options are only supported with local logging")
}
return
case let driver?:
throw ComposeError.unsupported("service '\(serviceName)' uses unsupported logging driver '\(driver)'; supported drivers are json-file, local, and none")
}
for (key, value) in configuration.options {
switch key {
case "max-size":
_ = try logOptionSizeInBytes(value, serviceName: serviceName)
case "max-file":
_ = try logOptionFileCount(value, serviceName: serviceName)
default:
throw ComposeError.unsupported("service '\(serviceName)' uses unsupported logging option '\(key)'; supported options are max-size and max-file")
}
}
}
/// Parses a Compose log size option into bytes.
func logOptionSizeInBytes(_ value: String, serviceName: String) throws -> UInt64 {
let bytes: Double
do {
bytes = try ComposeByteSizeParser.bytes(value)
} catch {
throw ComposeError.invalidProject("service '\(serviceName)' logging option max-size '\(value)' must be a size")
}
guard bytes.isFinite, bytes > 0, bytes <= Double(UInt64.max) else {
throw ComposeError.invalidProject("service '\(serviceName)' logging option max-size '\(value)' is outside the supported range")
}
return UInt64(bytes)
}
/// Parses a Compose log file-count option.
func logOptionFileCount(_ value: String, serviceName: String) throws -> Int {
guard let count = Int(value), count > 0 else {
throw ComposeError.invalidProject("service '\(serviceName)' logging option max-file '\(value)' must be a positive integer")
}
return count
}
/// Returns the runtime hostname argument for Compose `hostname`.
func runtimeHostnameArgument(service: ComposeService) throws -> String? {
guard let hostname = service.hostname?.trimmingCharacters(in: .whitespacesAndNewlines), !hostname.isEmpty else {
return nil
}
return try validatedRFC1123Hostname(hostname, field: "hostname", service: service)
}
/// Returns the runtime NIS domain-name argument for Compose `domainname`.
func runtimeDomainnameArgument(service: ComposeService) throws -> String? {
let domainName = service.domainName?.trimmingCharacters(
in: .whitespacesAndNewlines,
)
guard let domainName, !domainName.isEmpty else {
return nil
}
return try validatedRFC1123Hostname(domainName, field: "domainname", service: service)
}
/// Validates a Compose hostname using RFC1123 label rules.
func validatedRFC1123Hostname(_ raw: String, field: String, service: ComposeService) throws -> String {
guard let hostname = canonicalRFC1123Hostname(raw) else {
throw invalidRFC1123HostnameError(raw, field: field, service: service)
}
return hostname
}
/// Returns runtime host-entry arguments for Compose `extra_hosts`.
func runtimeExtraHostArguments(service: ComposeService) throws -> [String] {
try runtimeHostEntries(service: service).flatMap { entry in
entry.hostnames.map { hostname in
"\(hostname):\(entry.ipAddress)"
}
}
}
/// Returns typed host entries for Compose `extra_hosts`.
func runtimeHostEntries(service: ComposeService) throws -> [ComposeHostEntry] {
try (service.extraHosts ?? []).map { raw in
try runtimeHostEntry(raw, service: service)
}
}
/// Returns runtime sysctl arguments for Compose `sysctls`.
func runtimeSysctlArguments(service: ComposeService) throws -> [String] {
try runtimeSysctls(service: service)
.sorted(by: { $0.key < $1.key })
.map { name, value in
"\(name)=\(value)"
}
}
/// Returns typed sysctl values for `ContainerConfiguration.sysctls`.
func runtimeSysctls(service: ComposeService) throws -> [String: String] {
try (service.sysctls ?? [:]).reduce(into: [String: String]()) { result, item in
let trimmedName = item.key.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedName.isEmpty else {
throw ComposeError.invalidProject("service '\(service.name)' uses sysctls with an empty name")
}
guard !trimmedName.contains("=") else {
throw ComposeError.invalidProject("service '\(service.name)' uses sysctl name '\(trimmedName)'; sysctl names must not contain '='")
}
result[trimmedName] = item.value
}
}
/// Returns a Docker-compatible positive pids cgroup limit for service create/run.
/// Docker Compose local mode preserves non-positive values in config output
/// but does not project them to Docker Engine HostConfig.
func runtimePidsLimitArgument(service: ComposeService) -> String? {
guard let pidsLimit = service.pidsLimit, pidsLimit > 0 else {
return nil
}
return "\(pidsLimit)"
}
/// Converts Compose `blkio_config` into apple/container#1595 `--blkio`
/// specifications. Device path resolution stays inside apple/container.
func runtimeBlkioArguments(service: ComposeService) throws -> [String] {
guard let blkio = service.blkioConfig else {
return []
}
var result: [String] = []
if let weight = blkio.weight {
try validateBlockIOWeight(weight, serviceName: service.name, field: "blkio_config.weight")
result.append("weight=\(weight)")
}
for device in blkio.weightDevice ?? [] {
try validateBlockIODevicePath(
device.path,
serviceName: service.name,
field: "blkio_config.weight_device.path",
)
try validateBlockIOWeight(
device.weight,
serviceName: service.name,
field: "blkio_config.weight_device.weight",
)
result.append("device=\(device.path),weight=\(device.weight)")
}
try appendThrottleArguments(
blkio.deviceReadBps,
key: "read-bps",
field: "blkio_config.device_read_bps",
serviceName: service.name,
to: &result,
)
try appendThrottleArguments(
blkio.deviceWriteBps,
key: "write-bps",
field: "blkio_config.device_write_bps",
serviceName: service.name,
to: &result,
)
try appendThrottleArguments(
blkio.deviceReadIOps,
key: "read-iops",
field: "blkio_config.device_read_iops",
serviceName: service.name,
to: &result,
)
try appendThrottleArguments(
blkio.deviceWriteIOps,
key: "write-iops",
field: "blkio_config.device_write_iops",
serviceName: service.name,
to: &result,
)
return result
}
/// Returns Docker-compatible device cgroup rules for service create/run.
func runtimeDeviceCgroupRuleArguments(service: ComposeService) throws -> [String] {
guard let rules = service.deviceCgroupRules, !rules.isEmpty else {
return []
}
do {
try ComposeRuntimeInputParser.validateDeviceCgroupRules(rules)
} catch {
throw ComposeError.invalidProject("service '\(service.name)' has invalid device_cgroup_rules; entries must use '<type> <major>:<minor> <access>' such as 'c 1:3 mr'")
}
return rules
}
/// Returns Docker-compatible Linux device mappings for service create/run.
func runtimeDeviceArguments(service: ComposeService) throws -> [String] {
guard let devices = service.devices, !devices.isEmpty else {
return []
}
do {
return try devices.map { try runtimeDeviceArgument($0) }
} catch {
throw ComposeError.invalidProject("service '\(service.name)' has invalid devices; entries must use HOST[:CONTAINER[:PERMISSIONS]] with absolute paths and r/w/m permissions")
}
}
/// Returns Docker-compatible GPU requests for service create/run.
func runtimeGPUArguments(service: ComposeService) throws -> [String] {
let values = (service.gpus ?? []) + (service.deployGPURequests ?? [])
guard !values.isEmpty else {
return []
}
let arguments: [String]
do {
arguments = try values.map(runtimeGPUArgument)
} catch let error as ComposeError {
throw error
} catch {
throw ComposeError.invalidProject("service '\(service.name)' has an invalid GPU device request")
}
let requests: [ComposeGPURequest]
do {
requests = try ComposeRuntimeInputParser.gpuRequests(arguments)
} catch {
throw ComposeError.invalidProject("service '\(service.name)' has an invalid GPU device request")
}
try validateGPUBackendSupport(requests, serviceName: service.name)
return arguments
}
private func runtimeGPUArgument(_ value: ComposeValue) throws -> String {
switch value {
case let .string(spec):
return spec
case let .object(object):
return try runtimeGPUArgument(object)
default:
throw ComposeError.invalidProject("GPU request must be a string or object")
}
}
private func runtimeGPUArgument(_ object: [String: ComposeValue]) throws -> String {
let driver = try optionalGPUStringField("driver", in: object)
let count = try optionalGPUCountField("count", in: object)
let deviceIDs = try optionalGPUStringArrayField("device_ids", in: object)
let capabilities = try optionalGPUStringArrayField("capabilities", in: object)
let options = try optionalGPUStringMapField("options", in: object)
if count != nil, !(deviceIDs ?? []).isEmpty {
throw ComposeError.invalidProject("GPU request count and device_ids are mutually exclusive")
}
let onlyGenericGPU = driver == nil
&& options == nil
&& (capabilities ?? []).allSatisfy { $0 == "gpu" }
if onlyGenericGPU {
if count == "-1" {
return "all"
}
if count == nil, deviceIDs == ["0"] {
return "device=0"
}
}
var fields: [String] = []
if let driver {
fields.append("driver=\(driver)")
}
if let count {
fields.append("count=\(count == "-1" ? "all" : count)")
}
if let deviceIDs, !deviceIDs.isEmpty {
fields.append("device=\(csvQuoteIfNeeded(deviceIDs.joined(separator: ",")))")
}
if let capabilities, !capabilities.isEmpty, capabilities != ["gpu"] {
fields.append("capabilities=\(csvQuoteIfNeeded(capabilities.joined(separator: ",")))")
}
if let options, !options.isEmpty {
let value = options.sorted(by: { $0.key < $1.key })
.map { "\($0.key)=\($0.value)" }
.joined(separator: ",")
fields.append("options=\(csvQuoteIfNeeded(value))")
}
if fields.isEmpty {
return "count=1"
}
return fields.joined(separator: ",")
}
private func validateGPUBackendSupport(_ requests: [ComposeGPURequest], serviceName: String) throws {
guard requests.count == 1 else {
throw ComposeError.unsupported("service '\(serviceName)' requests multiple GPUs; the Apple virtio-gpu backend exposes one GPU")
}
let request = requests[0]
guard request.driver.isEmpty || request.driver == "virtio" else {
throw ComposeError.unsupported("service '\(serviceName)' requests GPU driver '\(request.driver)'; the Apple backend supports only virtio-gpu")
}
guard request.options.isEmpty else {
throw ComposeError.unsupported("service '\(serviceName)' uses GPU driver options; the Apple virtio-gpu backend does not expose driver options")
}
guard request.capabilities.allSatisfy({ $0 == "gpu" }) else {
throw ComposeError.unsupported("service '\(serviceName)' requests GPU capabilities beyond 'gpu'; the Apple virtio-gpu backend exposes only the generic GPU capability")
}
if request.deviceIDs.isEmpty {
guard request.count == -1 || request.count == 1 else {
throw ComposeError.unsupported("service '\(serviceName)' requests \(request.count) GPUs; the Apple virtio-gpu backend exposes one GPU")
}
} else {
guard request.count == 0, request.deviceIDs == ["0"] else {
throw ComposeError.unsupported("service '\(serviceName)' requests GPU device IDs \(request.deviceIDs.joined(separator: ",")); the Apple virtio-gpu backend exposes only device 0")
}
}
}
private func optionalGPUStringField(_ name: String, in object: [String: ComposeValue]) throws -> String? {
guard let value = object[name] else {
return nil
}
guard case let .string(string) = value else {
throw ComposeError.invalidProject("GPU request \(name) must be a string")
}
return string
}
private func optionalGPUCountField(_ name: String, in object: [String: ComposeValue]) throws -> String? {
guard let value = object[name] else {
return nil
}
switch value {
case let .number(number):
let decimal = NSDecimalNumber(decimal: number)
guard decimal.doubleValue.rounded() == decimal.doubleValue else {
throw ComposeError.invalidProject("GPU request \(name) must be 'all' or an integer")
}
return decimal.stringValue
case let .string(string):
guard string == "all" || Int(string) != nil else {
throw ComposeError.invalidProject("GPU request \(name) must be 'all' or an integer")
}
return string == "all" ? "-1" : string
default:
throw ComposeError.invalidProject("GPU request \(name) must be 'all' or an integer")
}
}
private func optionalGPUStringArrayField(_ name: String, in object: [String: ComposeValue]) throws -> [String]? {
guard let value = object[name] else {
return nil
}
guard case let .array(values) = value else {
throw ComposeError.invalidProject("GPU request \(name) must be a list")
}
return try values.map {
guard case let .string(string) = $0 else {
throw ComposeError.invalidProject("GPU request \(name) entries must be strings")
}
return string
}
}
private func optionalGPUStringMapField(_ name: String, in object: [String: ComposeValue]) throws -> [String: String]? {
guard let value = object[name] else {
return nil
}
guard case let .object(values) = value else {
throw ComposeError.invalidProject("GPU request \(name) must be a mapping")
}
return try values.mapValues {
guard case let .string(string) = $0 else {
throw ComposeError.invalidProject("GPU request \(name) values must be strings")
}
return string
}
}
private func csvQuoteIfNeeded(_ value: String) -> String {
guard value.contains(",") || value.contains("\"") else {
return value
}
return "\"\(value.replacingOccurrences(of: "\"", with: "\"\""))\""
}
private func runtimeDeviceArgument(_ value: ComposeValue) throws -> String {
switch value {
case let .string(spec):
return try runtimeDeviceArgument(spec)
case let .object(object):
guard case let .string(source)? = object["source"] else {
throw ComposeError.invalidProject("missing device source")
}
let target = try optionalStringField("target", in: object)
let permissions = try optionalStringField("permissions", in: object)
return try runtimeDeviceArgument(source: source, target: target, permissions: permissions)
default:
throw ComposeError.invalidProject("invalid device value")
}
}
private func runtimeDeviceArgument(_ spec: String) throws -> String {
let parts = spec.split(separator: ":", omittingEmptySubsequences: false).map(String.init)
guard !parts.isEmpty, parts.count <= 3 else {
throw ComposeError.invalidProject("invalid device string")
}
let source = parts[0]
let target = parts.count >= 2 ? parts[1] : nil
let permissions = parts.count == 3 ? parts[2] : nil
return try runtimeDeviceArgument(source: source, target: target, permissions: permissions)
}
private func runtimeDeviceArgument(source: String, target: String?, permissions: String?) throws -> String {
guard isAbsoluteDevicePath(source) else {
throw ComposeError.invalidProject("device source must be absolute")
}
if let target, !isAbsoluteDevicePath(target) {
throw ComposeError.invalidProject("device target must be absolute")
}
if let permissions, !isDevicePermissions(permissions) {
throw ComposeError.invalidProject("invalid device permissions")
}
return if let target, let permissions {
"\(source):\(target):\(permissions)"
} else if let target {
"\(source):\(target)"
} else if let permissions {
"\(source):\(permissions)"
} else {
source
}
}
private func optionalStringField(_ name: String, in object: [String: ComposeValue]) throws -> String? {
guard let value = object[name] else {
return nil
}
guard case let .string(rawValue) = value else {
throw ComposeError.invalidProject("device \(name) must be a string")
}
return rawValue
}
private func isAbsoluteDevicePath(_ value: String) -> Bool {
value.hasPrefix("/") && !value.isEmpty
}
private func isDevicePermissions(_ value: String) -> Bool {
let allowed = Set("rwm")
return !value.isEmpty && value.allSatisfy { allowed.contains($0) }
}
/// Canonicalizes one Compose host entry into the typed runtime hosts entry.
func runtimeHostEntry(_ raw: String, service: ComposeService) throws -> ComposeHostEntry {
let separator = raw.firstIndex(of: "=") ?? raw.firstIndex(of: ":")
guard let separator else {
throw ComposeError.invalidProject("service '\(service.name)' extra_hosts entry '\(raw)' must use HOST=IP or HOST:IP")
}
let hostname = String(raw[..<separator]).trimmingCharacters(in: .whitespacesAndNewlines)
let rawAddress = String(raw[raw.index(after: separator)...]).trimmingCharacters(in: .whitespacesAndNewlines)
guard !hostname.isEmpty else {
throw ComposeError.invalidProject("service '\(service.name)' extra_hosts entry '\(raw)' has an empty hostname")
}
guard !rawAddress.isEmpty else {
throw ComposeError.invalidProject("service '\(service.name)' extra_hosts entry '\(raw)' has an empty IP address")
}
if rawAddress == ComposeHostEntry.hostGatewayAddress {
return ComposeHostEntry(
ipAddress: ComposeHostEntry.hostGatewayAddress,
hostnames: [hostname],
)
}
let ipAddress = unbracketedIPAddress(rawAddress)
guard isValidIPAddress(ipAddress) else {
throw ComposeError.invalidProject("service '\(service.name)' extra_hosts entry '\(raw)' has invalid IP address '\(rawAddress)'")
}
return ComposeHostEntry(ipAddress: ipAddress, hostnames: [hostname])
}
/// Canonicalizes one Compose host entry into the runtime `--add-host` form.
func runtimeExtraHostArgument(_ raw: String, service: ComposeService) throws -> String {
let entry = try runtimeHostEntry(raw, service: service)
return entry.hostnames.map { "\($0):\(entry.ipAddress)" }.joined(separator: " ")
}
/// Removes brackets accepted by Compose around IPv6 literals.
func unbracketedIPAddress(_ value: String) -> String {
if value.hasPrefix("["), value.hasSuffix("]") {
return String(value.dropFirst().dropLast())
}
return value
}
}