-
Notifications
You must be signed in to change notification settings - Fork 709
Expand file tree
/
Copy pathImagesService.swift
More file actions
569 lines (516 loc) · 20.1 KB
/
ImagesService.swift
File metadata and controls
569 lines (516 loc) · 20.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
//===----------------------------------------------------------------------===//
// 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 ContainerAPIClient
import ContainerImagesServiceClient
import ContainerResource
import Containerization
import ContainerizationArchive
import ContainerizationError
import ContainerizationExtras
import ContainerizationOCI
import Foundation
import Logging
import TerminalProgress
public actor ImagesService {
private let log: Logger
private let contentStore: ContentStore
private let imageStore: ImageStore
private let snapshotStore: SnapshotStore
public init(contentStore: ContentStore, imageStore: ImageStore, snapshotStore: SnapshotStore, log: Logger) throws {
self.contentStore = contentStore
self.imageStore = imageStore
self.snapshotStore = snapshotStore
self.log = log
}
private func _list() async throws -> [Containerization.Image] {
try await imageStore.list()
}
private func _get(_ reference: String) async throws -> Containerization.Image {
try await imageStore.get(reference: reference)
}
private func _get(_ description: ImageDescription) async throws -> Containerization.Image {
let exists = try await self._get(description.reference)
guard exists.descriptor == description.descriptor else {
throw ContainerizationError(.invalidState, message: "descriptor mismatch: expected \(description.descriptor), got \(exists.descriptor)")
}
return exists
}
public func list() async throws -> [ImageDescription] {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)"
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)"
]
)
}
return try await imageStore.list().map { $0.description.fromCZ }
}
public func pull(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?, maxConcurrentDownloads: Int = 3) async throws
-> ImageDescription
{
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
"platform": "\(String(describing: platform))",
"insecure": "\(insecure)",
"maxConcurrentDownloads": "\(maxConcurrentDownloads)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
"platform": "\(String(describing: platform))",
]
)
}
let img = try await Self.withAuthentication(ref: reference) { auth in
try await self.imageStore.pull(
reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate),
maxConcurrentDownloads: maxConcurrentDownloads)
}
guard let img else {
throw ContainerizationError(.internalError, message: "failed to pull image \(reference)")
}
return img.description.fromCZ
}
public func push(reference: String, platform: Platform?, insecure: Bool, progressUpdate: ProgressUpdateHandler?) async throws {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
"platform": "\(String(describing: platform))",
"insecure": "\(insecure)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
"platform": "\(String(describing: platform))",
]
)
}
try await Self.withAuthentication(ref: reference) { auth in
try await self.imageStore.push(
reference: reference, platform: platform, insecure: insecure, auth: auth, progress: ContainerizationProgressAdapter.handler(from: progressUpdate))
}
}
public func pushAllTags(repositoryName: String, platform: Platform?, insecure: Bool, maxConcurrentUploads: Int, progressUpdate: ProgressUpdateHandler?) async throws
-> [ImageDescription]
{
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"repositoryName": "\(repositoryName)",
"platform": "\(String(describing: platform))",
"insecure": "\(insecure)",
"maxConcurrentUploads": "\(maxConcurrentUploads)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"repositoryName": "\(repositoryName)",
"platform": "\(String(describing: platform))",
]
)
}
let allImages = try await imageStore.list()
let matchingImages = allImages.filter { image in
guard !Utility.isInfraImage(name: image.reference) else { return false }
guard let ref = try? Reference.parse(image.reference) else { return false }
let resolvedName: String
if let resolved = ref.resolvedDomain {
resolvedName = "\(resolved)/\(ref.path)"
} else {
resolvedName = ref.name
}
return resolvedName == repositoryName
}
guard !matchingImages.isEmpty else {
throw ContainerizationError(.notFound, message: "no tags found for repository \(repositoryName)")
}
let maxConcurrent = maxConcurrentUploads > 0 ? maxConcurrentUploads : 3
try await Self.withAuthentication(ref: repositoryName) { auth in
let progress = ContainerizationProgressAdapter.handler(from: progressUpdate)
var iterator = matchingImages.makeIterator()
var failures: [(reference: String, message: String)] = []
await withTaskGroup(of: (String, String?).self) { group in
for _ in 0..<maxConcurrent {
guard let image = iterator.next() else { break }
let ref = image.reference
group.addTask {
do {
try await self.imageStore.push(
reference: ref, platform: platform, insecure: insecure, auth: auth, progress: progress)
return (ref, nil)
} catch {
return (ref, String(describing: error))
}
}
}
for await (ref, error) in group {
if let error {
failures.append((ref, error))
}
if let image = iterator.next() {
let nextRef = image.reference
group.addTask {
do {
try await self.imageStore.push(
reference: nextRef, platform: platform, insecure: insecure, auth: auth, progress: progress)
return (nextRef, nil)
} catch {
return (nextRef, String(describing: error))
}
}
}
}
}
if !failures.isEmpty {
let details = failures.map { "\($0.reference): \($0.message)" }.joined(separator: "\n")
throw ContainerizationError(.internalError, message: "failed to push one or more tags:\n\(details)")
}
}
return matchingImages.map { $0.description.fromCZ }
}
public func tag(old: String, new: String) async throws -> ImageDescription {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"old": "\(old)",
"new": "\(new)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"old": "\(old)",
"new": "\(new)",
]
)
}
let img = try await self.imageStore.tag(existing: old, new: new)
return img.description.fromCZ
}
public func delete(reference: String, garbageCollect: Bool) async throws {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"ref": "\(reference)",
]
)
}
try await self.imageStore.delete(reference: reference, performCleanup: garbageCollect)
}
public func save(references: [String], out: URL, platform: Platform?) async throws {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"references": "\(references)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"references": "\(references)",
]
)
}
let tempDir = FileManager.default.uniqueTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: tempDir)
}
try await self.imageStore.save(references: references, out: tempDir, platform: platform)
let writer = try ArchiveWriter(format: .pax, filter: .none, file: out)
try writer.archiveDirectory(tempDir)
try writer.finishEncoding()
}
public func load(from tarFile: URL, force: Bool) async throws -> ([ImageDescription], [String]) {
let archivePathname = tarFile.absolutePath()
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"archivePath": "\(archivePathname)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"archivePath": "\(archivePathname)",
]
)
}
let reader = try ArchiveReader(file: tarFile)
let tempDir = FileManager.default.uniqueTemporaryDirectory()
defer {
try? FileManager.default.removeItem(at: tempDir)
}
let rejectedMembers = try reader.extractContents(to: tempDir)
guard rejectedMembers.isEmpty || force else {
throw ContainerizationError(.invalidArgument, message: "cannot load tar image with rejected paths: \(rejectedMembers)")
}
let loaded = try await self.imageStore.load(from: tempDir)
var images: [ImageDescription] = []
for image in loaded {
images.append(image.description.fromCZ)
}
return (images, rejectedMembers)
}
public func cleanUpOrphanedBlobs() async throws -> ([String], UInt64) {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)"
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)"
]
)
}
let images = try await self._list()
let freedSnapshotBytes = try await self.snapshotStore.clean(keepingSnapshotsFor: images)
let (deleted, freedContentBytes) = try await self.imageStore.cleanUpOrphanedBlobs()
return (deleted, freedContentBytes + freedSnapshotBytes)
}
/// Calculate disk usage for images
/// - Parameter activeReferences: Set of image references currently in use by containers
/// - Returns: Tuple of (total count, active count, total size, reclaimable size)
public func calculateDiskUsage(activeReferences: Set<String>) async throws -> (Int, Int, UInt64, UInt64) {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"references": "\(activeReferences)",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"references": "\(activeReferences)",
]
)
}
let images = try await self._list()
var totalSize: UInt64 = 0
var reclaimableSize: UInt64 = 0
var activeCount = 0
for image in images {
// Calculate size for all platform variants
let imageSize = try await self.calculateImageSize(image)
totalSize += imageSize
// Check if image is referenced by any container
let isActive = activeReferences.contains(image.reference)
if isActive {
activeCount += 1
} else {
reclaimableSize += imageSize
}
}
return (images.count, activeCount, totalSize, reclaimableSize)
}
/// Calculate total size for an image including all platform variants
private func calculateImageSize(_ image: Containerization.Image) async throws -> UInt64 {
var totalSize: UInt64 = 0
let index = try await image.index()
for descriptor in index.manifests {
// Skip attestation manifests
if let refType = descriptor.annotations?["vnd.docker.reference.type"],
refType == "attestation-manifest"
{
continue
}
guard descriptor.platform != nil else { continue }
// Get snapshot size for this platform
if let snapshotSize = try? await self.snapshotStore.getSnapshotSize(descriptor: descriptor) {
totalSize += snapshotSize
}
}
return totalSize
}
}
// MARK: Image Snapshot Methods
extension ImagesService {
public func unpack(description: ImageDescription, platform: Platform?, progressUpdate: ProgressUpdateHandler?) async throws {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
}
let img = try await self._get(description)
try await self.snapshotStore.unpack(image: img, platform: platform, progressUpdate: progressUpdate)
}
public func deleteImageSnapshot(description: ImageDescription, platform: Platform?) async throws {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
}
let img = try await self._get(description)
try await self.snapshotStore.delete(for: img, platform: platform)
}
public func getImageSnapshot(description: ImageDescription, platform: Platform) async throws -> Filesystem {
self.log.debug(
"ImagesService: enter",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
defer {
self.log.debug(
"ImagesService: exit",
metadata: [
"func": "\(#function)",
"description": "\(description)",
"platform": "\(String(describing: platform))",
]
)
}
let img = try await self._get(description)
return try await self.snapshotStore.get(for: img, platform: platform)
}
}
// MARK: Static Methods
extension ImagesService {
private static func withAuthentication<T>(
ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?
) async throws -> T? {
var authentication: Authentication?
let ref = try Reference.parse(ref)
guard let host = ref.resolvedDomain else {
throw ContainerizationError(.invalidArgument, message: "no host specified in image reference: \(ref)")
}
authentication = Self.authenticationFromEnv(host: host)
if let authentication {
return try await body(authentication)
}
let keychain = KeychainHelper(securityDomain: Constants.keychainID)
do {
authentication = try keychain.lookup(hostname: host)
} catch let err as KeychainHelper.Error {
guard case .keyNotFound = err else {
throw ContainerizationError(.internalError, message: "error querying keychain for \(host)", cause: err)
}
}
do {
return try await body(authentication)
} catch let err as RegistryClient.Error {
guard case .invalidStatus(_, let status, _) = err else {
throw err
}
guard status == .unauthorized || status == .forbidden else {
throw err
}
guard authentication != nil else {
throw ContainerizationError(.internalError, message: "\(String(describing: err)), no credentials found for host \(host)")
}
throw err
}
}
private static func authenticationFromEnv(host: String) -> Authentication? {
let env = ProcessInfo.processInfo.environment
guard env["CONTAINER_REGISTRY_HOST"] == host else {
return nil
}
guard let user = env["CONTAINER_REGISTRY_USER"], let password = env["CONTAINER_REGISTRY_TOKEN"] else {
return nil
}
return BasicAuthentication(username: user, password: password)
}
}
extension ImageDescription {
public var toCZ: Containerization.Image.Description {
.init(reference: self.reference, descriptor: self.descriptor)
}
}
extension Containerization.Image.Description {
public var fromCZ: ImageDescription {
.init(
reference: self.reference,
descriptor: self.descriptor
)
}
}