Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
import ArgumentParser
import CZlib
import CommonCrypto
import Compression
import Darwin
import Foundation
import Swift
// Extension to calculate SHA256 hash
extension Data {
func sha256String() -> String {
let hash = self.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256(bytes.baseAddress, CC_LONG(self.count), &hash)
return hash
}
return hash.map { String(format: "%02x", $0) }.joined()
}
}
// Streaming SHA256 of a file; disk layers can be multi-GB so we hash in chunks.
func sha256OfFile(at url: URL) throws -> String {
let handle = try FileHandle(forReadingFrom: url)
defer { try? handle.close() }
var context = CC_SHA256_CTX()
CC_SHA256_Init(&context)
let chunkSize = 4 * 1024 * 1024 // 4 MiB
while true {
let data = handle.readData(ofLength: chunkSize)
if data.isEmpty { break }
data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) in
_ = CC_SHA256_Update(&context, ptr.baseAddress, CC_LONG(data.count))
}
}
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256_Final(&hash, &context)
return hash.map { String(format: "%02x", $0) }.joined()
}
private let sparseHoleGranularityBytes = 4 * 1024 * 1024
private let sparseZeroChunk = Data(count: sparseHoleGranularityBytes)
/// Gunzip-decompress a chunk and write it sparsely into an output file handle,
/// skipping zero-filled 4 MiB blocks to create holes in the sparse file.
func gunzipChunkAndWriteSparse(
inputPath: URL, outputHandle: FileHandle, startOffset: UInt64
) throws -> UInt64 {
try gunzipChunkAndWriteSparse(
inputPath: inputPath, outputHandle: outputHandle, startOffsets: [startOffset])
}
/// Decompresses a gzip blob once and writes it sparsely at every offset in
/// `startOffsets` (a blob that several disk parts share, such as an all-zero
/// chunk). Returns the decompressed size of the blob.
func gunzipChunkAndWriteSparse(
inputPath: URL, outputHandle: FileHandle, startOffsets: [UInt64]
) throws -> UInt64 {
guard FileManager.default.fileExists(atPath: inputPath.path) else {
throw PullError.layerDownloadFailed(inputPath.lastPathComponent)
}
// Apple's Compression framework (.zlib) only handles raw DEFLATE, not
// gzip headers, so stream through the system gunzip executable first.
let decompressedPath = inputPath.appendingPathExtension("raw")
defer { try? FileManager.default.removeItem(at: decompressedPath) }
FileManager.default.createFile(atPath: decompressedPath.path, contents: nil)
let tempHandle = try FileHandle(forWritingTo: decompressedPath)
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/gunzip")
process.arguments = ["-c", inputPath.path]
process.standardOutput = tempHandle
try process.run()
// Poll instead of waitUntilExit so a cancelled pull stops gunzip at once.
while process.isRunning {
if Task.isCancelled {
process.terminate()
process.waitUntilExit()
try? tempHandle.close()
throw CancellationError()
}
usleep(20_000)
}
try tempHandle.close()
if Task.isCancelled { throw CancellationError() }
guard process.terminationStatus == 0 else {
throw PullError.layerDownloadFailed(inputPath.lastPathComponent)
}
return try writeFileSparse(decompressedPath, to: outputHandle, startOffsets: startOffsets)
}
func writeFileSparse(
_ url: URL, to outputHandle: FileHandle, startOffsets: [UInt64]
) throws -> UInt64 {
let readHandle = try FileHandle(forReadingFrom: url)
defer { try? readHandle.close() }
let blockSize = sparseHoleGranularityBytes
// One offset: stream the blob once, skipping all-zero blocks.
if startOffsets.count == 1 {
var currentWriteOffset = startOffsets[0]
var totalDecompressedBytes: UInt64 = 0
while true {
// A cancelled pull stops between blocks instead of finishing the chunk.
if Task.isCancelled { throw CancellationError() }
let written: Int = try autoreleasepool {
let data = readHandle.readData(ofLength: blockSize)
if data.isEmpty { return 0 }
if !(data.count == blockSize && data == sparseZeroChunk) {
try outputHandle.seek(toOffset: currentWriteOffset)
try outputHandle.write(contentsOf: data)
}
return data.count
}
if written == 0 { break }
currentWriteOffset += UInt64(written)
totalDecompressedBytes += UInt64(written)
}
return totalDecompressedBytes
}
// Several offsets: find the blocks that hold data once, then write only
// those at each offset. A shared all-zero blob (common in disk images)
// then costs one scan instead of one full pass per offset.
var dataBlocks: [UInt64] = []
var totalDecompressedBytes: UInt64 = 0
while true {
if Task.isCancelled { throw CancellationError() }
let count: Int = autoreleasepool {
let data = readHandle.readData(ofLength: blockSize)
if data.isEmpty { return 0 }
if !(data.count == blockSize && data == sparseZeroChunk) {
dataBlocks.append(totalDecompressedBytes)
}
return data.count
}
if count == 0 { break }
totalDecompressedBytes += UInt64(count)
}
for startOffset in startOffsets {
for blockOffset in dataBlocks {
if Task.isCancelled { throw CancellationError() }
try autoreleasepool {
try readHandle.seek(toOffset: blockOffset)
let data = readHandle.readData(ofLength: blockSize)
try outputHandle.seek(toOffset: startOffset + blockOffset)
try outputHandle.write(contentsOf: data)
}
}
}
return totalDecompressedBytes
}
// Push-related errors
enum PushError: Error {
case uploadInitiationFailed
case blobUploadFailed
case manifestPushFailed
case authenticationFailed
case missingToken
case invalidURL
case lz4NotFound // Added error case
case invalidMediaType // Added during part refactoring
case missingUncompressedSizeAnnotation // Added for sparse file handling
case fileCreationFailed(String) // Added for sparse file handling
case reassemblySetupFailed(path: String, underlyingError: Error?) // Added for sparse file handling
case missingPart(Int) // Added for sparse file handling
case layerDownloadFailed(String) // Added for download retries
case manifestFetchFailed // Added for manifest fetching
case insufficientPermissions(String) // Added for permission issues
}
// Define a specific error type for when no underlying error exists
struct NoSpecificUnderlyingError: Error, CustomStringConvertible {
var description: String { "No specific underlying error was provided." }
}
struct ChunkMetadata: Codable {
let uncompressedDigest: String
let uncompressedSize: UInt64
let compressedDigest: String
let compressedSize: Int
}
// Define struct to decode relevant parts of config.json
struct OCIManifestLayer {
let mediaType: String
let size: Int
let digest: String
let uncompressedSize: UInt64?
let uncompressedContentDigest: String?
init(
mediaType: String, size: Int, digest: String, uncompressedSize: UInt64? = nil,
uncompressedContentDigest: String? = nil
) {
self.mediaType = mediaType
self.size = size
self.digest = digest
self.uncompressedSize = uncompressedSize
self.uncompressedContentDigest = uncompressedContentDigest
}
}
struct OCIConfig: Codable {
struct Annotations: Codable {
let uncompressedSize: String? // Use optional String
enum CodingKeys: String, CodingKey {
case uncompressedSize = "com.trycua.lume.disk.uncompressed_size"
}
}
let annotations: Annotations? // Optional annotations
}
struct Layer: Codable, Equatable, Sendable {
let mediaType: String
let digest: String
let size: Int
let annotations: [String: String]?
}
struct OCIChunkReference: Equatable, Sendable {
let index: Int
let offset: UInt64
}
struct OCIChunkGroup: Equatable, Sendable {
let layer: Layer
var references: [OCIChunkReference]
}
/// Groups logical disk parts by their shared OCI blob while preserving the
/// order in which each unique digest first appears in the manifest.
func groupOCIChunksByDigest(_ layers: [Layer]) -> [OCIChunkGroup] {
var groups: [OCIChunkGroup] = []
var groupIndexByDigest: [String: Int] = [:]
for (index, layer) in layers.enumerated() {
let reference = OCIChunkReference(
index: index,
offset: UInt64(layer.annotations?[OCIAnnotation.partOffset] ?? "0") ?? 0)
if let groupIndex = groupIndexByDigest[layer.digest] {
groups[groupIndex].references.append(reference)
} else {
groupIndexByDigest[layer.digest] = groups.count
groups.append(OCIChunkGroup(layer: layer, references: [reference]))
}
}
return groups
}
func uniqueLayersByDigest(_ layers: [Layer]) -> [Layer] {
var seenDigests: Swift.Set<String> = []
return layers.filter { seenDigests.insert($0.digest).inserted }
}
struct Manifest: Codable {
let layers: [Layer]
let config: Layer?
let mediaType: String
let schemaVersion: Int
let annotations: [String: String]?
}
// MARK: - OCI-Compliant Format (kubelet-compatible)
enum ImageFormat {
case oci // kubelet-compatible: single gzip-compressed disk, trycua media types
case legacy // Lume legacy: LZ4-chunked disk, trycua media types
}
/// Media type constants for the OCI image format.
enum OCIMediaType {
static let config = "application/vnd.trycua.lume.config.v1+json"
static let disk = "application/vnd.trycua.lume.disk.v1"
static let nvram = "application/vnd.trycua.lume.nvram.v1"
static let standardTarLayer = "application/vnd.oci.image.layer.v1.tar"
static func detect(_ manifest: Manifest) -> ImageFormat {
let hasOCIDisk = manifest.layers.contains { $0.mediaType == disk }
let hasOCIConfig = manifest.config?.mediaType == config
return (hasOCIDisk || hasOCIConfig) ? .oci : .legacy
}
static func rawDiskPart(_ layer: Layer) -> (number: Int, total: Int)? {
let fields = layer.mediaType.lowercased().split(separator: ";").map {
$0.trimmingCharacters(in: .whitespaces)
}
guard fields.first == standardTarLayer,
layer.annotations?["org.opencontainers.image.title"]?.hasPrefix("disk.img.part.")
== true
else {
return nil
}
var parameters: [String: Int] = [:]
for field in fields.dropFirst() {
let pair = field.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
.map { $0.trimmingCharacters(in: .whitespaces) }
guard pair.count == 2, !pair[0].isEmpty else { return (0, 0) }
parameters[pair[0]] = Int(pair[1])
}
return (parameters["part.number"] ?? 0, parameters["part.total"] ?? 0)
}
static func validateRawDiskParts(_ manifest: Manifest) throws {
let parts = manifest.layers.compactMap(rawDiskPart)
guard !parts.isEmpty else { return }
guard parts.map({ $0.number }).sorted() == Array(1...parts.count),
parts.allSatisfy({ $0.total == parts.count }),
!manifest.layers.contains(where: { $0.mediaType == "application/octet-stream+lz4" })
else {
throw PullError.reassemblyFailed(
"raw OCI disk parts must be numbered 1...part.total without LZ4 parts")
}
}
}
/// Annotation keys for multi-layer chunked disk images.
enum OCIAnnotation {
static let partNumber = "org.trycua.lume.part.number"
static let partTotal = "org.trycua.lume.part.total"
static let partOffset = "org.trycua.lume.part.offset"
static let chunkSize = "org.trycua.lume.chunk.size"
}
/// Where chunked disk layers fail to cover a disk of `total` bytes: the first
/// gap or overlap (chunks as `(offset, size)`), or nil when they tile it
/// exactly. A push that lost chunks published a manifest whose layers leave
/// holes; reassembling it leaves those ranges zero and the guest's file
/// system corrupt, so pull refuses it and push never writes one.
func diskChunkCoverageGap(_ chunks: [(offset: UInt64, size: UInt64)], total: UInt64) -> String? {
var next: UInt64 = 0
for chunk in chunks.sorted(by: { $0.offset < $1.offset }) {
if chunk.offset > next {
return "bytes \(next)..<\(chunk.offset) are in no disk layer"
}
if chunk.offset < next {
return "disk layers overlap at byte \(chunk.offset)"
}
next = chunk.offset + chunk.size
}
if next < total {
return "bytes \(next)..<\(total) are in no disk layer"
}
if next > total {
return "disk layers end at byte \(next), past the disk's \(total) bytes"
}
return nil
}
/// Holds per-chunk upload results for manifest construction.
struct DiskChunkDescriptor {
let partNumber: Int
let compressedDigest: String
let compressedSize: Int
let uncompressedDigest: String
let uncompressedSize: UInt64
let diskOffset: UInt64
}
/// OCI config JSON structure for lume VM images.
struct LumeOCIConfig: Codable {
let mediatype: String?
let os: String
let hardwareModel: String
let machineIdentifier: String
let storage: [LumeStorageItem]?
}
struct LumeStorageItem: Codable {
let mediatype: String
let file: String
}
struct RepositoryTag: Codable {
let name: String
let tags: [String]
}
struct RepositoryList: Codable {
let repositories: [String]
}
struct RepositoryTags: Codable {
let name: String
let tags: [String]
}
struct CachedImage {
let repository: String
let imageId: String
let manifestId: String
}
struct ImageMetadata: Codable {
let image: String
let manifestId: String
let timestamp: Date
}
// Actor to safely collect disk part information from concurrent tasks
actor DiskPartsCollector {
// Store tuples of (sequentialPartNum, url)
private var diskParts: [(Int, URL)] = []
// Restore internal counter
private var partCounter = 0
// Adds a part and returns its assigned sequential number
func addPart(url: URL, number: Int? = nil) -> Int {
let partNum = number ?? partCounter + 1
partCounter = max(partCounter, partNum)
diskParts.append((partNum, url)) // Store sequential number
return partNum // Return assigned sequential number
}
// Sort by the sequential part number (index 0 of tuple)
func getSortedParts() -> [(Int, URL)] {
return diskParts.sorted { $0.0 < $1.0 }
}
// Restore getTotalParts
func getTotalParts() -> Int {
return partCounter
}
}
/// Tracks image download progress at byte granularity.
///
/// Bytes are counted as they arrive: each in-flight layer transfer reports its
/// running byte count under a unique id, a finished layer moves its bytes into
/// the completed total, and a failed attempt drops its in-flight bytes again so
/// a retry never counts the same bytes twice. Layers copied from the local
/// cache count as done at once but do not feed the transfer rate.
actor ProgressTracker {
/// Minimum time between two progress reports (about 6 per second).
static let defaultEmitInterval: TimeInterval = 0.15
/// Time constant of the exponentially weighted transfer rate.
static let rateTimeConstant: TimeInterval = 2.0
private var totalBytes: Int64 = 0
/// Bytes of layers that finished (downloaded and verified, or copied from cache).
private var completedBytes: Int64 = 0
/// Bytes received so far by transfers that have not finished yet, by transfer id.
private var inFlight: [String: Int64] = [:]
/// Transfer ids that finished or were dropped; late updates for them are ignored.
private var closedTransfers: Swift.Set<String> = []
/// Bytes that actually came over the network (monotonic, drives the rate).
private var transferredBytes: Int64 = 0
private var totalFiles: Int = 0
var onProgress: PullProgressHandler? = nil
private let now: @Sendable () -> Date
private let emitInterval: TimeInterval
private let printsToTerminal: Bool
// Rate tracking
private var startTime: Date
private var lastEmitTime: Date?
private var lastEmitTransferred: Int64 = 0
private var smoothedSpeed: Double = 0
private var hasRateSample = false
private var peakSpeed: Double = 0
private var speedSamples: [Double] = []
private var totalElapsedTime: TimeInterval = 0
private var emitCount = 0
init(
now: @escaping @Sendable () -> Date = { Date() },
emitInterval: TimeInterval = ProgressTracker.defaultEmitInterval,
printsToTerminal: Bool = true
) {
self.now = now
self.emitInterval = emitInterval
self.printsToTerminal = printsToTerminal
self.startTime = now()
}
func setProgressHandler(_ handler: @escaping PullProgressHandler) {
onProgress = handler
}
func setTotal(_ total: Int64, files: Int) {
totalBytes = total
totalFiles = files
startTime = now()
lastEmitTime = nil
lastEmitTransferred = transferredBytes
smoothedSpeed = 0
hasRateSample = false
emit(force: true)
}
/// Counts `bytes` as done at once (a layer copied from the local cache).
func addProgress(_ bytes: Int64) {
completedBytes += max(0, bytes)
emit(force: false)
}
/// Records that transfer `id` has received `bytesWritten` bytes so far.
func updateTransfer(id: String, bytesWritten: Int64) {
guard !closedTransfers.contains(id) else { return }
let previous = inFlight[id] ?? 0
guard bytesWritten > previous else { return }
inFlight[id] = bytesWritten
transferredBytes += bytesWritten - previous
emit(force: false)
}
/// Drops the in-flight bytes of transfer `id` (the attempt failed or was cancelled).
func dropTransfer(id: String) {
closedTransfers.insert(id)
if inFlight.removeValue(forKey: id) != nil {
emit(force: false)
}
}
/// Marks transfer `id` as finished: its `bytes` count as completed.
func finishTransfer(id: String, bytes: Int64) {
closedTransfers.insert(id)
inFlight.removeValue(forKey: id)
completedBytes += max(0, bytes)
emit(force: false)
}
/// The current progress, with downloaded bytes capped at the total.
func snapshot() -> PullProgress {
let raw = completedBytes + inFlight.values.reduce(0, +)
let downloaded = totalBytes > 0 ? min(raw, totalBytes) : raw
let percent = totalBytes > 0 ? Double(downloaded) / Double(totalBytes) * 100.0 : 0.0
return PullProgress(
percent: percent,
downloadedBytes: downloaded,
totalBytes: totalBytes,
bytesPerSecond: smoothedSpeed)
}
/// How many times the progress handler has been called (for tests).
func emittedCount() -> Int { emitCount }
private func emit(force: Bool) {
let t = now()
let current = snapshot()
let done = totalBytes > 0 && current.downloadedBytes >= totalBytes
if let last = lastEmitTime, !force, !done, t.timeIntervalSince(last) < emitInterval {
return
}
updateRate(at: t)
let progress = snapshot()
emitCount += 1
onProgress?(progress)
if printsToTerminal {
logSpeedProgress(
current: progress.percent / 100.0,
currentSpeed: speedSamples.last ?? 0,
averageSpeed: calculateAverageSpeed(),
smoothedSpeed: smoothedSpeed,
overallSpeed: totalElapsedTime > 0
? Double(transferredBytes) / totalElapsedTime : 0,
peakSpeed: peakSpeed,
context: "Downloading Image"
)
}
}
/// Updates the smoothed rate from the bytes transferred since the last report.
/// The weight of a sample grows with the time it covers, so the rate does not
/// depend on how often reports happen.
private func updateRate(at t: Date) {
defer {
lastEmitTime = t
lastEmitTransferred = transferredBytes
totalElapsedTime = t.timeIntervalSince(startTime)
}
guard let last = lastEmitTime else { return }
let dt = t.timeIntervalSince(last)
guard dt > 0 else { return }
let instant = Double(max(0, transferredBytes - lastEmitTransferred)) / dt
speedSamples.append(instant)
if speedSamples.count > 20 {
speedSamples.removeFirst(speedSamples.count - 20)
}
peakSpeed = max(peakSpeed, instant)
if !hasRateSample {
smoothedSpeed = instant
hasRateSample = true
} else {
let alpha = 1 - exp(-dt / Self.rateTimeConstant)
smoothedSpeed = alpha * instant + (1 - alpha) * smoothedSpeed
}
}
private func calculateAverageSpeed() -> Double {
guard !speedSamples.isEmpty else { return 0 }
// Use weighted average giving more emphasis to recent samples
var totalWeight = 0.0
var weightedSum = 0.0
let samples = speedSamples.suffix(min(8, speedSamples.count))
for (index, speed) in samples.enumerated() {
let weight = Double(index + 1)
weightedSum += speed * weight
totalWeight += weight
}
return totalWeight > 0 ? weightedSum / totalWeight : 0
}
func getDownloadStats() -> DownloadStats {
let downloaded = snapshot().downloadedBytes
let avgSpeed = totalElapsedTime > 0 ? Double(transferredBytes) / totalElapsedTime : 0
return DownloadStats(
totalBytes: totalBytes,
downloadedBytes: downloaded,
elapsedTime: totalElapsedTime,
averageSpeed: avgSpeed,
peakSpeed: peakSpeed
)
}
private func logSpeedProgress(
current: Double,
currentSpeed: Double,
averageSpeed: Double,
smoothedSpeed: Double,
overallSpeed: Double,
peakSpeed: Double,
context: String
) {
let progressPercent = Int(current * 100)
let currentSpeedStr = formatByteSpeed(currentSpeed)
let avgSpeedStr = formatByteSpeed(averageSpeed)
let peakSpeedStr = formatByteSpeed(peakSpeed)
// Calculate ETA based on the smoothed speed which is more stable
// This provides a more realistic estimate that doesn't fluctuate as much
let remainingBytes = totalBytes - snapshot().downloadedBytes
let speedForEta = max(smoothedSpeed, averageSpeed * 0.8) // Use the higher of smoothed or 80% of avg
let etaSeconds = speedForEta > 0 ? Double(remainingBytes) / speedForEta : 0
let etaStr = formatTimeRemaining(etaSeconds)
let progressBar = createProgressBar(progress: current)
print(
"\r\(progressBar) \(progressPercent)% | Current: \(currentSpeedStr) | Avg: \(avgSpeedStr) | Peak: \(peakSpeedStr) | ETA: \(etaStr) ",
terminator: "")
fflush(stdout)
}
private func createProgressBar(progress: Double, width: Int = 30) -> String {
let completedWidth = Int(progress * Double(width))
let remainingWidth = width - completedWidth
let completed = String(repeating: "█", count: completedWidth)
let remaining = String(repeating: "░", count: remainingWidth)
return "[\(completed)\(remaining)]"
}
private func formatByteSpeed(_ bytesPerSecond: Double) -> String {
let units = ["B/s", "KB/s", "MB/s", "GB/s"]
var speed = bytesPerSecond
var unitIndex = 0
while speed > 1024 && unitIndex < units.count - 1 {
speed /= 1024
unitIndex += 1
}
return String(format: "%.1f %@", speed, units[unitIndex])
}
private func formatTimeRemaining(_ seconds: Double) -> String {
if seconds.isNaN || seconds.isInfinite || seconds <= 0 {
return "calculating..."
}
let hours = Int(seconds) / 3600
let minutes = (Int(seconds) % 3600) / 60
let secs = Int(seconds) % 60
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, minutes, secs)
} else {
return String(format: "%d:%02d", minutes, secs)
}
}
}
struct DownloadStats {
let totalBytes: Int64
let downloadedBytes: Int64
let elapsedTime: TimeInterval
let averageSpeed: Double
let peakSpeed: Double
func formattedSummary() -> String {
let bytesStr = ByteCountFormatter.string(fromByteCount: downloadedBytes, countStyle: .file)
let avgSpeedStr = formatSpeed(averageSpeed)
let peakSpeedStr = formatSpeed(peakSpeed)
let timeStr = formatTime(elapsedTime)
return """
Download Statistics:
- Total downloaded: \(bytesStr)
- Elapsed time: \(timeStr)
- Average speed: \(avgSpeedStr)
- Peak speed: \(peakSpeedStr)
"""
}
private func formatSpeed(_ bytesPerSecond: Double) -> String {
let formatter = ByteCountFormatter()
formatter.countStyle = .file
let bytesStr = formatter.string(fromByteCount: Int64(bytesPerSecond))
return "\(bytesStr)/s"
}
private func formatTime(_ seconds: TimeInterval) -> String {
let hours = Int(seconds) / 3600
let minutes = (Int(seconds) % 3600) / 60
let secs = Int(seconds) % 60
if hours > 0 {
return String(format: "%d hours, %d minutes, %d seconds", hours, minutes, secs)
} else if minutes > 0 {
return String(format: "%d minutes, %d seconds", minutes, secs)
} else {
return String(format: "%d seconds", secs)
}
}
}
// Renamed struct
struct UploadStats {
let totalBytes: Int64
let uploadedBytes: Int64 // Renamed
let elapsedTime: TimeInterval
let averageSpeed: Double
let peakSpeed: Double
func formattedSummary() -> String {
let bytesStr = ByteCountFormatter.string(fromByteCount: uploadedBytes, countStyle: .file)
let avgSpeedStr = formatSpeed(averageSpeed)
let peakSpeedStr = formatSpeed(peakSpeed)
let timeStr = formatTime(elapsedTime)
return """
Upload Statistics:
- Total uploaded: \(bytesStr)
- Elapsed time: \(timeStr)
- Average speed: \(avgSpeedStr)
- Peak speed: \(peakSpeedStr)
"""
}
private func formatSpeed(_ bytesPerSecond: Double) -> String {
let formatter = ByteCountFormatter()
formatter.countStyle = .file
let bytesStr = formatter.string(fromByteCount: Int64(bytesPerSecond))
return "\(bytesStr)/s"
}
private func formatTime(_ seconds: TimeInterval) -> String {
let hours = Int(seconds) / 3600
let minutes = (Int(seconds) % 3600) / 60
let secs = Int(seconds) % 60
if hours > 0 {
return String(format: "%d hours, %d minutes, %d seconds", hours, minutes, secs)
} else if minutes > 0 {
return String(format: "%d minutes, %d seconds", minutes, secs)
} else {
return String(format: "%d seconds", secs)
}
}
}
actor TaskCounter {
private var count: Int = 0
func increment() { count += 1 }
func decrement() { count -= 1 }
func current() -> Int { count }
}
class ImageContainerRegistry: ImageRegistry, @unchecked Sendable {
private let registry: String
private let organization: String
private let username: String?
private let password: String?
private let downloadProgress = ProgressTracker() // Renamed for clarity
private let uploadProgress = UploadProgressTracker() // Added upload tracker
private let cacheDirectory: URL
private let downloadLock = NSLock()
private var activeDownloads: [String] = []
private let cachingEnabled: Bool
/// Extra URLProtocol classes for layer downloads (tests serve blobs locally).
var urlProtocolClasses: [AnyClass]? = nil
/// Base delay in seconds between layer download retries.
var retryBaseDelay: Double = 2
/// Part of the hidden name a layer has while it is being copied into the cache.
static let cacheStagingMarker = ".partial-"
// Constants for zero-skipping write logic
private static let holeGranularityBytes = 4 * 1024 * 1024 // 4MB block size for checking zeros
private static let zeroChunk = Data(count: holeGranularityBytes)
// Add the createProgressBar function here as a private method
private func createProgressBar(progress: Double, width: Int = 30) -> String {
let completedWidth = Int(progress * Double(width))
let remainingWidth = width - completedWidth
let completed = String(repeating: "█", count: completedWidth)
let remaining = String(repeating: "░", count: remainingWidth)
return "[\(completed)\(remaining)]"
}
init(registry: String, organization: String, username: String? = nil, password: String? = nil) {
self.registry = registry
self.organization = organization
self.username = username
self.password = password
// Get cache directory from settings
let cacheDir = SettingsManager.shared.getCacheDirectory()
let expandedCacheDir = (cacheDir as NSString).expandingTildeInPath
self.cacheDirectory = URL(fileURLWithPath: expandedCacheDir)
.appendingPathComponent("ghcr")
// Get caching enabled setting
self.cachingEnabled = SettingsManager.shared.isCachingEnabled()
try? FileManager.default.createDirectory(
at: cacheDirectory, withIntermediateDirectories: true)
// Create organization directory
let orgDir = cacheDirectory.appendingPathComponent(organization)
try? FileManager.default.createDirectory(at: orgDir, withIntermediateDirectories: true)
}
/// Creates a registry client with an explicit cache (tests).
init(
registry: String, organization: String, cacheDirectory: URL, cachingEnabled: Bool
) {
self.registry = registry
self.organization = organization
self.username = nil
self.password = nil
self.cacheDirectory = cacheDirectory
self.cachingEnabled = cachingEnabled
}
private func getManifestIdentifier(_ manifest: Manifest, manifestDigest: String) -> String {
// Use the manifest's own digest as the identifier
return manifestDigest.replacingOccurrences(of: ":", with: "_")
}
private func getShortImageId(_ digest: String) -> String {
// Take first 12 characters of the digest after removing the "sha256:" prefix
let id = digest.replacingOccurrences(of: "sha256:", with: "")
return String(id.prefix(12))
}
private func getImageCacheDirectory(manifestId: String) -> URL {
return
cacheDirectory
.appendingPathComponent(organization)
.appendingPathComponent(manifestId)
}
private func getCachedManifestPath(manifestId: String) -> URL {
return getImageCacheDirectory(manifestId: manifestId).appendingPathComponent(
"manifest.json")
}
func getCachedLayerPath(manifestId: String, digest: String) -> URL {
return getImageCacheDirectory(manifestId: manifestId).appendingPathComponent(
digest.replacingOccurrences(of: ":", with: "_"))
}
private func setupImageCache(manifestId: String, manifest: Manifest) throws {
let cacheDir = getImageCacheDirectory(manifestId: manifestId)
// An earlier pull of this manifest that was cancelled or failed left its
// verified layers here: keep them so this pull resumes from them.
if FileManager.default.fileExists(atPath: cacheDir.path),
let cachedManifest = loadCachedManifest(manifestId: manifestId),
cachedManifest.layers == manifest.layers
{
pruneUnusableCacheFiles(in: cacheDir, manifest: manifest)
return
}
// Remove existing cache if it exists
if FileManager.default.fileExists(atPath: cacheDir.path) {
try FileManager.default.removeItem(at: cacheDir)
// Ensure it's completely removed
while FileManager.default.fileExists(atPath: cacheDir.path) {
try? FileManager.default.removeItem(at: cacheDir)
}
}
try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)
}
/// Removes copies that never finished (staging files) and layer files whose
/// size does not match the manifest, so only complete layers are reused.
private func pruneUnusableCacheFiles(in cacheDir: URL, manifest: Manifest) {
let fm = FileManager.default
let sizes = Dictionary(
manifest.layers.map { ($0.digest.replacingOccurrences(of: ":", with: "_"), $0.size) },
uniquingKeysWith: { first, _ in first })
guard let names = try? fm.contentsOfDirectory(atPath: cacheDir.path) else { return }
for name in names {
let path = cacheDir.appendingPathComponent(name)
if name.contains(Self.cacheStagingMarker) {
try? fm.removeItem(at: path)
} else if let expected = sizes[name],
let actual = (try? fm.attributesOfItem(atPath: path.path)[.size] as? NSNumber)?
.intValue,
actual != expected
{
try? fm.removeItem(at: path)
}
}
}
private func loadCachedManifest(manifestId: String) -> Manifest? {
let manifestPath = getCachedManifestPath(manifestId: manifestId)
guard let data = try? Data(contentsOf: manifestPath) else { return nil }
return try? JSONDecoder().decode(Manifest.self, from: data)
}
private func validateCache(manifest: Manifest, manifestId: String) -> Bool {
// Skip cache validation if caching is disabled
if !cachingEnabled {
return false
}
// Check if we have a reassembled image
let reassembledCachePath = getImageCacheDirectory(manifestId: manifestId)
.appendingPathComponent("disk.img.reassembled")
if FileManager.default.fileExists(atPath: reassembledCachePath.path) {
Logger.debug("Found reassembled disk image in cache validation")
// If we have a reassembled image, we only need to make sure the manifest matches
guard let cachedManifest = loadCachedManifest(manifestId: manifestId),
cachedManifest.layers == manifest.layers
else {
return false
}
// We have a reassembled image and the manifest matches
return true
}
// If no reassembled image, check layer files
// First check if manifest exists and matches
guard let cachedManifest = loadCachedManifest(manifestId: manifestId),
cachedManifest.layers == manifest.layers
else {
return false
}
// Then verify all layer files exist
for layer in manifest.layers {
let cachedLayer = getCachedLayerPath(manifestId: manifestId, digest: layer.digest)
if !FileManager.default.fileExists(atPath: cachedLayer.path) {
return false
}
}
return true
}
private func saveManifest(_ manifest: Manifest, manifestId: String) throws {
// Skip saving manifest if caching is disabled
if !cachingEnabled {
return
}
let manifestPath = getCachedManifestPath(manifestId: manifestId)
try JSONEncoder().encode(manifest).write(to: manifestPath)
}
func isDownloading(_ digest: String) -> Bool {
downloadLock.lock()
defer { downloadLock.unlock() }
return activeDownloads.contains(digest)
}
func markDownloadStarted(_ digest: String) {
downloadLock.lock()
if !activeDownloads.contains(digest) {
activeDownloads.append(digest)
}
downloadLock.unlock()
}
private func markDownloadComplete(_ digest: String) {
downloadLock.lock()
activeDownloads.removeAll { $0 == digest }
downloadLock.unlock()
}
private func waitForExistingDownload(_ digest: String, cachedLayer: URL) async throws {
while isDownloading(digest) {
try await Task.sleep(nanoseconds: 1_000_000_000) // Sleep for 1 second
if FileManager.default.fileExists(atPath: cachedLayer.path) {
return // File is now available
}
}
}
private func saveImageMetadata(image: String, manifestId: String) throws {
// Skip saving metadata if caching is disabled
if !cachingEnabled {
return
}
let metadataPath = getImageCacheDirectory(manifestId: manifestId).appendingPathComponent(
"metadata.json")
let metadata = ImageMetadata(
image: image,
manifestId: manifestId,
timestamp: Date()
)
try JSONEncoder().encode(metadata).write(to: metadataPath)
}
private func cleanupOldVersions(currentManifestId: String, image: String) throws {
// Skip cleanup if caching is disabled
if !cachingEnabled {
return
}
Logger.info(
"Checking for old versions of image to clean up",
metadata: [
"image": image,
"current_manifest_id": currentManifestId,
])
let orgDir = cacheDirectory.appendingPathComponent(organization)
guard FileManager.default.fileExists(atPath: orgDir.path) else { return }
let contents = try FileManager.default.contentsOfDirectory(atPath: orgDir.path)
for item in contents {
if item == currentManifestId { continue }
let itemPath = orgDir.appendingPathComponent(item)
let metadataPath = itemPath.appendingPathComponent("metadata.json")
if let metadataData = try? Data(contentsOf: metadataPath),
let metadata = try? JSONDecoder().decode(ImageMetadata.self, from: metadataData)
{
if metadata.image == image {
// Before removing, check if there's a reassembled image we should preserve
let reassembledPath = itemPath.appendingPathComponent("disk.img.reassembled")
let nvramPath = itemPath.appendingPathComponent("nvram.bin")
let configPath = itemPath.appendingPathComponent("config.json")
// Preserve reassembled image if it exists
if FileManager.default.fileExists(atPath: reassembledPath.path) {
Logger.info(
"Preserving reassembled disk image during cleanup",
metadata: ["manifest_id": item])
// Ensure the current cache directory exists
let currentCacheDir = getImageCacheDirectory(manifestId: currentManifestId)
try FileManager.default.createDirectory(
at: currentCacheDir, withIntermediateDirectories: true)
// Move reassembled image to current cache directory
let currentReassembledPath = currentCacheDir.appendingPathComponent(
"disk.img.reassembled")
if !FileManager.default.fileExists(atPath: currentReassembledPath.path) {
try FileManager.default.copyItem(
at: reassembledPath, to: currentReassembledPath)
}
// Also preserve nvram if it exists
if FileManager.default.fileExists(atPath: nvramPath.path) {
let currentNvramPath = currentCacheDir.appendingPathComponent(
"nvram.bin")
if !FileManager.default.fileExists(atPath: currentNvramPath.path) {
try FileManager.default.copyItem(
at: nvramPath, to: currentNvramPath)
}
}
// Also preserve config if it exists
if FileManager.default.fileExists(atPath: configPath.path) {
let currentConfigPath = currentCacheDir.appendingPathComponent(
"config.json")
if !FileManager.default.fileExists(atPath: currentConfigPath.path) {
try FileManager.default.copyItem(
at: configPath, to: currentConfigPath)
}
}
}
// Now remove the old directory
try FileManager.default.removeItem(at: itemPath)
Logger.info(
"Removed old version of image",
metadata: [
"image": image,
"old_manifest_id": item,
])
}
continue
}
Logger.info(
"Skipping cleanup check for item without metadata", metadata: ["item": item])
}
}
private func optimizeNetworkSettings() {
// Set global URLSession configuration properties for better performance
URLSessionConfiguration.default.httpMaximumConnectionsPerHost = 10
URLSessionConfiguration.default.httpShouldUsePipelining = true
URLSessionConfiguration.default.timeoutIntervalForResource = 3600
// Pre-warm DNS resolution
let preWarmTask = URLSession.shared.dataTask(with: URL(string: "https://\(self.registry)")!)
preWarmTask.resume()
}
public func pull(
image: String,
name: String?,
locationName: String? = nil,
force: Bool = false,
progressHandler: PullProgressHandler? = nil
) async throws -> VMDirectory {
guard !image.isEmpty else {
throw ValidationError("Image name cannot be empty")
}
if let handler = progressHandler {
await downloadProgress.setProgressHandler(handler)
}
let home = Home()
// Use provided name or derive from image
let vmName = name ?? image.split(separator: ":").first.map(String.init) ?? ""
// Determine if locationName is a direct path or a named storage location
let vmDir: VMDirectory
if let locationName = locationName,
locationName.contains("/") || locationName.contains("\\")
{
// Direct path
vmDir = try home.getVMDirectoryFromPath(vmName, storagePath: locationName)
} else {
// Named storage or default location
vmDir = try home.getVMDirectory(vmName, storage: locationName)
}
// Check if image is already cached with all required files
let manifestDigestPath = vmDir.dir.url.appendingPathComponent(".manifest-digest")
if !force
&& vmDir.exists()
&& vmDir.diskPath.exists()
&& vmDir.nvramPath.exists()
&& vmDir.configPath.exists()
&& FileManager.default.fileExists(atPath: manifestDigestPath.path)
{
Logger.info("Image already cached, skipping download")
return vmDir
}
// If force is set and directory exists, remove it before re-downloading
if force && vmDir.exists() {
Logger.info("Force flag set, removing existing VM directory")
try FileManager.default.removeItem(at: vmDir.dir.url)
}
// Optimize network early in the process
optimizeNetworkSettings()
// Parse image name and tag
let components = image.split(separator: ":")
guard components.count == 2, let tag = components.last else {
throw ValidationError("Invalid image format. Expected format: name:tag")
}
let imageName = String(components.first!)
let imageTag = String(tag)
Logger.debug(
"Pulling image",
metadata: [
"image": image,
"name": vmName,
"location": locationName ?? "home",
"registry": registry,
"organization": organization,
])
// Get anonymous token
Logger.debug("Getting registry authentication token")
let token = try await getToken(
repository: "\(self.organization)/\(imageName)", scopes: ["pull"])
// Fetch manifest
Logger.debug("Fetching Image manifest")
let (manifest, manifestDigest): (Manifest, String) = try await fetchManifest(
repository: "\(self.organization)/\(imageName)",
tag: imageTag,
token: token
)
// Get manifest identifier using the manifest's own digest
let manifestId = getManifestIdentifier(manifest, manifestDigest: manifestDigest)
Logger.debug(
"Pulling image",
metadata: [
"repository": imageName,
"manifest_id": manifestId,
])
// Create temporary directory for the entire VM setup
let tempVMDir = FileManager.default.temporaryDirectory.appendingPathComponent(
"lume_vm_\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempVMDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempVMDir)
}
// Auto-detect image format from manifest layer media types
let imageFormat = OCIMediaType.detect(manifest)
Logger.debug("Detected image format: \(imageFormat == .oci ? "OCI-compliant" : "legacy Lume")")
// OCI-compliant images bypass the legacy cache/assembly path
if imageFormat == .oci {
Logger.debug("Pulling OCI-compliant image")
try await pullOCI(
manifest: manifest,
manifestId: manifestId,
imageName: imageName,
repository: "\(self.organization)/\(imageName)",
token: token,
to: tempVMDir
)
}
// Check if caching is enabled and if we have a valid cached version
Logger.debug("Caching enabled: \(cachingEnabled)")
if imageFormat == .oci {
// OCI pull already populated tempVMDir; skip legacy cache logic
} else if cachingEnabled && validateCache(manifest: manifest, manifestId: manifestId) {
Logger.debug("Using cached version of image")
try await copyFromCache(manifest: manifest, manifestId: manifestId, to: tempVMDir)
} else {
// If caching is disabled, log it
if !cachingEnabled {
Logger.info("Caching is disabled, downloading fresh copy")
} else {
Logger.info("Cache miss or invalid cache, setting up new cache")
}
try OCIMediaType.validateRawDiskParts(manifest)
// Clean up old versions of this repository before setting up new cache if caching is enabled
if cachingEnabled {
try cleanupOldVersions(currentManifestId: manifestId, image: imageName)
// Setup new cache directory
try setupImageCache(manifestId: manifestId, manifest: manifest)
// Save new manifest
try saveManifest(manifest, manifestId: manifestId)
// Save image metadata
try saveImageMetadata(
image: imageName,
manifestId: manifestId
)
}
// Create temporary directory for new downloads
let tempDownloadDir = FileManager.default.temporaryDirectory.appendingPathComponent(
UUID().uuidString)
try FileManager.default.createDirectory(
at: tempDownloadDir, withIntermediateDirectories: true)
defer {
try? FileManager.default.removeItem(at: tempDownloadDir)
}
// Set total size and file count
let totalFiles = manifest.layers.filter {
$0.mediaType != "application/vnd.oci.empty.v1+json"
}.count
let totalSize = manifest.layers.reduce(0) { $0 + Int64($1.size) }
await downloadProgress.setTotal(totalSize, files: totalFiles)
// Process layers with limited concurrency
Logger.info("Processing Image layers")
Logger.info(
"This may take several minutes depending on the image size and your internet connection. Please wait..."
)
// Add immediate progress indicator before starting downloads
print(
"[░░░░░░░░░░░░░░░░░░░░] 0% | Initializing downloads... | ETA: calculating... ")
fflush(stdout)
// Instantiate the collector
let diskPartsCollector = DiskPartsCollector()
// Adaptive concurrency based on system capabilities
let memoryConstrained = determineIfMemoryConstrained()
let networkQuality = determineNetworkQuality()
let maxConcurrentTasks = calculateOptimalConcurrency(
memoryConstrained: memoryConstrained, networkQuality: networkQuality)
Logger.info(
"Using adaptive download configuration: Concurrency=\(maxConcurrentTasks), Memory-optimized=\(memoryConstrained)"
)
let counter = TaskCounter()
var lz4LayerCount = 0 // Count lz4 layers found
try await withThrowingTaskGroup(of: Int64.self) { group in
for layer in manifest.layers {
if layer.mediaType == "application/vnd.oci.empty.v1+json" {
continue
}
while await counter.current() >= maxConcurrentTasks {
_ = try await group.next()
await counter.decrement()
}
// Identify disk parts by media type
if layer.mediaType == "application/octet-stream+lz4"
|| OCIMediaType.rawDiskPart(layer) != nil
{
// --- Handle LZ4 Disk Part Layer ---
lz4LayerCount += 1 // Increment count
let currentPartNum = lz4LayerCount // Use the current count as the logical number for logging
let cachedLayer = getCachedLayerPath(
manifestId: manifestId, digest: layer.digest)
let digest = layer.digest
let size = layer.size
if memoryConstrained
&& FileManager.default.fileExists(atPath: cachedLayer.path)
{
// Add to collector, get sequential number assigned by collector
let collectorPartNum = await diskPartsCollector.addPart(
url: cachedLayer)
// Log using the sequential number from collector for clarity if needed, or the lz4LayerCount
Logger.info(
"Using cached lz4 layer (part \(currentPartNum)) directly: \(cachedLayer.lastPathComponent) -> Collector #\(collectorPartNum)"
)
await downloadProgress.addProgress(Int64(size))
continue
} else {
// Download/Copy Path (Task Group)
group.addTask { [self] in
await counter.increment()
let finalPath: URL
if FileManager.default.fileExists(atPath: cachedLayer.path) {
let tempPartURL = tempDownloadDir.appendingPathComponent(
"disk.img.part.\(UUID().uuidString)")
try FileManager.default.copyItem(
at: cachedLayer, to: tempPartURL)
await downloadProgress.addProgress(Int64(size))
finalPath = tempPartURL
} else {
let tempPartURL = tempDownloadDir.appendingPathComponent(
"disk.img.part.\(UUID().uuidString)")
if isDownloading(digest) {
try await waitForExistingDownload(
digest, cachedLayer: cachedLayer)
if FileManager.default.fileExists(atPath: cachedLayer.path)
{
try FileManager.default.copyItem(
at: cachedLayer, to: tempPartURL)
await downloadProgress.addProgress(Int64(size))
finalPath = tempPartURL
} else {
markDownloadStarted(digest)
try await self.downloadLayer(
repository: "\(self.organization)/\(imageName)",
digest: digest, mediaType: layer.mediaType,
token: token,
to: tempPartURL, maxRetries: 5,
progress: downloadProgress, manifestId: manifestId
)
finalPath = tempPartURL
}
} else {
markDownloadStarted(digest)
try await self.downloadLayer(
repository: "\(self.organization)/\(imageName)",
digest: digest, mediaType: layer.mediaType,
token: token,
to: tempPartURL, maxRetries: 5,
progress: downloadProgress, manifestId: manifestId
)
finalPath = tempPartURL
}
}
// Add to collector, get sequential number assigned by collector
let collectorPartNum = await diskPartsCollector.addPart(
url: finalPath)
// Log using the sequential number from collector
Logger.info(
"Assigned path for lz4 layer (part \(currentPartNum)): \(finalPath.lastPathComponent) -> Collector #\(collectorPartNum)"
)
await counter.decrement()
return Int64(size)
}
}
} else {
// --- Handle Non-Disk-Part Layer ---
let mediaType = layer.mediaType
let digest = layer.digest
let size = layer.size
// Determine output path based on media type
let outputURL: URL
switch mediaType {
case "application/vnd.oci.image.layer.v1.tar",
"application/octet-stream+gzip": // Might be compressed disk.img single file?
outputURL = tempDownloadDir.appendingPathComponent("disk.img")
case "application/vnd.oci.image.config.v1+json":
outputURL = tempDownloadDir.appendingPathComponent("config.json")
case "application/octet-stream": // Could be nvram or uncompressed single disk.img
// Heuristic: If a config.json already exists or is expected, assume this is nvram.
// This might need refinement if single disk images use octet-stream.
if manifest.config != nil {
outputURL = tempDownloadDir.appendingPathComponent("nvram.bin")
} else {
// Assume it's a single-file disk image if no config layer is present
outputURL = tempDownloadDir.appendingPathComponent("disk.img")
}
default:
Logger.info("Skipping unsupported layer media type: \(mediaType)")
continue // Skip to the next layer
}
// Add task to download/copy the non-disk-part layer
group.addTask { [self] in
await counter.increment()
let cachedLayer = getCachedLayerPath(
manifestId: manifestId, digest: digest)
if FileManager.default.fileExists(atPath: cachedLayer.path) {
try FileManager.default.copyItem(at: cachedLayer, to: outputURL)
await downloadProgress.addProgress(Int64(size))
} else {
if isDownloading(digest) {
try await waitForExistingDownload(
digest, cachedLayer: cachedLayer)
if FileManager.default.fileExists(atPath: cachedLayer.path) {
try FileManager.default.copyItem(
at: cachedLayer, to: outputURL)
await downloadProgress.addProgress(Int64(size))
await counter.decrement() // Decrement before returning
return Int64(size)
}
}
markDownloadStarted(digest)
try await self.downloadLayer(
repository: "\(self.organization)/\(imageName)",
digest: digest, mediaType: mediaType, token: token,
to: outputURL, maxRetries: 5,
progress: downloadProgress, manifestId: manifestId
)
// Note: downloadLayer handles caching and marking download complete
}
await counter.decrement()
return Int64(size)
}
}
} // End for layer in manifest.layers
// Wait for remaining tasks
for try await _ in group {}
} // End TaskGroup
// Display download statistics
let stats = await downloadProgress.getDownloadStats()
Logger.info("") // New line after progress
Logger.info(stats.formattedSummary())
// Now that we've downloaded everything to the cache, use copyFromCache to create final VM files
if cachingEnabled {
Logger.info("Using copyFromCache method to properly preserve partition tables")
try await copyFromCache(manifest: manifest, manifestId: manifestId, to: tempVMDir)
} else {
// Even if caching is disabled, we need to use copyFromCache to assemble the disk image
// correctly with partition tables, then we'll clean up the cache afterward
Logger.info("Caching disabled - using temporary cache to assemble VM files")
try await copyFromCache(manifest: manifest, manifestId: manifestId, to: tempVMDir)
}
}
// Only move to final location once everything is complete
if FileManager.default.fileExists(atPath: vmDir.dir.path) {
try FileManager.default.removeItem(at: URL(fileURLWithPath: vmDir.dir.path))
}
// Ensure parent directory exists
try FileManager.default.createDirectory(
at: URL(fileURLWithPath: vmDir.dir.path).deletingLastPathComponent(),
withIntermediateDirectories: true)
// Log the final destination
Logger.debug(
"Moving files to VM directory",
metadata: [
"destination": vmDir.dir.path,
"location": locationName ?? "home",
])
// Move files to final location
try FileManager.default.moveItem(at: tempVMDir, to: URL(fileURLWithPath: vmDir.dir.path))
// If caching is disabled, clean up the cache entry
if !cachingEnabled {
Logger.debug("Caching disabled - cleaning up temporary cache entry")
try? cleanupCacheEntry(manifestId: manifestId)
}
// Write manifest digest to mark this as a complete cached image
let digestFilePath = URL(fileURLWithPath: vmDir.dir.path).appendingPathComponent(".manifest-digest")
try manifestDigest.write(to: digestFilePath, atomically: true, encoding: .utf8)
Logger.debug("Download complete: Files extracted to \(vmDir.dir.path)")
Logger.debug(
"Note: Actual disk usage is significantly lower than reported size due to macOS sparse file system"
)
Logger.debug(
"Run 'lume run \(vmName)' to reduce the disk image file size by using macOS sparse file system"
)
return vmDir
}
// Helper function to clean up a specific cache entry
private func cleanupCacheEntry(manifestId: String) throws {
let cacheDir = getImageCacheDirectory(manifestId: manifestId)
if FileManager.default.fileExists(atPath: cacheDir.path) {
Logger.info("Removing cache entry for manifest ID: \(manifestId)")
try FileManager.default.removeItem(at: cacheDir)
}
}
// Shared function to handle disk image creation - can be used by both cache hit and cache miss paths
private func createDiskImageFromSource(
sourceURL: URL, // Source data to decompress
destinationURL: URL, // Where to create the disk image
diskSize: UInt64 // Total size for the sparse file
) throws {
Logger.info("Creating sparse disk image...")
// Create empty destination file
if FileManager.default.fileExists(atPath: destinationURL.path) {
try FileManager.default.removeItem(at: destinationURL)
}
guard FileManager.default.createFile(atPath: destinationURL.path, contents: nil) else {
throw PullError.fileCreationFailed(destinationURL.path)
}
// Create sparse file
let outputHandle = try FileHandle(forWritingTo: destinationURL)
try outputHandle.truncate(atOffset: diskSize)
// Write test patterns at beginning and end
Logger.info("Writing test patterns to verify writability...")
let testPattern = "LUME_TEST_PATTERN".data(using: .utf8)!
try outputHandle.seek(toOffset: 0)
try outputHandle.write(contentsOf: testPattern)
try outputHandle.seek(toOffset: diskSize - UInt64(testPattern.count))
try outputHandle.write(contentsOf: testPattern)
try outputHandle.synchronize()
// Decompress the source data at offset 0
Logger.info("Decompressing source data...")
let bytesWritten = try decompressChunkAndWriteSparse(
inputPath: sourceURL.path,
outputHandle: outputHandle,
startOffset: 0
)
Logger.info(
"Decompressed \(ByteCountFormatter.string(fromByteCount: Int64(bytesWritten), countStyle: .file)) of data"
)
// Ensure data is written and close handle
try outputHandle.synchronize()
try outputHandle.close()
// Run sync to flush filesystem
let syncProcess = Process()
syncProcess.executableURL = URL(fileURLWithPath: "/bin/sync")
try syncProcess.run()
syncProcess.waitUntilExit()
// Optimize with cp -c
if FileManager.default.fileExists(atPath: "/bin/cp") {
Logger.info("Optimizing sparse file representation...")
let optimizedPath = destinationURL.path + ".optimized"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
process.arguments = ["-c", destinationURL.path, optimizedPath]
try process.run()
process.waitUntilExit()
if process.terminationStatus == 0 {
// Get optimization results
let optimizedSize =
(try? FileManager.default.attributesOfItem(atPath: optimizedPath)[.size]
as? UInt64) ?? 0
let originalUsage = getActualDiskUsage(path: destinationURL.path)
let optimizedUsage = getActualDiskUsage(path: optimizedPath)
Logger.info(
"Sparse optimization results: Before: \(ByteCountFormatter.string(fromByteCount: Int64(originalUsage), countStyle: .file)) actual usage, After: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedUsage), countStyle: .file)) actual usage (Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedSize), countStyle: .file)))"
)
// Replace original with optimized
try FileManager.default.removeItem(at: destinationURL)
try FileManager.default.moveItem(
at: URL(fileURLWithPath: optimizedPath), to: destinationURL)
Logger.info("Replaced with optimized sparse version")
} else {
Logger.info("Sparse optimization failed, using original file")
try? FileManager.default.removeItem(atPath: optimizedPath)
}
}
// Set permissions to 0644
let chmodProcess = Process()
chmodProcess.executableURL = URL(fileURLWithPath: "/bin/chmod")
chmodProcess.arguments = ["0644", destinationURL.path]
try chmodProcess.run()
chmodProcess.waitUntilExit()
// Final sync
let finalSyncProcess = Process()
finalSyncProcess.executableURL = URL(fileURLWithPath: "/bin/sync")
try finalSyncProcess.run()
finalSyncProcess.waitUntilExit()
}
// Function to simulate cache pull behavior for freshly downloaded images
private func simulateCachePull(tempVMDir: URL) throws {
Logger.info("Simulating cache pull behavior for freshly downloaded image...")
// Find disk.img in tempVMDir
let diskImgPath = tempVMDir.appendingPathComponent("disk.img")
guard FileManager.default.fileExists(atPath: diskImgPath.path) else {
Logger.info("No disk.img found to simulate cache pull behavior")
return
}
// Get file attributes and size
let attributes = try FileManager.default.attributesOfItem(atPath: diskImgPath.path)
guard let diskSize = attributes[.size] as? UInt64, diskSize > 0 else {
Logger.error("Could not determine disk.img size for simulation")
return
}
Logger.info("Creating true disk image clone with partition table preserved...")
// Create backup of original file
let backupPath = tempVMDir.appendingPathComponent("disk.img.original")
try FileManager.default.moveItem(at: diskImgPath, to: backupPath)
// Let's first check if the original image has a partition table
Logger.info("Checking if source image has a partition table...")
let checkProcess = Process()
checkProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
checkProcess.arguments = ["imageinfo", backupPath.path]
let checkPipe = Pipe()
checkProcess.standardOutput = checkPipe
try checkProcess.run()
checkProcess.waitUntilExit()
let checkData = checkPipe.fileHandleForReading.readDataToEndOfFile()
let checkOutput = String(data: checkData, encoding: .utf8) ?? ""
Logger.info("Source image info: \(checkOutput)")
// Try different methods in sequence until one works
var success = false
// Method 1: Use hdiutil convert to convert the image while preserving all data
if !success {
Logger.info("Trying hdiutil convert...")
let tempPath = tempVMDir.appendingPathComponent("disk.img.temp")
let convertProcess = Process()
convertProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
convertProcess.arguments = [
"convert",
backupPath.path,
"-format", "UDRO", // Read-only first to preserve partition table
"-o", tempPath.path,
]
let convertOutPipe = Pipe()
let convertErrPipe = Pipe()
convertProcess.standardOutput = convertOutPipe
convertProcess.standardError = convertErrPipe
do {
try convertProcess.run()
convertProcess.waitUntilExit()
let errData = convertErrPipe.fileHandleForReading.readDataToEndOfFile()
let errOutput = String(data: errData, encoding: .utf8) ?? ""
if convertProcess.terminationStatus == 0 {
Logger.info("hdiutil convert succeeded. Converting to writable format...")
// Now convert to writable format
let convertBackProcess = Process()
convertBackProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
convertBackProcess.arguments = [
"convert",
tempPath.path,
"-format", "UDRW", // Read-write format
"-o", diskImgPath.path,
]
try convertBackProcess.run()
convertBackProcess.waitUntilExit()
if convertBackProcess.terminationStatus == 0 {
Logger.info(
"Successfully converted to writable format with partition table")
success = true
} else {
Logger.error("hdiutil convert to writable format failed")
}
// Clean up temporary image
try? FileManager.default.removeItem(at: tempPath)
} else {
Logger.error("hdiutil convert failed: \(errOutput)")
}
} catch {
Logger.error("Error executing hdiutil convert: \(error)")
}
}
// Method 2: Try direct raw copy method
if !success {
Logger.info("Trying direct raw copy with dd...")
// Create empty file first
FileManager.default.createFile(atPath: diskImgPath.path, contents: nil)
let ddProcess = Process()
ddProcess.executableURL = URL(fileURLWithPath: "/bin/dd")
ddProcess.arguments = [
"if=\(backupPath.path)",
"of=\(diskImgPath.path)",
"bs=1m", // Large block size
"count=81920", // Ensure we copy everything (80GB+ should be sufficient)
]
let ddErrPipe = Pipe()
ddProcess.standardError = ddErrPipe
do {
try ddProcess.run()
ddProcess.waitUntilExit()
let errData = ddErrPipe.fileHandleForReading.readDataToEndOfFile()
let errOutput = String(data: errData, encoding: .utf8) ?? ""
if ddProcess.terminationStatus == 0 {
Logger.info("Raw dd copy completed: \(errOutput)")
success = true
} else {
Logger.error("Raw dd copy failed: \(errOutput)")
}
} catch {
Logger.error("Error executing dd: \(error)")
}
}
// Method 3: Use a more complex approach with disk mounting
if !success {
Logger.info("Trying advanced disk attach/detach approach...")
// Mount the source disk image
let attachProcess = Process()
attachProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
attachProcess.arguments = ["attach", backupPath.path, "-nomount"]
let attachPipe = Pipe()
attachProcess.standardOutput = attachPipe
try attachProcess.run()
attachProcess.waitUntilExit()
let attachData = attachPipe.fileHandleForReading.readDataToEndOfFile()
let attachOutput = String(data: attachData, encoding: .utf8) ?? ""
// Extract the disk device from output (/dev/diskN)
var diskDevice: String? = nil
if let diskMatch = attachOutput.range(
of: "/dev/disk[0-9]+", options: .regularExpression)
{
diskDevice = String(attachOutput[diskMatch])
}
if let device = diskDevice {
Logger.info("Source disk attached at \(device)")
// Create a bootable disk image clone
let createProcess = Process()
createProcess.executableURL = URL(fileURLWithPath: "/usr/sbin/asr")
createProcess.arguments = [
"restore",
"--source", device,
"--target", diskImgPath.path,
"--erase",
"--noprompt",
]
let createPipe = Pipe()
createProcess.standardOutput = createPipe
do {
try createProcess.run()
createProcess.waitUntilExit()
let createOutput =
String(
data: createPipe.fileHandleForReading.readDataToEndOfFile(),
encoding: .utf8) ?? ""
Logger.info("asr output: \(createOutput)")
if createProcess.terminationStatus == 0 {
Logger.info("Successfully created bootable disk image clone!")
success = true
} else {
Logger.error("Failed to create bootable disk image clone")
}
} catch {
Logger.error("Error executing asr: \(error)")
}
// Always detach the disk when done
let detachProcess = Process()
detachProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
detachProcess.arguments = ["detach", device]
try? detachProcess.run()
detachProcess.waitUntilExit()
} else {
Logger.error("Failed to extract disk device from hdiutil attach output")
}
}
// Fallback: If none of the methods worked, revert to our previous method just to ensure we have a usable image
if !success {
Logger.info("All specialized methods failed. Reverting to basic copy...")
// If the disk image file exists (from a failed attempt), remove it
if FileManager.default.fileExists(atPath: diskImgPath.path) {
try FileManager.default.removeItem(at: diskImgPath)
}
// Attempt a basic file copy which will at least give us something to work with
try FileManager.default.copyItem(at: backupPath, to: diskImgPath)
}
// Optimize sparseness if possible
if FileManager.default.fileExists(atPath: "/bin/cp") {
Logger.info("Optimizing sparse file representation...")
let optimizedPath = diskImgPath.path + ".optimized"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
process.arguments = ["-c", diskImgPath.path, optimizedPath]
try process.run()
process.waitUntilExit()
if process.terminationStatus == 0 {
let optimizedSize =
(try? FileManager.default.attributesOfItem(atPath: optimizedPath)[.size]
as? UInt64) ?? 0
let originalUsage = getActualDiskUsage(path: diskImgPath.path)
let optimizedUsage = getActualDiskUsage(path: optimizedPath)
Logger.info(
"Sparse optimization results: Before: \(ByteCountFormatter.string(fromByteCount: Int64(originalUsage), countStyle: .file)) actual usage, After: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedUsage), countStyle: .file)) actual usage (Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedSize), countStyle: .file)))"
)
// Replace with optimized version
try FileManager.default.removeItem(at: diskImgPath)
try FileManager.default.moveItem(
at: URL(fileURLWithPath: optimizedPath), to: diskImgPath)
Logger.info("Replaced with optimized sparse version")
} else {
Logger.info("Sparse optimization failed, using original file")
try? FileManager.default.removeItem(atPath: optimizedPath)
}
}
// Set permissions to 0644
let chmodProcess = Process()
chmodProcess.executableURL = URL(fileURLWithPath: "/bin/chmod")
chmodProcess.arguments = ["0644", diskImgPath.path]
try chmodProcess.run()
chmodProcess.waitUntilExit()
// Final sync
let finalSyncProcess = Process()
finalSyncProcess.executableURL = URL(fileURLWithPath: "/bin/sync")
try finalSyncProcess.run()
finalSyncProcess.waitUntilExit()
// Verify the final disk image
Logger.info("Verifying final disk image partition information...")
let verifyProcess = Process()
verifyProcess.executableURL = URL(fileURLWithPath: "/usr/bin/hdiutil")
verifyProcess.arguments = ["imageinfo", diskImgPath.path]
let verifyOutputPipe = Pipe()
verifyProcess.standardOutput = verifyOutputPipe
try verifyProcess.run()
verifyProcess.waitUntilExit()
let verifyOutputData = verifyOutputPipe.fileHandleForReading.readDataToEndOfFile()
let verifyOutput = String(data: verifyOutputData, encoding: .utf8) ?? ""
Logger.info("Final disk image verification:\n\(verifyOutput)")
// Clean up backup file
try FileManager.default.removeItem(at: backupPath)
Logger.info(
"Cache pull simulation completed successfully with partition table preservation")
}
func copyFromCache(manifest: Manifest, manifestId: String, to destination: URL)
async throws
{
Logger.debug("Copying from cache...")
// Define output URL and expected size variable scope here
let outputURL = destination.appendingPathComponent("disk.img")
var expectedTotalSize: UInt64? = nil // Use optional to handle missing config
// Define the path for the reassembled cache image
let cacheDir = getImageCacheDirectory(manifestId: manifestId)
let reassembledCachePath = cacheDir.appendingPathComponent("disk.img.reassembled")
let nvramCachePath = cacheDir.appendingPathComponent("nvram.bin")
// First check if we already have a reassembled image in the cache
if FileManager.default.fileExists(atPath: reassembledCachePath.path) {
Logger.debug("Found reassembled disk image in cache, using it directly")
// Copy reassembled disk image
try FileManager.default.copyItem(at: reassembledCachePath, to: outputURL)
// Copy nvram if it exists
if FileManager.default.fileExists(atPath: nvramCachePath.path) {
try FileManager.default.copyItem(
at: nvramCachePath,
to: destination.appendingPathComponent("nvram.bin")
)
Logger.debug("Using cached nvram.bin file")
} else {
// Look for nvram in layer cache if needed
let nvramLayers = manifest.layers.filter {
$0.mediaType == "application/octet-stream"
}
if let nvramLayer = nvramLayers.first {
let cachedNvram = getCachedLayerPath(
manifestId: manifestId, digest: nvramLayer.digest)
if FileManager.default.fileExists(atPath: cachedNvram.path) {
try FileManager.default.copyItem(
at: cachedNvram,
to: destination.appendingPathComponent("nvram.bin")
)
// Also save it to the dedicated nvram location for future use
try FileManager.default.copyItem(at: cachedNvram, to: nvramCachePath)
Logger.debug("Recovered nvram.bin from layer cache")
}
}
}
// Copy config if it exists
let configCachePath = cacheDir.appendingPathComponent("config.json")
if FileManager.default.fileExists(atPath: configCachePath.path) {
try FileManager.default.copyItem(
at: configCachePath,
to: destination.appendingPathComponent("config.json")
)
Logger.debug("Using cached config.json file")
} else {
// Look for config in layer cache if needed
let configLayers = manifest.layers.filter {
$0.mediaType == "application/vnd.oci.image.config.v1+json"
}
if let configLayer = configLayers.first {
let cachedConfig = getCachedLayerPath(
manifestId: manifestId, digest: configLayer.digest)
if FileManager.default.fileExists(atPath: cachedConfig.path) {
try FileManager.default.copyItem(
at: cachedConfig,
to: destination.appendingPathComponent("config.json")
)
// Also save it to the dedicated config location for future use
try FileManager.default.copyItem(at: cachedConfig, to: configCachePath)
Logger.debug("Recovered config.json from layer cache")
}
}
}
Logger.debug("Cache copy complete using reassembled image")
return
}
// If we don't have a reassembled image, proceed with legacy part handling
Logger.debug("No reassembled image found, using part-based reassembly")
try OCIMediaType.validateRawDiskParts(manifest)
// Instantiate collector
let diskPartsCollector = DiskPartsCollector()
var lz4LayerCount = 0 // Count lz4 layers found
var hasNvram = false
var configPath: URL? = nil
// First identify disk parts and non-disk files
for layer in manifest.layers {
let cachedLayer = getCachedLayerPath(manifestId: manifestId, digest: layer.digest)
let rawPart = OCIMediaType.rawDiskPart(layer)
// Identify disk parts simply by media type
if layer.mediaType == "application/octet-stream+lz4" || rawPart != nil {
lz4LayerCount += 1 // Increment count
// When caching is disabled, the file might not exist with the cache path name
// Check if the file exists before trying to use it
if rawPart == nil && !FileManager.default.fileExists(atPath: cachedLayer.path) {
Logger.info("Layer file not found in cache: \(cachedLayer.path) - skipping")
continue
}
// Add to collector. It will assign the sequential part number.
let collectorPartNum = await diskPartsCollector.addPart(
url: cachedLayer, number: rawPart?.number)
Logger.info(
"Adding cached lz4 layer (part \(lz4LayerCount)) -> Collector #\(collectorPartNum): \(cachedLayer.lastPathComponent)"
)
} else {
// --- Handle Non-Disk-Part Layer (from cache) ---
let fileName: String
switch layer.mediaType {
case "application/vnd.oci.image.config.v1+json":
fileName = "config.json"
configPath = cachedLayer
case "application/octet-stream":
// Assume nvram if config layer exists, otherwise assume single disk image
fileName = manifest.config != nil ? "nvram.bin" : "disk.img"
if fileName == "nvram.bin" {
hasNvram = true
}
case "application/vnd.oci.image.layer.v1.tar",
"application/octet-stream+gzip":
// Assume disk image for these types as well if encountered in cache scenario
fileName = "disk.img"
default:
Logger.info("Skipping unsupported cached layer media type: \(layer.mediaType)")
continue
}
// When caching is disabled, the file might not exist with the cache path name
if !FileManager.default.fileExists(atPath: cachedLayer.path) {
Logger.info(
"Non-disk layer file not found in cache: \(cachedLayer.path) - skipping")
continue
}
// Copy the non-disk file directly from cache to destination
try FileManager.default.copyItem(
at: cachedLayer,
to: destination.appendingPathComponent(fileName)
)
}
}
// --- Safely retrieve parts AFTER loop ---
let diskPartSources = await diskPartsCollector.getSortedParts() // Sorted by assigned sequential number
let totalParts = await diskPartsCollector.getTotalParts() // Get total count from collector
let rawParts = manifest.layers.contains { OCIMediaType.rawDiskPart($0) != nil }
Logger.info("Found \(totalParts) lz4 disk parts in cache to reassemble.")
// --- End retrieving parts ---
// Reassemble disk parts if needed
// Use the count from the collector
if !diskPartSources.isEmpty {
// Use totalParts from collector directly
Logger.info(
"Reassembling \(totalParts) disk image parts using sparse file technique...")
// Get uncompressed size from cached config file (needs to be copied first)
let configURL = destination.appendingPathComponent("config.json")
// Parse config.json to get uncompressed size *before* reassembly
let uncompressedSize = getUncompressedSizeFromConfig(configPath: configURL)
// Now also try to get disk size from VM config if OCI annotation not found
var vmConfigDiskSize: UInt64? = nil
if uncompressedSize == nil && FileManager.default.fileExists(atPath: configURL.path) {
do {
let configData = try Data(contentsOf: configURL)
let decoder = JSONDecoder()
if let vmConfig = try? decoder.decode(VMConfig.self, from: configData) {
vmConfigDiskSize = vmConfig.diskSize
if let size = vmConfigDiskSize {
Logger.info("Found diskSize from VM config.json: \(size) bytes")
}
}
} catch {
Logger.error("Failed to parse VM config.json for diskSize: \(error)")
}
}
// Determine the size to use for the sparse file
// Use: annotation size > VM config diskSize > fallback (error)
if let size = uncompressedSize {
Logger.info("Using uncompressed size from annotation: \(size) bytes")
expectedTotalSize = size
} else if let size = vmConfigDiskSize {
Logger.info("Using diskSize from VM config: \(size) bytes")
expectedTotalSize = size
} else {
// If neither is found in cache scenario, throw error as we cannot determine the size
Logger.error(
"Missing both uncompressed size annotation and VM config diskSize for cached multi-part image."
+ " Cannot reassemble."
)
throw PullError.missingUncompressedSizeAnnotation
}
// Now that expectedTotalSize is guaranteed to be non-nil, proceed with setup
guard let sizeForTruncate = expectedTotalSize else {
// This should not happen due to the checks above, but safety first
let nilError: Error? = nil
// Use nil-coalescing to provide a default error, appeasing the compiler
throw PullError.reassemblySetupFailed(
path: outputURL.path, underlyingError: nilError ?? NoSpecificUnderlyingError())
}
// If we have just one disk part, use the shared function
if totalParts == 1 && !rawParts {
// Single part - use shared function
let sourceURL = diskPartSources[0].1 // Get the first source URL (index 1 of the tuple)
try createDiskImageFromSource(
sourceURL: sourceURL,
destinationURL: outputURL,
diskSize: sizeForTruncate
)
} else {
// Multiple parts - we need to reassemble
// Wrap file handle setup and sparse file creation within this block
let outputHandle: FileHandle
do {
// Ensure parent directory exists
try FileManager.default.createDirectory(
at: outputURL.deletingLastPathComponent(), withIntermediateDirectories: true
)
// Explicitly create the file first, removing old one if needed
if FileManager.default.fileExists(atPath: outputURL.path) {
try FileManager.default.removeItem(at: outputURL)
}
guard FileManager.default.createFile(atPath: outputURL.path, contents: nil)
else {
throw PullError.fileCreationFailed(outputURL.path)
}
// Open handle for writing
outputHandle = try FileHandle(forWritingTo: outputURL)
// Set the file size (creates sparse file)
try outputHandle.truncate(atOffset: sizeForTruncate)
Logger.info(
"Sparse file initialized for cache reassembly with size: \(ByteCountFormatter.string(fromByteCount: Int64(sizeForTruncate), countStyle: .file))"
)
} catch {
Logger.error(
"Failed during setup for cached disk image reassembly: \(error.localizedDescription)",
metadata: ["path": outputURL.path])
throw PullError.reassemblySetupFailed(
path: outputURL.path, underlyingError: error)
}
// Ensure handle is closed when exiting this scope
defer { try? outputHandle.close() }
var reassemblyProgressLogger = ProgressLogger(threshold: 0.05)
var currentOffset: UInt64 = 0
// Iterate from 1 up to the total number of parts found by the collector
for collectorPartNum in 1...totalParts {
// Find the source URL from our collected parts using the sequential collectorPartNum
guard
let sourceInfo = diskPartSources.first(where: { $0.0 == collectorPartNum })
else {
Logger.error(
"Missing required cached part number \(collectorPartNum) in collected parts during reassembly."
)
throw PullError.missingPart(collectorPartNum)
}
let sourceURL = sourceInfo.1 // Get URL from tuple
// Log using the sequential collector part number
Logger.info(
"Decompressing part \(collectorPartNum) of \(totalParts) from cache: \(sourceURL.lastPathComponent) at offset \(currentOffset)..."
)
// Always use the correct sparse decompression function
let decompressedBytesWritten =
try rawParts
? writeFileSparse(
sourceURL, to: outputHandle, startOffsets: [currentOffset])
: decompressChunkAndWriteSparse(
inputPath: sourceURL.path,
outputHandle: outputHandle,
startOffset: currentOffset
)
currentOffset += decompressedBytesWritten
// Update progress (using sizeForTruncate which should be available)
reassemblyProgressLogger.logProgress(
current: Double(currentOffset) / Double(sizeForTruncate),
context: "Reassembling Cache")
try outputHandle.synchronize() // Explicitly synchronize after each chunk
}
// Finalize progress, close handle (done by defer)
reassemblyProgressLogger.logProgress(current: 1.0, context: "Reassembly Complete")
// Ensure handle is properly synchronized before closing
try outputHandle.synchronize()
// Close handle explicitly instead of relying on defer
try outputHandle.close()
// Verify final size
let finalSize =
(try? FileManager.default.attributesOfItem(atPath: outputURL.path)[.size]
as? UInt64) ?? 0
Logger.info(
"Final disk image size from cache (before sparse file optimization): \(ByteCountFormatter.string(fromByteCount: Int64(finalSize), countStyle: .file))"
)
// Use the calculated sizeForTruncate for comparison
if finalSize != sizeForTruncate {
Logger.info(
"Warning: Final reported size (\(finalSize) bytes) differs from expected size (\(sizeForTruncate) bytes), but this doesn't affect functionality"
)
}
Logger.info("Disk image reassembly completed")
// Optimize sparseness for cached reassembly if on macOS
if FileManager.default.fileExists(atPath: "/bin/cp") {
Logger.info("Optimizing sparse file representation for cached reassembly...")
let optimizedPath = outputURL.path + ".optimized"
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
process.arguments = ["-c", outputURL.path, optimizedPath]
do {
try process.run()
process.waitUntilExit()
if process.terminationStatus == 0 {
// Get size of optimized file
let optimizedSize =
(try? FileManager.default.attributesOfItem(atPath: optimizedPath)[
.size] as? UInt64) ?? 0
let originalUsage = getActualDiskUsage(path: outputURL.path)
let optimizedUsage = getActualDiskUsage(path: optimizedPath)
Logger.info(
"Sparse optimization results for cache: Before: \(ByteCountFormatter.string(fromByteCount: Int64(originalUsage), countStyle: .file)) actual usage, After: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedUsage), countStyle: .file)) actual usage (Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedSize), countStyle: .file)))"
)
// Replace the original with the optimized version
try FileManager.default.removeItem(at: outputURL)
try FileManager.default.moveItem(
at: URL(fileURLWithPath: optimizedPath), to: outputURL)
Logger.info("Replaced cached reassembly with optimized sparse version")
} else {
Logger.info("Sparse optimization failed for cache, using original file")
try? FileManager.default.removeItem(atPath: optimizedPath)
}
} catch {
Logger.info(
"Error during sparse optimization for cache: \(error.localizedDescription)"
)
try? FileManager.default.removeItem(atPath: optimizedPath)
}
}
// Set permissions to ensure consistency
let chmodProcess = Process()
chmodProcess.executableURL = URL(fileURLWithPath: "/bin/chmod")
chmodProcess.arguments = ["0644", outputURL.path]
try chmodProcess.run()
chmodProcess.waitUntilExit()
}
// After successful reassembly, store the reassembled image in the cache
if cachingEnabled {
Logger.info("Saving reassembled disk image to cache for future use")
// Copy the reassembled disk image to the cache
try FileManager.default.copyItem(at: outputURL, to: reassembledCachePath)
// Clean up disk parts after successful reassembly
Logger.info("Cleaning up disk part files from cache")
// Use an array to track unique file paths to avoid trying to delete the same file multiple times
var processedPaths: [String] = []
for (_, partURL) in diskPartSources {
let path = partURL.path
// Skip if we've already processed this exact path
if processedPaths.contains(path) {
Logger.info("Skipping duplicate part file: \(partURL.lastPathComponent)")
continue
}
// Add to processed array
processedPaths.append(path)
// Check if file exists before attempting to delete
if FileManager.default.fileExists(atPath: path) {
do {
try FileManager.default.removeItem(at: partURL)
Logger.info("Removed disk part: \(partURL.lastPathComponent)")
} catch {
Logger.info(
"Failed to remove disk part: \(partURL.lastPathComponent) - \(error.localizedDescription)"
)
}
} else {
Logger.info("Disk part already removed: \(partURL.lastPathComponent)")
}
}
// Also save nvram if we have it
if hasNvram {
let srcNvram = destination.appendingPathComponent("nvram.bin")
if FileManager.default.fileExists(atPath: srcNvram.path) {
try? FileManager.default.copyItem(at: srcNvram, to: nvramCachePath)
}
}
// Save config.json in the cache for future use if it exists
if let configPath = configPath {
let cacheConfigPath = cacheDir.appendingPathComponent("config.json")
try? FileManager.default.copyItem(at: configPath, to: cacheConfigPath)
}
// Perform a final cleanup to catch any leftover part files
Logger.info("Performing final cleanup of any remaining part files")
do {
let cacheContents = try FileManager.default.contentsOfDirectory(
at: cacheDir, includingPropertiesForKeys: nil)
for item in cacheContents {
let fileName = item.lastPathComponent
// Only remove sha256_ files that aren't the reassembled image, nvram or config
if fileName.starts(with: "sha256_") && fileName != "disk.img.reassembled"
&& fileName != "nvram.bin" && fileName != "config.json"
&& fileName != "manifest.json" && fileName != "metadata.json"
{
do {
try FileManager.default.removeItem(at: item)
Logger.info(
"Removed leftover file during final cleanup: \(fileName)")
} catch {
Logger.info(
"Failed to remove leftover file: \(fileName) - \(error.localizedDescription)"
)
}
}
}
} catch {
Logger.info("Error during final cleanup: \(error.localizedDescription)")
}
}
}
Logger.debug("Cache copy complete")
}
private func getToken(
repository: String, scopes: [String] = ["pull"], requireAllScopes: Bool = false
) async throws
-> String
{
let encodedRepo =
repository.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? repository
// Build scope string from scopes array
let scopeString = scopes.joined(separator: ",")
Logger.debug("Requesting token with scopes: \(scopeString) for repository: \(repository)")
// Request both pull and push scope for uploads
let url = URL(
string:
"https://\(self.registry)/token?scope=repository:\(encodedRepo):\(scopeString)&service=\(self.registry)"
)!
var request = URLRequest(url: url)
request.httpMethod = "GET" // Token endpoint uses GET
request.setValue("application/json", forHTTPHeaderField: "Accept")
// *** Add Basic Authentication Header if credentials exist ***
let (username, password) = getCredentialsFromEnvironment()
if let username = username, let password = password, !username.isEmpty, !password.isEmpty {
let authString = "\(username):\(password)"
if let authData = authString.data(using: .utf8) {
let base64Auth = authData.base64EncodedString()
request.setValue("Basic \(base64Auth)", forHTTPHeaderField: "Authorization")
Logger.debug("Adding Basic Authentication header to token request")
} else {
Logger.error("Failed to encode credentials for Basic Auth")
}
} else {
Logger.debug("No credentials found in environment for token request")
// Allow anonymous request for pull scope, but push scope likely requires auth
}
// *** End Basic Auth addition ***
let (data, response) = try await URLSession.shared.data(for: request)
// Check response status code *before* parsing JSON
guard let httpResponse = response as? HTTPURLResponse else {
throw PushError.authenticationFailed // Or a more generic network error
}
// Handle errors based on status code
if httpResponse.statusCode != 200 {
// Special handling for push operations that require all scopes
if requireAllScopes
&& (httpResponse.statusCode == 401 || httpResponse.statusCode == 403)
{
// Try to parse the error message from the response
let errorResponse = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
let errors = errorResponse?["errors"] as? [[String: Any]]
let errorMessage = errors?.first?["message"] as? String ?? "Permission denied"
Logger.error("Push permission denied: \(errorMessage)")
Logger.error(
"Your token does not have 'packages:write' permission to \(repository)")
Logger.error("Make sure you have the appropriate access rights to the repository")
// Check if this is an organization repository
if repository.contains("/") {
let orgName = repository.split(separator: "/").first.map(String.init) ?? ""
if orgName != "" {
Logger.error("For organization repositories (\(orgName)), you must:")
Logger.error("1. Be a member of the organization with write access")
Logger.error("2. Have a token with 'write:packages' scope")
Logger.error(
"3. The organization must allow you to create/publish packages")
}
}
throw PushError.insufficientPermissions("Push permission denied: \(errorMessage)")
}
// If we get 403 and we're requesting both pull and push, retry with just pull
// ONLY if requireAllScopes is false
if httpResponse.statusCode == 403 && scopes.contains("push")
&& scopes.contains("pull") && !requireAllScopes
{
Logger.info("Permission denied for push scope, retrying with pull scope only")
return try await getToken(repository: repository, scopes: ["pull"])
}
// For pull scope only, if authentication fails, assume this is a public image
// and continue without a token (empty string)
if scopes == ["pull"] {
Logger.info(
"Authentication failed for pull scope, assuming public image and continuing without token"
)
return ""
}
// Handle other authentication failures
let responseBody = String(data: data, encoding: .utf8) ?? "(Could not decode body)"
Logger.error(
"Token request failed with status code: \(httpResponse.statusCode). Response: \(responseBody)"
)
throw PushError.authenticationFailed
}
let jsonResponse = try JSONSerialization.jsonObject(with: data) as? [String: Any]
guard
let token = jsonResponse?["token"] as? String ?? jsonResponse?["access_token"]
as? String
else {
Logger.error("Token not found in registry response")
throw PushError.missingToken
}
return token
}
private func fetchManifest(repository: String, tag: String, token: String) async throws -> (
Manifest, String
) {
var request = URLRequest(
url: URL(string: "https://\(self.registry)/v2/\(repository)/manifests/\(tag)")!)
// Only add Authorization header if token is not empty
if !token.isEmpty {
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
request.addValue("application/vnd.oci.image.manifest.v1+json", forHTTPHeaderField: "Accept")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200,
let digest = httpResponse.value(forHTTPHeaderField: "Docker-Content-Digest")
else {
throw PullError.manifestFetchFailed
}
let manifest = try JSONDecoder().decode(Manifest.self, from: data)
return (manifest, digest)
}
/// Downloads one blob to `url`, reporting bytes to `progress` as they arrive.
///
/// The blob is verified against its digest before it counts as done or is
/// copied into the cache, so the cache only ever holds verified layers. A
/// failed attempt drops its in-flight bytes before retrying. Task
/// cancellation stops the transfer at once (URLSession removes its temp
/// file) and ends the retry loop instead of retrying.
func downloadLayer(
repository: String,
digest: String,
mediaType: String,
token: String,
to url: URL,
maxRetries: Int = 5,
progress: ProgressTracker,
manifestId: String? = nil,
onBytes: (@Sendable (Int64) -> Void)? = nil
) async throws {
// Whatever happens, this pull no longer downloads the digest.
defer { markDownloadComplete(digest) }
var lastError: Error?
for attempt in 1...maxRetries {
try Task.checkCancellation()
let transferId = "\(digest)#\(UUID().uuidString)"
do {
var request = URLRequest(
url: URL(string: "https://\(self.registry)/v2/\(repository)/blobs/\(digest)")!)
// Only add Authorization header if token is not empty
if !token.isEmpty {
request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
request.addValue(mediaType, forHTTPHeaderField: "Accept")
request.timeoutInterval = 60
// Request identity encoding: blobs are content-addressed, so transparent
// gzip/deflate decompression by URLSession would corrupt the stored bytes.
request.setValue("identity", forHTTPHeaderField: "Accept-Encoding")
try FileManager.default.createDirectory(
at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
let written = try await LayerDownload.run(
request: request,
configuration: makeLayerSessionConfiguration(),
to: url,
onBytes: { bytes in
onBytes?(bytes)
Task { await progress.updateTransfer(id: transferId, bytesWritten: bytes) }
})
try Task.checkCancellation()
// Verify the layer against its digest before caching it; a mismatch means
// a corrupt blob, so drop it and let the retry loop re-download (issue #296).
if digest.hasPrefix("sha256:") {
let expected = String(digest.dropFirst("sha256:".count)).lowercased()
let actual = try sha256OfFile(at: url)
if actual != expected {
try? FileManager.default.removeItem(at: url)
throw PullError.layerVerificationFailed(
expected: digest, actual: "sha256:\(actual)")
}
}
// Always save a copy to the cache directory for use by copyFromCache,
// even if caching is disabled
if let manifestId = manifestId {
let cachedLayer = getCachedLayerPath(manifestId: manifestId, digest: digest)
try storeVerifiedLayer(from: url, inCacheAt: cachedLayer)
}
await progress.finishTransfer(id: transferId, bytes: written)
return
} catch {
await progress.dropTransfer(id: transferId)
if Task.isCancelled || error is CancellationError {
try? FileManager.default.removeItem(at: url)
throw CancellationError()
}
lastError = error
if case PullError.layerVerificationFailed(let expected, let actual) = error {
Logger.info(
"Layer checksum mismatch (expected \(expected), got \(actual)); will re-download."
)
}
if attempt < maxRetries {
// Exponential backoff with jitter for retries. Task.sleep throws
// on cancellation, which ends the loop instead of retrying.
let baseDelay = Double(attempt) * retryBaseDelay
let jitter = Double.random(in: 0...1) * min(1, retryBaseDelay)
let delay = baseDelay + jitter
try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
Logger.info("Retrying download (attempt \(attempt+1)/\(maxRetries)): \(digest)")
}
}
}
throw lastError ?? PullError.layerDownloadFailed(digest)
}
/// Session configuration for one layer download attempt.
private func makeLayerSessionConfiguration() -> URLSessionConfiguration {
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 60
config.timeoutIntervalForResource = 3600
config.waitsForConnectivity = true
config.httpMaximumConnectionsPerHost = 6
config.httpShouldUsePipelining = true
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.httpAdditionalHeaders = ["Connection": "keep-alive"]
// Check for TCP window size and optimize if possible
if getTCPReceiveWindowSize() != nil {
config.networkServiceType = .responsiveData
}
if let protocolClasses = urlProtocolClasses {
config.protocolClasses = protocolClasses
}
return config
}
/// Copies a verified layer into the cache without ever exposing a partial
/// file under the cached name: the copy goes to a hidden sibling first and
/// is renamed into place once complete.
func storeVerifiedLayer(from source: URL, inCacheAt cachedLayer: URL) throws {
let fm = FileManager.default
try fm.createDirectory(
at: cachedLayer.deletingLastPathComponent(), withIntermediateDirectories: true)
let staging = cachedLayer.deletingLastPathComponent().appendingPathComponent(
".\(cachedLayer.lastPathComponent)\(Self.cacheStagingMarker)\(UUID().uuidString)")
defer { try? fm.removeItem(at: staging) }
try fm.copyItem(at: source, to: staging)
if fm.fileExists(atPath: cachedLayer.path) {
_ = try fm.replaceItemAt(cachedLayer, withItemAt: staging)
} else {
try fm.moveItem(at: staging, to: cachedLayer)
}
}
// Function removed as it's not applicable to the observed manifest format
/*
private func extractPartInfo(from mediaType: String) -> (partNum: Int, total: Int)? {
let pattern = #"part\\.number=(\\d+);part\\.total=(\\d+)"#
guard let regex = try? NSRegularExpression(pattern: pattern),
let match = regex.firstMatch(
in: mediaType,
range: NSRange(mediaType.startIndex..., in: mediaType)
),
let partNumRange = Range(match.range(at: 1), in: mediaType),
let totalRange = Range(match.range(at: 2), in: mediaType),
let partNum = Int(mediaType[partNumRange]),
let total = Int(mediaType[totalRange])
else {
return nil
}
return (partNum, total)
}
*/
private func listRepositories() async throws -> [String] {
var request = URLRequest(
url: URL(string: "https://\(registry)/v2/\(organization)/repositories/list")!)
request.setValue("application/json", forHTTPHeaderField: "Accept")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw PullError.manifestFetchFailed
}
if httpResponse.statusCode == 404 {
return []
}
guard httpResponse.statusCode == 200 else {
throw PullError.manifestFetchFailed
}
let repoList = try JSONDecoder().decode(RepositoryList.self, from: data)
return repoList.repositories
}
func getImages() async throws -> [CachedImage] {
Logger.info("Scanning for cached images in \(cacheDirectory.path)")
var images: [CachedImage] = []
let orgDir = cacheDirectory.appendingPathComponent(organization)
if FileManager.default.fileExists(atPath: orgDir.path) {
let contents = try FileManager.default.contentsOfDirectory(atPath: orgDir.path)
Logger.info("Found \(contents.count) items in cache directory")
for item in contents {
let itemPath = orgDir.appendingPathComponent(item)
var isDirectory: ObjCBool = false
guard
FileManager.default.fileExists(
atPath: itemPath.path, isDirectory: &isDirectory),
isDirectory.boolValue
else { continue }
// First try to read metadata file
let metadataPath = itemPath.appendingPathComponent("metadata.json")
if let metadataData = try? Data(contentsOf: metadataPath),
let metadata = try? JSONDecoder().decode(ImageMetadata.self, from: metadataData)
{
Logger.info(
"Found metadata for image",
metadata: [
"image": metadata.image,
"manifest_id": metadata.manifestId,
])
images.append(
CachedImage(
repository: metadata.image,
imageId: String(metadata.manifestId.prefix(12)),
manifestId: metadata.manifestId
))
continue
}
// Fallback to checking manifest if metadata doesn't exist
Logger.info("No metadata found for \(item), checking manifest")
let manifestPath = itemPath.appendingPathComponent("manifest.json")
guard FileManager.default.fileExists(atPath: manifestPath.path),
let manifestData = try? Data(contentsOf: manifestPath),
let manifest = try? JSONDecoder().decode(Manifest.self, from: manifestData)
else {
Logger.info("No valid manifest found for \(item)")
continue
}
let manifestId = item
// Verify the manifest ID matches
let currentManifestId = getManifestIdentifier(manifest, manifestDigest: "")
Logger.info(
"Manifest check",
metadata: [
"item": item,
"current_manifest_id": currentManifestId,
"matches": "\(currentManifestId == manifestId)",
])
if currentManifestId == manifestId {
// Skip if we can't determine the repository name
// This should be rare since we now save metadata during pull
Logger.info("Skipping image without metadata: \(item)")
continue
}
}
} else {
Logger.info("Cache directory does not exist")
}
Logger.info("Found \(images.count) cached images")
return images.sorted {
$0.repository == $1.repository ? $0.imageId < $1.imageId : $0.repository < $1.repository
}
}
private func listRemoteImageTags(repository: String) async throws -> [String] {
var request = URLRequest(
url: URL(string: "https://\(registry)/v2/\(organization)/\(repository)/tags/list")!)
request.setValue("application/json", forHTTPHeaderField: "Accept")
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw PullError.manifestFetchFailed
}
if httpResponse.statusCode == 404 {
return []
}
guard httpResponse.statusCode == 200 else {
throw PullError.manifestFetchFailed
}
let repoTags = try JSONDecoder().decode(RepositoryTags.self, from: data)
return repoTags.tags
}
// Determine appropriate chunk size based on available system memory on macOS
private func getOptimalChunkSize() -> Int {
// Try to get system memory info
var stats = vm_statistics64_data_t()
var size = mach_msg_type_number_t(
MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)
let hostPort = mach_host_self()
let result = withUnsafeMutablePointer(to: &stats) { statsPtr in
statsPtr.withMemoryRebound(to: integer_t.self, capacity: Int(size)) { ptr in
host_statistics64(hostPort, HOST_VM_INFO64, ptr, &size)
}
}
// Define chunk size parameters
let safeMinimumChunkSize = 128 * 1024 // Reduced minimum for constrained systems
let defaultChunkSize = 512 * 1024 // Standard default / minimum for non-constrained
let constrainedCap = 512 * 1024 // Lower cap for constrained systems
let standardCap = 2 * 1024 * 1024 // Standard cap for non-constrained systems
// If we can't get memory info, return a reasonable default
guard result == KERN_SUCCESS else {
Logger.info(
"Could not get VM statistics, using default chunk size: \(defaultChunkSize) bytes")
return defaultChunkSize
}
// Calculate free memory in bytes
let pageSize = 4096 // Use a constant page size assumption
let freeMemory = UInt64(stats.free_count) * UInt64(pageSize)
let isConstrained = determineIfMemoryConstrained() // Check if generally constrained
// Extremely constrained (< 512MB free) -> use absolute minimum
if freeMemory < 536_870_912 { // 512MB
Logger.info(
"System extremely memory constrained (<512MB free), using minimum chunk size: \(safeMinimumChunkSize) bytes"
)
return safeMinimumChunkSize
}
// Generally constrained -> use adaptive size with lower cap
if isConstrained {
let adaptiveSize = min(
max(Int(freeMemory / 1000), safeMinimumChunkSize), constrainedCap)
Logger.info(
"System memory constrained, using adaptive chunk size capped at \(constrainedCap) bytes: \(adaptiveSize) bytes"
)
return adaptiveSize
}
// Not constrained -> use original adaptive logic with standard cap
let adaptiveSize = min(max(Int(freeMemory / 1000), defaultChunkSize), standardCap)
Logger.info(
"System has sufficient memory, using adaptive chunk size capped at \(standardCap) bytes: \(adaptiveSize) bytes"
)
return adaptiveSize
}
// Check if system is memory constrained for more aggressive memory management
private func determineIfMemoryConstrained() -> Bool {
var stats = vm_statistics64_data_t()
var size = mach_msg_type_number_t(
MemoryLayout<vm_statistics64_data_t>.size / MemoryLayout<integer_t>.size)
let hostPort = mach_host_self()
let result = withUnsafeMutablePointer(to: &stats) { statsPtr in
statsPtr.withMemoryRebound(to: integer_t.self, capacity: Int(size)) { ptr in
host_statistics64(hostPort, HOST_VM_INFO64, ptr, &size)
}
}
guard result == KERN_SUCCESS else {
// If we can't determine, assume constrained for safety
return true
}
// Calculate free memory in bytes using a fixed page size
// Standard page size on macOS is 4KB or 16KB
let pageSize = 4096 // Use a constant instead of vm_kernel_page_size
let freeMemory = UInt64(stats.free_count) * UInt64(pageSize)
// Consider memory constrained if less than 2GB free
return freeMemory < 2_147_483_648 // 2GB
}
// Helper method to determine network quality
private func determineNetworkQuality() -> Int {
// Default quality is medium (3)
var quality = 3
// A simple ping test to determine network quality
let process = Process()
process.executableURL = URL(fileURLWithPath: "/sbin/ping")
process.arguments = ["-c", "3", "-q", self.registry]
let outputPipe = Pipe()
process.standardOutput = outputPipe
process.standardError = outputPipe
do {
try process.run()
process.waitUntilExit()
let outputData = try outputPipe.fileHandleForReading.readToEnd() ?? Data()
if let output = String(data: outputData, encoding: .utf8) {
// Check for average ping time
if let avgTimeRange = output.range(
of: "= [0-9.]+/([0-9.]+)/", options: .regularExpression)
{
let avgSubstring = output[avgTimeRange]
if let avgString = avgSubstring.split(separator: "/").dropFirst().first,
let avgTime = Double(avgString)
{
// Classify network quality based on ping time
if avgTime < 50 {
quality = 5 // Excellent
} else if avgTime < 100 {
quality = 4 // Good
} else if avgTime < 200 {
quality = 3 // Average
} else if avgTime < 300 {
quality = 2 // Poor
} else {
quality = 1 // Very poor
}
}
}
}
} catch {
// Default to medium if ping fails
Logger.info("Failed to determine network quality, using default settings")
}
return quality
}
// Helper method to calculate optimal concurrency based on system capabilities
private func calculateOptimalConcurrency(memoryConstrained: Bool, networkQuality: Int) -> Int {
// Base concurrency based on network quality (1-5)
let baseThreads = min(networkQuality * 2, 8)
if memoryConstrained {
// Reduce concurrency for memory-constrained systems
return max(2, baseThreads / 2)
}
// Physical cores available on the system
let cores = ProcessInfo.processInfo.processorCount
// Adaptive approach: 1-2 threads per core depending on network quality
let threadsPerCore = (networkQuality >= 4) ? 2 : 1
let systemBasedThreads = min(cores * threadsPerCore, 12)
// Take the larger of network-based and system-based concurrency
return max(baseThreads, systemBasedThreads)
}
// Helper to get optimal TCP window size
private func getTCPReceiveWindowSize() -> Int? {
// Try to query system TCP window size
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/sysctl")
process.arguments = ["net.inet.tcp.recvspace"]
let outputPipe = Pipe()
process.standardOutput = outputPipe
do {
try process.run()
process.waitUntilExit()
let outputData = try outputPipe.fileHandleForReading.readToEnd() ?? Data()
if let output = String(data: outputData, encoding: .utf8),
let valueStr = output.split(separator: ":").last?.trimmingCharacters(
in: .whitespacesAndNewlines),
let value = Int(valueStr)
{
return value
}
} catch {
// Ignore errors, we'll use defaults
}
return nil
}
// Add helper to check media type and get decompress command
private func getDecompressionCommand(for mediaType: String) -> String? {
// Determine appropriate decompression command based on layer media type
Logger.info("Determining decompression command for media type: \(mediaType)")
// For the specific format that appears in our GHCR repository, skip decompression attempts
// These files are labeled +lzfse but aren't actually in Apple Archive format
if mediaType.contains("+lzfse;part.number=") {
Logger.info("Detected LZFSE part file, using direct copy instead of decompression")
return nil
}
// Check for LZFSE or Apple Archive format anywhere in the media type string
// The format may include part information like: application/octet-stream+lzfse;part.number=1;part.total=38
if mediaType.contains("+lzfse") || mediaType.contains("+aa") {
// Apple Archive format requires special handling
if let aaPath = findExecutablePath(for: "aa") {
Logger.info("Found Apple Archive tool at: \(aaPath)")
return "apple_archive:\(aaPath)"
} else {
Logger.error(
"Apple Archive tool (aa) not found in PATH, falling back to default path")
// Check if the default path exists
let defaultPath = "/usr/bin/aa"
if FileManager.default.isExecutableFile(atPath: defaultPath) {
Logger.info("Default Apple Archive tool exists at: \(defaultPath)")
} else {
Logger.error("Default Apple Archive tool not found at: \(defaultPath)")
}
return "apple_archive:/usr/bin/aa"
}
} else {
Logger.info(
"Unsupported media type: \(mediaType) - only Apple Archive (+lzfse/+aa) is supported"
)
return nil
}
}
// Helper to find executables (optional, or hardcode paths)
private func findExecutablePath(for executableName: String) -> String? {
let pathEnv =
ProcessInfo.processInfo.environment["PATH"]
?? "/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin"
let paths = pathEnv.split(separator: ":")
for path in paths {
let executablePath = URL(fileURLWithPath: String(path)).appendingPathComponent(
executableName
).path
if FileManager.default.isExecutableFile(atPath: executablePath) {
return executablePath
}
}
return nil
}
// Helper function to extract uncompressed disk size from config.json
private func getUncompressedSizeFromConfig(configPath: URL) -> UInt64? {
guard FileManager.default.fileExists(atPath: configPath.path) else {
Logger.info("Config file not found: \(configPath.path)")
return nil
}
do {
let configData = try Data(contentsOf: configPath)
let decoder = JSONDecoder()
let ociConfig = try decoder.decode(OCIConfig.self, from: configData)
if let sizeString = ociConfig.annotations?.uncompressedSize,
let size = UInt64(sizeString)
{
Logger.info("Found uncompressed disk size annotation: \(size) bytes")
return size
} else {
Logger.info("No uncompressed disk size annotation found in config.json")
return nil
}
} catch {
Logger.error("Failed to parse config.json for uncompressed size: \(error)")
return nil
}
}
// Helper function to find formatted file with potential extensions
private func findFormattedFile(tempFormatted: URL) -> URL? {
// Check for the exact path first
if FileManager.default.fileExists(atPath: tempFormatted.path) {
return tempFormatted
}
// Check with .dmg extension
let dmgPath = tempFormatted.path + ".dmg"
if FileManager.default.fileExists(atPath: dmgPath) {
return URL(fileURLWithPath: dmgPath)
}
// Check with .sparseimage extension
let sparsePath = tempFormatted.path + ".sparseimage"
if FileManager.default.fileExists(atPath: sparsePath) {
return URL(fileURLWithPath: sparsePath)
}
// Try to find any file with the same basename
do {
let files = try FileManager.default.contentsOfDirectory(
at: tempFormatted.deletingLastPathComponent(),
includingPropertiesForKeys: nil)
if let matchingFile = files.first(where: {
$0.lastPathComponent.starts(with: tempFormatted.lastPathComponent)
}) {
return matchingFile
}
} catch {
Logger.error("Failed to list directory contents: \(error)")
}
return nil
}
// Helper function to decompress LZFSE compressed disk image
@discardableResult
private func decompressLZFSEImage(inputPath: String, outputPath: String? = nil) -> Bool {
Logger.info("Attempting to decompress LZFSE compressed disk image using sparse pipe...")
let finalOutputPath = outputPath ?? inputPath // If outputPath is nil, we'll overwrite input
let tempFinalPath = finalOutputPath + ".ddsparse.tmp" // Temporary name during dd operation
// Ensure the temporary file doesn't exist from a previous failed run
try? FileManager.default.removeItem(atPath: tempFinalPath)
// Process 1: compression_tool
let process1 = Process()
process1.executableURL = URL(fileURLWithPath: "/usr/bin/compression_tool")
process1.arguments = [
"-decode",
"-i", inputPath,
"-o", "/dev/stdout", // Write to standard output
]
// Process 2: dd
let process2 = Process()
process2.executableURL = URL(fileURLWithPath: "/bin/dd")
process2.arguments = [
"if=/dev/stdin", // Read from standard input
"of=\(tempFinalPath)", // Write to the temporary final path
"conv=sparse", // Use sparse conversion
"bs=1m", // Use a reasonable block size (e.g., 1MB)
]
// Create pipes
let pipe = Pipe() // Connects process1 stdout to process2 stdin
let errorPipe1 = Pipe()
let errorPipe2 = Pipe()
process1.standardOutput = pipe
process1.standardError = errorPipe1
process2.standardInput = pipe
process2.standardError = errorPipe2
do {
Logger.info("Starting decompression pipe: compression_tool | dd conv=sparse...")
// Start processes
try process1.run()
try process2.run()
// Close the write end of the pipe for process2 to prevent hanging
// This might not be strictly necessary if process1 exits cleanly, but safer.
// Note: Accessing fileHandleForWriting after run can be tricky.
// We rely on process1 exiting to signal EOF to process2.
process1.waitUntilExit()
process2.waitUntilExit() // Wait for dd to finish processing the stream
// --- Check for errors ---
let errorData1 = errorPipe1.fileHandleForReading.readDataToEndOfFile()
if !errorData1.isEmpty,
let errorString = String(data: errorData1, encoding: .utf8)?.trimmingCharacters(
in: .whitespacesAndNewlines), !errorString.isEmpty
{
Logger.error("compression_tool stderr: \(errorString)")
}
let errorData2 = errorPipe2.fileHandleForReading.readDataToEndOfFile()
if !errorData2.isEmpty,
let errorString = String(data: errorData2, encoding: .utf8)?.trimmingCharacters(
in: .whitespacesAndNewlines), !errorString.isEmpty
{
// dd often reports blocks in/out to stderr, filter that if needed, but log for now
Logger.info("dd stderr: \(errorString)")
}
// Check termination statuses
let status1 = process1.terminationStatus
let status2 = process2.terminationStatus
if status1 != 0 || status2 != 0 {
Logger.error(
"Pipe command failed. compression_tool status: \(status1), dd status: \(status2)"
)
try? FileManager.default.removeItem(atPath: tempFinalPath) // Clean up failed attempt
return false
}
// --- Validation ---
if FileManager.default.fileExists(atPath: tempFinalPath) {
let fileSize =
(try? FileManager.default.attributesOfItem(atPath: tempFinalPath)[.size]
as? UInt64) ?? 0
let actualUsage = getActualDiskUsage(path: tempFinalPath)
Logger.info(
"Piped decompression successful - Allocated: \(ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)), Actual Usage: \(ByteCountFormatter.string(fromByteCount: Int64(actualUsage), countStyle: .file))"
)
// Basic header validation
var isValid = false
if let fileHandle = FileHandle(forReadingAtPath: tempFinalPath) {
if let data = try? fileHandle.read(upToCount: 512), data.count >= 512,
data[510] == 0x55 && data[511] == 0xAA
{
isValid = true
}
// Ensure handle is closed regardless of validation outcome
try? fileHandle.close()
} else {
Logger.error(
"Validation Error: Could not open decompressed file handle for reading.")
}
if isValid {
Logger.info("Decompressed file appears to be a valid disk image.")
// Move the final file into place
// If outputPath was nil, we need to replace the original inputPath
if outputPath == nil {
// Backup original only if it's different from the temp path
if inputPath != tempFinalPath {
try? FileManager.default.copyItem(
at: URL(fileURLWithPath: inputPath),
to: URL(fileURLWithPath: inputPath + ".compressed.bak"))
try? FileManager.default.removeItem(at: URL(fileURLWithPath: inputPath))
}
try FileManager.default.moveItem(
at: URL(fileURLWithPath: tempFinalPath),
to: URL(fileURLWithPath: inputPath))
Logger.info("Replaced original file with sparsely decompressed version.")
} else {
// If outputPath was specified, move it there (overwrite if needed)
try? FileManager.default.removeItem(
at: URL(fileURLWithPath: finalOutputPath)) // Remove existing if overwriting
try FileManager.default.moveItem(
at: URL(fileURLWithPath: tempFinalPath),
to: URL(fileURLWithPath: finalOutputPath))
Logger.info("Moved sparsely decompressed file to: \(finalOutputPath)")
}
return true
} else {
Logger.error(
"Validation failed: Decompressed file header is invalid or file couldn't be read. Cleaning up."
)
try? FileManager.default.removeItem(atPath: tempFinalPath)
return false
}
} else {
Logger.error(
"Piped decompression failed: Output file '\(tempFinalPath)' not found after dd completed."
)
return false
}
} catch {
Logger.error("Error running decompression pipe command: \(error)")
try? FileManager.default.removeItem(atPath: tempFinalPath) // Clean up on error
return false
}
}
// Helper function to get actual disk usage of a file
private func getActualDiskUsage(path: String) -> UInt64 {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/usr/bin/du")
task.arguments = ["-k", path] // -k for 1024-byte blocks
let pipe = Pipe()
task.standardOutput = pipe
do {
try task.run()
task.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8),
let size = UInt64(output.split(separator: "\t").first ?? "0")
{
return size * 1024 // Convert from KB to bytes
}
} catch {
Logger.error("Failed to get actual disk usage: \(error)")
}
return 0
}
// New push method
public func push(
vmDirPath: String,
imageName: String,
tags: [String],
chunkSizeMb: Int = 512,
verbose: Bool = false,
dryRun: Bool = false,
reassemble: Bool = false,
singleLayer: Bool = false,
legacy: Bool = false
) async throws {
if !legacy {
try await pushOCI(
vmDirPath: vmDirPath,
imageName: imageName,
tags: tags,
chunkSizeMb: chunkSizeMb,
singleLayer: singleLayer,
verbose: verbose,
dryRun: dryRun
)
return
}
Logger.debug(
"Pushing VM to registry",
metadata: [
"vm_path": vmDirPath,
"imageName": imageName,
"tags": "\(tags.joined(separator: ", "))", // Log all tags
"registry": registry,
"organization": organization,
"chunk_size": "\(chunkSizeMb)MB",
"dry_run": "\(dryRun)",
"reassemble": "\(reassemble)",
])
// Check for credentials if not in dry-run mode
if !dryRun {
let (username, token) = getCredentialsFromEnvironment()
if username == nil || token == nil {
Logger.error(
"Missing GitHub credentials. Please set GITHUB_USERNAME and GITHUB_TOKEN environment variables"
)
Logger.error(
"Your token must have 'packages:read' and 'packages:write' permissions")
throw PushError.authenticationFailed
}
Logger.info("Using GitHub credentials from environment variables")
}
// Remove tag parsing here, imageName is now passed directly
// let components = image.split(separator: ":") ...
// let imageTag = String(tag)
// Get authentication token only if not in dry-run mode
var token: String = ""
if !dryRun {
Logger.debug("Getting registry authentication token")
token = try await getToken(
repository: "\(self.organization)/\(imageName)",
scopes: ["pull", "push"],
requireAllScopes: true) // Require push scope, don't fall back to pull-only
} else {
Logger.info("Dry run mode: skipping authentication token request")
}
// Create working directory inside the VM folder for caching/resuming
let workDir = URL(fileURLWithPath: vmDirPath).appendingPathComponent(".lume_push_cache")
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
Logger.info("Using push cache directory: \(workDir.path)")
// Get VM files that need to be pushed using vmDirPath
let diskPath = URL(fileURLWithPath: vmDirPath).appendingPathComponent("disk.img")
let configPath = URL(fileURLWithPath: vmDirPath).appendingPathComponent("config.json")
let nvramPath = URL(fileURLWithPath: vmDirPath).appendingPathComponent("nvram.bin")
var layers: [OCIManifestLayer] = []
var uncompressedDiskSize: UInt64? = nil
// Process config.json
let cachedConfigPath = workDir.appendingPathComponent("config.json")
var configDigest: String? = nil
var configSize: Int? = nil
if FileManager.default.fileExists(atPath: cachedConfigPath.path) {
Logger.info("Using cached config.json")
do {
let configData = try Data(contentsOf: cachedConfigPath)
configDigest = "sha256:" + configData.sha256String()
configSize = configData.count
// Try to get uncompressed disk size from cached config
if let vmConfig = try? JSONDecoder().decode(VMConfig.self, from: configData) {
uncompressedDiskSize = vmConfig.diskSize
Logger.info(
"Found disk size in cached config: \(uncompressedDiskSize ?? 0) bytes")
}
} catch {
Logger.error("Failed to read cached config.json: \(error). Will re-process.")
// Force re-processing by leaving configDigest nil
}
} else if FileManager.default.fileExists(atPath: configPath.path) {
Logger.info("Processing config.json")
let configData = try Data(contentsOf: configPath)
configDigest = "sha256:" + configData.sha256String()
configSize = configData.count
try configData.write(to: cachedConfigPath) // Save to cache
// Try to get uncompressed disk size from original config
if let vmConfig = try? JSONDecoder().decode(VMConfig.self, from: configData) {
uncompressedDiskSize = vmConfig.diskSize
Logger.info("Found disk size in config: \(uncompressedDiskSize ?? 0) bytes")
}
}
if var digest = configDigest, let size = configSize { // Use 'var' to modify if uploaded
if !dryRun {
// Upload only if not in dry-run mode and blob doesn't exist
if !(try await blobExists(
repository: "\(self.organization)/\(imageName)", digest: digest, token: token))
{
Logger.info("Uploading config.json blob")
let configData = try Data(contentsOf: cachedConfigPath) // Read from cache for upload
digest = try await uploadBlobFromData(
repository: "\(self.organization)/\(imageName)",
data: configData,
token: token
)
} else {
Logger.info("Config blob already exists on registry")
}
}
// Add config layer
layers.append(
OCIManifestLayer(
mediaType: "application/vnd.oci.image.config.v1+json",
size: size,
digest: digest
))
}
// Process nvram.bin
let cachedNvramPath = workDir.appendingPathComponent("nvram.bin")
var nvramDigest: String? = nil
var nvramSize: Int? = nil
if FileManager.default.fileExists(atPath: cachedNvramPath.path) {
Logger.info("Using cached nvram.bin")
do {
let nvramData = try Data(contentsOf: cachedNvramPath)
nvramDigest = "sha256:" + nvramData.sha256String()
nvramSize = nvramData.count
} catch {
Logger.error("Failed to read cached nvram.bin: \(error). Will re-process.")
}
} else if FileManager.default.fileExists(atPath: nvramPath.path) {
Logger.info("Processing nvram.bin")
let nvramData = try Data(contentsOf: nvramPath)
nvramDigest = "sha256:" + nvramData.sha256String()
nvramSize = nvramData.count
try nvramData.write(to: cachedNvramPath) // Save to cache
}
if var digest = nvramDigest, let size = nvramSize { // Use 'var'
if !dryRun {
// Upload only if not in dry-run mode and blob doesn't exist
if !(try await blobExists(
repository: "\(self.organization)/\(imageName)", digest: digest, token: token))
{
Logger.info("Uploading nvram.bin blob")
let nvramData = try Data(contentsOf: cachedNvramPath) // Read from cache
digest = try await uploadBlobFromData(
repository: "\(self.organization)/\(imageName)",
data: nvramData,
token: token
)
} else {
Logger.info("NVRAM blob already exists on registry")
}
}
// Add nvram layer
layers.append(
OCIManifestLayer(
mediaType: "application/octet-stream",
size: size,
digest: digest
))
}
// Process disk.img
if FileManager.default.fileExists(atPath: diskPath.path) {
let diskAttributes = try FileManager.default.attributesOfItem(atPath: diskPath.path)
let diskSize = diskAttributes[.size] as? UInt64 ?? 0
let actualDiskSize = uncompressedDiskSize ?? diskSize
Logger.info(
"Processing disk.img in chunks",
metadata: [
"disk_path": diskPath.path, "disk_size": "\(diskSize) bytes",
"actual_size": "\(actualDiskSize) bytes", "chunk_size": "\(chunkSizeMb)MB",
])
let chunksDir = workDir.appendingPathComponent("disk.img.parts")
try FileManager.default.createDirectory(
at: chunksDir, withIntermediateDirectories: true)
let chunkSizeBytes = chunkSizeMb * 1024 * 1024
let totalChunks = Int((diskSize + UInt64(chunkSizeBytes) - 1) / UInt64(chunkSizeBytes))
Logger.info("Splitting disk into \(totalChunks) chunks")
let fileHandle = try FileHandle(forReadingFrom: diskPath)
defer { try? fileHandle.close() }
var pushedDiskLayers: [(index: Int, layer: OCIManifestLayer)] = []
var diskChunks: [(index: Int, path: URL, digest: String)] = []
try await withThrowingTaskGroup(of: (Int, OCIManifestLayer, URL, String).self) {
group in
let maxConcurrency = 4
for chunkIndex in 0..<totalChunks {
if chunkIndex >= maxConcurrency {
if let res = try await group.next() {
pushedDiskLayers.append((res.0, res.1))
diskChunks.append((res.0, res.2, res.3))
}
}
group.addTask { [token, verbose, dryRun, organization, imageName] in
let chunkIndex = chunkIndex
let chunkPath = chunksDir.appendingPathComponent("chunk.\(chunkIndex)")
let metadataPath = chunksDir.appendingPathComponent(
"chunk_metadata.\(chunkIndex).json")
var layer: OCIManifestLayer? = nil
var finalCompressedDigest: String? = nil
if FileManager.default.fileExists(atPath: metadataPath.path),
FileManager.default.fileExists(atPath: chunkPath.path)
{
do {
let metadataData = try Data(contentsOf: metadataPath)
let metadata = try JSONDecoder().decode(
ChunkMetadata.self, from: metadataData)
Logger.info(
"Resuming chunk \(chunkIndex + 1)/\(totalChunks) from cache")
finalCompressedDigest = metadata.compressedDigest
if !dryRun {
if !(try await self.blobExists(
repository: "\(organization)/\(imageName)",
digest: metadata.compressedDigest, token: token))
{
Logger.info("Uploading cached chunk \(chunkIndex + 1) blob")
_ = try await self.uploadBlobFromPath(
repository: "\(organization)/\(imageName)",
path: chunkPath, digest: metadata.compressedDigest,
token: token)
} else {
Logger.info(
"Chunk \(chunkIndex + 1) blob already exists on registry"
)
}
}
layer = OCIManifestLayer(
mediaType: "application/octet-stream+lz4",
size: metadata.compressedSize,
digest: metadata.compressedDigest,
uncompressedSize: metadata.uncompressedSize,
uncompressedContentDigest: metadata.uncompressedDigest)
} catch {
Logger.info(
"Failed to load cached metadata/chunk for index \(chunkIndex): \(error). Re-processing."
)
finalCompressedDigest = nil
layer = nil
}
}
if layer == nil {
Logger.info("Processing chunk \(chunkIndex + 1)/\(totalChunks)")
let localFileHandle = try FileHandle(forReadingFrom: diskPath)
defer { try? localFileHandle.close() }
try localFileHandle.seek(toOffset: UInt64(chunkIndex * chunkSizeBytes))
let chunkData =
try localFileHandle.read(upToCount: chunkSizeBytes) ?? Data()
let uncompressedSize = UInt64(chunkData.count)
let uncompressedDigest = "sha256:" + chunkData.sha256String()
let compressedData =
try (chunkData as NSData).compressed(using: .lz4) as Data
let compressedSize = compressedData.count
let compressedDigest = "sha256:" + compressedData.sha256String()
try compressedData.write(to: chunkPath)
let metadata = ChunkMetadata(
uncompressedDigest: uncompressedDigest,
uncompressedSize: uncompressedSize,
compressedDigest: compressedDigest, compressedSize: compressedSize)
let metadataData = try JSONEncoder().encode(metadata)
try metadataData.write(to: metadataPath)
finalCompressedDigest = compressedDigest
if !dryRun {
if !(try await self.blobExists(
repository: "\(organization)/\(imageName)",
digest: compressedDigest, token: token))
{
Logger.info("Uploading processed chunk \(chunkIndex + 1) blob")
_ = try await self.uploadBlobFromPath(
repository: "\(organization)/\(imageName)", path: chunkPath,
digest: compressedDigest, token: token)
} else {
Logger.info(
"Chunk \(chunkIndex + 1) blob already exists on registry (processed fresh)"
)
}
}
layer = OCIManifestLayer(
mediaType: "application/octet-stream+lz4", size: compressedSize,
digest: compressedDigest, uncompressedSize: uncompressedSize,
uncompressedContentDigest: uncompressedDigest)
}
guard let finalLayer = layer, let finalDigest = finalCompressedDigest else {
throw PushError.blobUploadFailed
}
if verbose {
Logger.info("Finished chunk \(chunkIndex + 1)/\(totalChunks)")
}
return (chunkIndex, finalLayer, chunkPath, finalDigest)
}
}
for try await (index, layer, path, digest) in group {
pushedDiskLayers.append((index, layer))
diskChunks.append((index, path, digest))
}
}
layers.append(
contentsOf: pushedDiskLayers.sorted { $0.index < $1.index }.map { $0.layer })
diskChunks.sort { $0.index < $1.index }
Logger.info("All disk chunks processed successfully")
// --- Calculate Total Upload Size & Initialize Tracker ---
if !dryRun {
var totalUploadSizeBytes: Int64 = 0
var totalUploadFiles: Int = 0
// Add config size if it exists
if let size = configSize {
totalUploadSizeBytes += Int64(size)
totalUploadFiles += 1
}
// Add nvram size if it exists
if let size = nvramSize {
totalUploadSizeBytes += Int64(size)
totalUploadFiles += 1
}
// Add sizes of all compressed disk chunks
let allChunkSizes = diskChunks.compactMap {
try? FileManager.default.attributesOfItem(atPath: $0.path.path)[.size] as? Int64
?? 0
}
totalUploadSizeBytes += allChunkSizes.reduce(0, +)
totalUploadFiles += totalChunks // Use totalChunks calculated earlier
if totalUploadSizeBytes > 0 {
Logger.info(
"Initializing upload progress: \(totalUploadFiles) files, total size: \(ByteCountFormatter.string(fromByteCount: totalUploadSizeBytes, countStyle: .file))"
)
await uploadProgress.setTotal(totalUploadSizeBytes, files: totalUploadFiles)
// Print initial progress bar
print(
"[░░░░░░░░░░░░░░░░░░░░] 0% (0/\(totalUploadFiles)) | Initializing upload... | ETA: calculating... "
)
fflush(stdout)
} else {
Logger.info("No files marked for upload.")
}
}
// --- End Size Calculation & Init ---
// Perform reassembly verification if requested in dry-run mode
if dryRun && reassemble {
Logger.info("=== REASSEMBLY MODE ===")
Logger.info("Reassembling chunks to verify integrity...")
let reassemblyDir = workDir.appendingPathComponent("reassembly")
try FileManager.default.createDirectory(
at: reassemblyDir, withIntermediateDirectories: true)
let reassembledFile = reassemblyDir.appendingPathComponent("reassembled_disk.img")
// Pre-allocate a sparse file with the correct size
Logger.info(
"Pre-allocating sparse file of \(ByteCountFormatter.string(fromByteCount: Int64(actualDiskSize), countStyle: .file))..."
)
if FileManager.default.fileExists(atPath: reassembledFile.path) {
try FileManager.default.removeItem(at: reassembledFile)
}
guard FileManager.default.createFile(atPath: reassembledFile.path, contents: nil)
else {
throw PushError.fileCreationFailed(reassembledFile.path)
}
let outputHandle = try FileHandle(forWritingTo: reassembledFile)
defer { try? outputHandle.close() }
// Set the file size without writing data (creates a sparse file)
try outputHandle.truncate(atOffset: actualDiskSize)
// Add test patterns at start and end to verify writability
let testPattern = "LUME_TEST_PATTERN".data(using: .utf8)!
try outputHandle.seek(toOffset: 0)
try outputHandle.write(contentsOf: testPattern)
try outputHandle.seek(toOffset: actualDiskSize - UInt64(testPattern.count))
try outputHandle.write(contentsOf: testPattern)
try outputHandle.synchronize()
Logger.info("Test patterns written to sparse file. File is ready for writing.")
// Track reassembly progress
var reassemblyProgressLogger = ProgressLogger(threshold: 0.05)
var currentOffset: UInt64 = 0
// Process each chunk in order
for (index, cachedChunkPath, _) in diskChunks.sorted(by: { $0.index < $1.index }) {
Logger.info(
"Decompressing & writing part \(index + 1)/\(diskChunks.count): \(cachedChunkPath.lastPathComponent) at offset \(currentOffset)..."
)
// Always seek to the correct position
try outputHandle.seek(toOffset: currentOffset)
// Decompress and write the chunk
let decompressedBytesWritten = try decompressChunkAndWriteSparse(
inputPath: cachedChunkPath.path,
outputHandle: outputHandle,
startOffset: currentOffset
)
currentOffset += decompressedBytesWritten
reassemblyProgressLogger.logProgress(
current: Double(currentOffset) / Double(actualDiskSize),
context: "Reassembling"
)
// Ensure data is written before processing next part
try outputHandle.synchronize()
}
// Finalize progress
reassemblyProgressLogger.logProgress(current: 1.0, context: "Reassembly Complete")
Logger.info("") // Newline
// Close handle before post-processing
try outputHandle.close()
// Optimize sparseness if on macOS
let optimizedFile = reassemblyDir.appendingPathComponent("optimized_disk.img")
if FileManager.default.fileExists(atPath: "/bin/cp") {
Logger.info("Optimizing sparse file representation...")
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
process.arguments = ["-c", reassembledFile.path, optimizedFile.path]
do {
try process.run()
process.waitUntilExit()
if process.terminationStatus == 0 {
// Get sizes of original and optimized files
let optimizedSize =
(try? FileManager.default.attributesOfItem(
atPath: optimizedFile.path)[.size] as? UInt64) ?? 0
let originalUsage = getActualDiskUsage(path: reassembledFile.path)
let optimizedUsage = getActualDiskUsage(path: optimizedFile.path)
Logger.info(
"Sparse optimization results: Before: \(ByteCountFormatter.string(fromByteCount: Int64(originalUsage), countStyle: .file)) actual usage, After: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedUsage), countStyle: .file)) actual usage (Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(optimizedSize), countStyle: .file)))"
)
// Replace original with optimized version
try FileManager.default.removeItem(at: reassembledFile)
try FileManager.default.moveItem(
at: optimizedFile, to: reassembledFile)
Logger.info("Using sparse-optimized file for verification")
} else {
Logger.info(
"Sparse optimization failed, using original file for verification")
try? FileManager.default.removeItem(at: optimizedFile)
}
} catch {
Logger.info(
"Error during sparse optimization: \(error.localizedDescription)")
try? FileManager.default.removeItem(at: optimizedFile)
}
}
// Verification step
Logger.info("Verifying reassembled file...")
let originalSize = diskSize
let originalDigest = calculateSHA256(filePath: diskPath.path)
let reassembledAttributes = try FileManager.default.attributesOfItem(
atPath: reassembledFile.path)
let reassembledSize = reassembledAttributes[.size] as? UInt64 ?? 0
let reassembledDigest = calculateSHA256(filePath: reassembledFile.path)
// Check actual disk usage
let originalActualSize = getActualDiskUsage(path: diskPath.path)
let reassembledActualSize = getActualDiskUsage(path: reassembledFile.path)
// Report results
Logger.info("Results:")
Logger.info(
" Original size: \(ByteCountFormatter.string(fromByteCount: Int64(originalSize), countStyle: .file)) (\(originalSize) bytes)"
)
Logger.info(
" Reassembled size: \(ByteCountFormatter.string(fromByteCount: Int64(reassembledSize), countStyle: .file)) (\(reassembledSize) bytes)"
)
Logger.info(" Original digest: \(originalDigest)")
Logger.info(" Reassembled digest: \(reassembledDigest)")
Logger.info(
" Original: Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(originalSize), countStyle: .file)), Actual disk usage: \(ByteCountFormatter.string(fromByteCount: Int64(originalActualSize), countStyle: .file))"
)
Logger.info(
" Reassembled: Apparent size: \(ByteCountFormatter.string(fromByteCount: Int64(reassembledSize), countStyle: .file)), Actual disk usage: \(ByteCountFormatter.string(fromByteCount: Int64(reassembledActualSize), countStyle: .file))"
)
// Determine if verification was successful
if originalDigest == reassembledDigest {
Logger.info("✅ VERIFICATION SUCCESSFUL: Files are identical")
} else {
Logger.info("❌ VERIFICATION FAILED: Files differ")
if originalSize != reassembledSize {
Logger.info(
" Size mismatch: Original \(originalSize) bytes, Reassembled \(reassembledSize) bytes"
)
}
// Check sparse file characteristics
Logger.info("Attempting to identify differences...")
Logger.info(
"NOTE: This might be a sparse file issue. The content may be identical, but sparse regions"
)
Logger.info(
" may be handled differently between the original and reassembled files."
)
if originalActualSize > 0 {
let diffPercentage =
((Double(reassembledActualSize) - Double(originalActualSize))
/ Double(originalActualSize)) * 100.0
Logger.info(
" Disk usage difference: \(String(format: "%.2f", diffPercentage))%")
if diffPercentage < -40 {
Logger.info(
" ⚠️ WARNING: Reassembled disk uses significantly less space (>40% difference)."
)
Logger.info(
" This indicates sparse regions weren't properly preserved and may affect VM functionality."
)
} else if diffPercentage < -10 {
Logger.info(
" ⚠️ WARNING: Reassembled disk uses less space (10-40% difference)."
)
Logger.info(
" Some sparse regions may not be properly preserved but VM might still function correctly."
)
} else if diffPercentage > 10 {
Logger.info(
" ⚠️ WARNING: Reassembled disk uses more space (>10% difference).")
Logger.info(
" This is unusual and may indicate improper sparse file handling.")
} else {
Logger.info(
" ✓ Disk usage difference is minimal (<10%). VM likely to function correctly."
)
}
}
// Offer recovery option
if originalDigest != reassembledDigest {
Logger.info("")
Logger.info("===== ATTEMPTING RECOVERY ACTION =====")
Logger.info(
"Since verification failed, trying direct copy as a fallback method.")
let fallbackFile = reassemblyDir.appendingPathComponent("fallback_disk.img")
Logger.info("Creating fallback disk image at: \(fallbackFile.path)")
// Try rsync first
let rsyncProcess = Process()
rsyncProcess.executableURL = URL(fileURLWithPath: "/usr/bin/rsync")
rsyncProcess.arguments = [
"-aS", "--progress", diskPath.path, fallbackFile.path,
]
do {
try rsyncProcess.run()
rsyncProcess.waitUntilExit()
if rsyncProcess.terminationStatus == 0 {
Logger.info(
"Direct copy completed with rsync. Fallback image available at: \(fallbackFile.path)"
)
} else {
// Try cp -c as fallback
Logger.info("Rsync failed. Attempting with cp -c command...")
let cpProcess = Process()
cpProcess.executableURL = URL(fileURLWithPath: "/bin/cp")
cpProcess.arguments = ["-c", diskPath.path, fallbackFile.path]
try cpProcess.run()
cpProcess.waitUntilExit()
if cpProcess.terminationStatus == 0 {
Logger.info(
"Direct copy completed with cp -c. Fallback image available at: \(fallbackFile.path)"
)
} else {
Logger.info("All recovery attempts failed.")
}
}
} catch {
Logger.info(
"Error during recovery attempts: \(error.localizedDescription)")
Logger.info("All recovery attempts failed.")
}
}
}
Logger.info("Reassembled file is available at: \(reassembledFile.path)")
}
}
// --- Manifest Creation & Push ---
let manifest = createManifest(
layers: layers,
configLayerIndex: layers.firstIndex(where: {
$0.mediaType == "application/vnd.oci.image.config.v1+json"
}),
uncompressedDiskSize: uncompressedDiskSize
)
// Push manifest only if not in dry-run mode
if !dryRun {
Logger.info("Pushing manifest(s)") // Updated log
// Serialize the manifest dictionary to Data first
let manifestData = try JSONSerialization.data(
withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys])
// Loop through tags to push the same manifest data
for tag in tags {
Logger.info("Pushing manifest for tag: \(tag)")
try await pushManifest(
repository: "\(self.organization)/\(imageName)",
tag: tag, // Use the current tag from the loop
manifest: manifestData, // Pass the serialized Data
token: token // Token should be in scope here now
)
}
}
// Print final upload summary if not dry run
if !dryRun {
let stats = await uploadProgress.getUploadStats()
Logger.info("\n\(stats.formattedSummary())") // Add newline for separation
}
// Clean up cache directory only on successful non-dry-run push
}
private func createManifest(
layers: [OCIManifestLayer], configLayerIndex: Int?, uncompressedDiskSize: UInt64?
) -> [String: Any] {
var manifest: [String: Any] = [
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"layers": layers.map { layer in
var layerDict: [String: Any] = [
"mediaType": layer.mediaType,
"size": layer.size,
"digest": layer.digest,
]
if let uncompressedSize = layer.uncompressedSize {
var annotations: [String: String] = [:]
annotations["org.trycua.lume.uncompressed-size"] = "\(uncompressedSize)" // Updated prefix
if let digest = layer.uncompressedContentDigest {
annotations["org.trycua.lume.uncompressed-content-digest"] = digest // Updated prefix
}
layerDict["annotations"] = annotations
}
return layerDict
},
]
// Add config reference if available
if let configIndex = configLayerIndex {
let configLayer = layers[configIndex]
manifest["config"] = [
"mediaType": configLayer.mediaType,
"size": configLayer.size,
"digest": configLayer.digest,
]
}
// Add annotations
var annotations: [String: String] = [:]
annotations["org.trycua.lume.upload-time"] = ISO8601DateFormatter().string(from: Date()) // Updated prefix
if let diskSize = uncompressedDiskSize {
annotations["org.trycua.lume.uncompressed-disk-size"] = "\(diskSize)" // Updated prefix
}
manifest["annotations"] = annotations
return manifest
}
private func uploadBlobFromData(repository: String, data: Data, token: String) async throws
-> String
{
// Calculate digest
let digest = "sha256:" + data.sha256String()
// Check if blob already exists
if try await blobExists(repository: repository, digest: digest, token: token) {
Logger.debug("Blob already exists: \(digest)")
return digest
}
// Initiate upload
let uploadURL = try await startBlobUpload(repository: repository, token: token)
// Upload blob
try await uploadBlob(url: uploadURL, data: data, digest: digest, token: token)
// Report progress
await uploadProgress.addProgress(Int64(data.count))
return digest
}
private func uploadBlobFromPath(
repository: String, path: URL, digest: String, token: String,
onProgress: (@Sendable (Int64, Int64) -> Void)? = nil
) async throws -> String {
// Check if blob already exists
if try await blobExists(repository: repository, digest: digest, token: token) {
Logger.debug("Blob already exists: \(digest)")
return digest
}
// Initiate upload
let uploadURL = try await startBlobUpload(repository: repository, token: token)
// Upload blob from file with progress tracking
try await uploadBlobFromFile(
url: uploadURL, filePath: path, digest: digest, token: token,
onProgress: onProgress)
// Report progress to legacy tracker
let attrs = try FileManager.default.attributesOfItem(atPath: path.path)
let size = attrs[.size] as? Int64 ?? 0
await uploadProgress.addProgress(size)
return digest
}
private func blobExists(repository: String, digest: String, token: String) async throws -> Bool
{
let url = URL(string: "https://\(registry)/v2/\(repository)/blobs/\(digest)")!
var request = URLRequest(url: url)
request.httpMethod = "HEAD"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let (_, response) = try await URLSession.shared.data(for: request)
if let httpResponse = response as? HTTPURLResponse {
return httpResponse.statusCode == 200
}
return false
}
private func startBlobUpload(repository: String, token: String) async throws -> URL {
let url = URL(string: "https://\(registry)/v2/\(repository)/blobs/uploads/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("0", forHTTPHeaderField: "Content-Length") // Explicitly set Content-Length to 0 for POST
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 202,
let locationString = httpResponse.value(forHTTPHeaderField: "Location")
else {
// Log response details on failure
let responseBody =
String(
data: (try? await URLSession.shared.data(for: request).0) ?? Data(),
encoding: .utf8) ?? "(No Body)"
Logger.error(
"Failed to initiate blob upload. Status: \( (response as? HTTPURLResponse)?.statusCode ?? 0 ). Headers: \( (response as? HTTPURLResponse)?.allHeaderFields ?? [:] ). Body: \(responseBody)"
)
throw PushError.uploadInitiationFailed
}
// Construct the base URL for the registry
guard let baseRegistryURL = URL(string: "https://\(registry)") else {
Logger.error("Failed to create base registry URL from: \(registry)")
throw PushError.invalidURL
}
// Create the final upload URL, resolving the location against the base URL
guard let uploadURL = URL(string: locationString, relativeTo: baseRegistryURL) else {
Logger.error(
"Failed to create absolute upload URL from location: \(locationString) relative to base: \(baseRegistryURL.absoluteString)"
)
throw PushError.invalidURL
}
Logger.debug("Blob upload initiated. Upload URL: \(uploadURL.absoluteString)")
return uploadURL.absoluteURL // Ensure it's absolute
}
/// Upload a blob from a file path with real byte-level progress tracking.
private func uploadBlobFromFile(
url: URL, filePath: URL, digest: String, token: String,
onProgress: (@Sendable (Int64, Int64) -> Void)? = nil
) async throws {
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
var queryItems = components.queryItems ?? []
queryItems.append(URLQueryItem(name: "digest", value: digest))
components.queryItems = queryItems
guard let uploadURL = components.url else {
throw PushError.invalidURL
}
let attrs = try FileManager.default.attributesOfItem(atPath: filePath.path)
let fileSize = attrs[.size] as? Int64 ?? 0
var request = URLRequest(url: uploadURL)
request.httpMethod = "PUT"
request.timeoutInterval = 3600
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.setValue("\(fileSize)", forHTTPHeaderField: "Content-Length")
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 3600
config.timeoutIntervalForResource = 7200
let delegate = UploadProgressDelegate(
totalBytes: fileSize, onProgress: onProgress)
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)
let (_, response) = try await session.upload(for: request, fromFile: filePath)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 201 else {
throw PushError.blobUploadFailed
}
}
private func uploadBlob(url: URL, data: Data, digest: String, token: String) async throws {
var components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
// Add digest parameter
var queryItems = components.queryItems ?? []
queryItems.append(URLQueryItem(name: "digest", value: digest))
components.queryItems = queryItems
guard let uploadURL = components.url else {
throw PushError.invalidURL
}
var request = URLRequest(url: uploadURL)
request.httpMethod = "PUT"
request.timeoutInterval = 3600 // 1 hour for large blob uploads
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
request.setValue("\(data.count)", forHTTPHeaderField: "Content-Length")
request.httpBody = data
let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 3600
config.timeoutIntervalForResource = 7200
let session = URLSession(configuration: config)
let (_, response) = try await session.data(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 201 else {
throw PushError.blobUploadFailed
}
}
private func pushManifest(repository: String, tag: String, manifest: Data, token: String)
async throws
{
let url = URL(string: "https://\(registry)/v2/\(repository)/manifests/\(tag)")!
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
request.setValue(
"application/vnd.oci.image.manifest.v1+json", forHTTPHeaderField: "Content-Type")
request.httpBody = manifest
let (_, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 201 else {
throw PushError.manifestPushFailed
}
}
private func getCredentialsFromEnvironment() -> (String?, String?) {
// Prefer explicit credentials over environment variables
if let username = self.username, let password = self.password,
!username.isEmpty, !password.isEmpty {
return (username, password)
}
let username =
ProcessInfo.processInfo.environment["GITHUB_USERNAME"]
?? ProcessInfo.processInfo.environment["GHCR_USERNAME"]
let password =
ProcessInfo.processInfo.environment["GITHUB_TOKEN"]
?? ProcessInfo.processInfo.environment["GHCR_TOKEN"]
return (username, password)
}
// Add these helper methods for dry-run and reassemble implementation
// NEW Helper function using Compression framework and sparse writing
private func decompressChunkAndWriteSparse(
inputPath: String, outputHandle: FileHandle, startOffset: UInt64
) throws -> UInt64 {
guard FileManager.default.fileExists(atPath: inputPath) else {
throw PullError.layerDownloadFailed(
URL(fileURLWithPath: inputPath).lastPathComponent)
}
let sourceData = try Data(
contentsOf: URL(fileURLWithPath: inputPath), options: .alwaysMapped)
var currentWriteOffset = startOffset
var totalDecompressedBytes: UInt64 = 0
var sourceReadOffset = 0 // Keep track of how much compressed data we've provided
// Use the initializer with the readingFrom closure
let filter = try InputFilter(.decompress, using: .lz4) { (length: Int) -> Data? in
let bytesAvailable = sourceData.count - sourceReadOffset
if bytesAvailable == 0 {
return nil // No more data
}
let bytesToRead = min(length, bytesAvailable)
let chunk = sourceData.subdata(in: sourceReadOffset..<sourceReadOffset + bytesToRead)
sourceReadOffset += bytesToRead
return chunk
}
// Process the decompressed output by reading from the filter
while let decompressedData = try filter.readData(ofLength: Self.holeGranularityBytes) {
if Task.isCancelled { throw CancellationError() }
if decompressedData.isEmpty { break } // End of stream
// Check if the chunk is all zeros
if decompressedData.count == Self.holeGranularityBytes
&& decompressedData == Self.zeroChunk
{
// It's a zero chunk, just advance the offset, don't write
currentWriteOffset += UInt64(decompressedData.count)
} else {
// Not a zero chunk (or a partial chunk at the end), write it
try outputHandle.seek(toOffset: currentWriteOffset)
try outputHandle.write(contentsOf: decompressedData)
currentWriteOffset += UInt64(decompressedData.count)
}
totalDecompressedBytes += UInt64(decompressedData.count)
}
// No explicit finalize needed when initialized with source data
return totalDecompressedBytes
}
// Helper function to calculate SHA256 hash of a file
private func calculateSHA256(filePath: String) -> String {
guard FileManager.default.fileExists(atPath: filePath) else {
return "file-not-found"
}
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/shasum")
process.arguments = ["-a", "256", filePath]
let outputPipe = Pipe()
process.standardOutput = outputPipe
do {
try process.run()
process.waitUntilExit()
if let data = try outputPipe.fileHandleForReading.readToEnd(),
let output = String(data: data, encoding: .utf8)
{
return output.components(separatedBy: " ").first ?? "hash-calculation-failed"
}
} catch {
Logger.error("SHA256 calculation failed: \(error)")
}
return "hash-calculation-failed"
}
// MARK: - OCI-Compliant Format Support
/// Gzip-compress a file using in-process zlib (streaming, sparse-aware).
/// Computes SHA256 digests for both uncompressed and compressed data in a single pass.
private func gzipFile(
inputPath: URL, outputPath: URL,
onProgress: ((_ bytesRead: UInt64, _ totalBytes: UInt64) -> Void)? = nil
) throws -> (
compressedDigest: String, compressedSize: Int,
uncompressedDigest: String, uncompressedSize: UInt64
) {
let inputHandle = try FileHandle(forReadingFrom: inputPath)
defer { try? inputHandle.close() }
let uncompressedAttrs = try FileManager.default.attributesOfItem(atPath: inputPath.path)
let uncompressedSize = uncompressedAttrs[.size] as? UInt64 ?? 0
FileManager.default.createFile(atPath: outputPath.path, contents: nil)
let outputHandle = try FileHandle(forWritingTo: outputPath)
defer { try? outputHandle.close() }
// Initialize zlib with gzip format (windowBits = MAX_WBITS + 16 = 31)
var stream = CZlib.z_stream()
let initResult = CZlib.deflateInit2_(
&stream,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
MAX_WBITS + 16, // gzip header/trailer
MAX_MEM_LEVEL,
Z_DEFAULT_STRATEGY,
ZLIB_VERSION,
Int32(MemoryLayout<CZlib.z_stream>.size)
)
guard initResult == Z_OK else {
throw PushError.blobUploadFailed
}
defer { CZlib.deflateEnd(&stream) }
// SHA256 contexts for both uncompressed and compressed data
var uncompCtx = CC_SHA256_CTX()
CC_SHA256_Init(&uncompCtx)
var compCtx = CC_SHA256_CTX()
CC_SHA256_Init(&compCtx)
let readSize = 4 * 1024 * 1024 // 4MB blocks (matches sparse granularity)
let outputBufSize = readSize + 1024
let outputBuf = UnsafeMutablePointer<UInt8>.allocate(capacity: outputBufSize)
defer { outputBuf.deallocate() }
var totalCompressed: Int = 0
var totalRead: UInt64 = 0
while true {
let inputData = inputHandle.readData(ofLength: readSize)
let isLast = inputData.count < readSize
totalRead += UInt64(inputData.count)
onProgress?(totalRead, uncompressedSize)
// Update uncompressed digest
inputData.withUnsafeBytes { ptr in
if let base = ptr.baseAddress {
CC_SHA256_Update(&uncompCtx, base, CC_LONG(inputData.count))
}
}
// Compress
try inputData.withUnsafeBytes { inputPtr in
stream.next_in = UnsafeMutablePointer<UInt8>(
mutating: inputPtr.baseAddress?.assumingMemoryBound(to: UInt8.self))
stream.avail_in = UInt32(inputData.count)
repeat {
stream.next_out = outputBuf
stream.avail_out = UInt32(outputBufSize)
let status = CZlib.deflate(&stream, isLast ? Z_FINISH : Z_NO_FLUSH)
guard status == Z_OK || status == Z_BUF_ERROR || status == Z_STREAM_END else {
throw PushError.blobUploadFailed
}
let produced = outputBufSize - Int(stream.avail_out)
if produced > 0 {
CC_SHA256_Update(&compCtx, outputBuf, CC_LONG(produced))
try outputHandle.write(contentsOf: Data(
bytesNoCopy: outputBuf, count: produced, deallocator: .none))
totalCompressed += produced
}
} while stream.avail_out == 0
}
if isLast { break }
}
// Finalize digests
var uncompHash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256_Final(&uncompHash, &uncompCtx)
let uncompressedDigest = "sha256:" + uncompHash.map { String(format: "%02x", $0) }.joined()
var compHash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256_Final(&compHash, &compCtx)
let compressedDigest = "sha256:" + compHash.map { String(format: "%02x", $0) }.joined()
return (compressedDigest, totalCompressed, uncompressedDigest, uncompressedSize)
}
/// Gunzip a file to an output path.
private func gunzipFile(inputPath: URL, outputPath: URL) throws {
FileManager.default.createFile(atPath: outputPath.path, contents: nil)
let outputHandle = try FileHandle(forWritingTo: outputPath)
let process = Process()
process.executableURL = URL(fileURLWithPath: "/usr/bin/gunzip")
process.arguments = ["-c", inputPath.path]
process.standardOutput = outputHandle
try process.run()
process.waitUntilExit()
try outputHandle.close()
guard process.terminationStatus == 0 else {
throw PullError.layerDownloadFailed(inputPath.lastPathComponent)
}
}
/// Build the OCI config JSON blob from a VMConfig.
private func createOCIConfigData(_ vmConfig: VMConfig) throws -> Data {
let hardwareModel = vmConfig.hardwareModel?.base64EncodedString() ?? ""
let machineIdentifier = vmConfig.machineIdentifier?.base64EncodedString() ?? ""
let configObj: [String: Any] = [
"mediatype": OCIMediaType.config,
"os": vmConfig.os,
"hardwareModel": hardwareModel,
"machineIdentifier": machineIdentifier,
"storage": [
["mediatype": OCIMediaType.nvram, "file": "nvram.bin"],
["mediatype": OCIMediaType.disk, "file": "disk.img"],
],
]
return try JSONSerialization.data(
withJSONObject: configObj, options: [.prettyPrinted, .sortedKeys])
}
/// Build an OCI manifest dictionary.
private func createOCIManifest(
configDigest: String, configSize: Int,
nvramDigest: String, nvramSize: Int,
diskDigest: String, diskSize: Int,
uncompressedDiskDigest: String, uncompressedDiskSize: UInt64,
vmConfig: VMConfig?
) -> [String: Any] {
// Config entry (in manifest's "config" field)
let configEntry: [String: Any] = [
"mediaType": OCIMediaType.config,
"digest": configDigest,
"size": configSize,
"annotations": ["org.opencontainers.image.title": "config.json"],
]
// NVRAM layer — stored uncompressed, title annotation only
let nvramLayer: [String: Any] = [
"mediaType": OCIMediaType.nvram,
"digest": nvramDigest,
"size": nvramSize,
"annotations": ["org.opencontainers.image.title": "nvram.bin"],
]
// Disk layer — gzip-compressed with size/digest annotations
let diskLayer: [String: Any] = [
"mediaType": OCIMediaType.disk,
"digest": diskDigest,
"size": diskSize,
"annotations": [
"org.opencontainers.image.title": "disk.img",
"org.trycua.lume.content.uncompressed-size": "\(uncompressedDiskSize)",
"org.trycua.lume.content.uncompressed-digest": uncompressedDiskDigest,
],
]
// Manifest-level annotations (preserve Lume config for round-trip pulls)
var manifestAnnotations: [String: String] = [
"org.trycua.lume.upload-time": ISO8601DateFormatter().string(from: Date()),
]
if let cfg = vmConfig {
manifestAnnotations["org.trycua.lume.os"] = cfg.os
if let v = cfg.cpuCount { manifestAnnotations["org.trycua.lume.cpu-count"] = "\(v)" }
if let v = cfg.memorySize { manifestAnnotations["org.trycua.lume.memory-size"] = "\(v)" }
if let v = cfg.diskSize { manifestAnnotations["org.trycua.lume.disk-size"] = "\(v)" }
manifestAnnotations["org.trycua.lume.display"] = cfg.display.string
manifestAnnotations["org.trycua.lume.network-mode"] = cfg.networkMode.description
}
return [
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": configEntry,
"layers": [nvramLayer, diskLayer],
"annotations": manifestAnnotations,
]
}
/// Build an OCI manifest with multiple disk chunk layers.
private func createOCIManifest(
configDigest: String, configSize: Int,
nvramDigest: String, nvramSize: Int,
diskChunks: [DiskChunkDescriptor],
totalUncompressedSize: UInt64,
vmConfig: VMConfig?
) -> [String: Any] {
let configEntry: [String: Any] = [
"mediaType": OCIMediaType.config,
"digest": configDigest,
"size": configSize,
"annotations": ["org.opencontainers.image.title": "config.json"],
]
let nvramLayer: [String: Any] = [
"mediaType": OCIMediaType.nvram,
"digest": nvramDigest,
"size": nvramSize,
"annotations": ["org.opencontainers.image.title": "nvram.bin"],
]
let totalParts = diskChunks.count
let diskChunkLayers: [[String: Any]] = diskChunks.sorted { $0.partNumber < $1.partNumber }
.map { chunk in
[
"mediaType": OCIMediaType.disk,
"digest": chunk.compressedDigest,
"size": chunk.compressedSize,
"annotations": [
"org.opencontainers.image.title": "disk.img.part.\(chunk.partNumber)",
"org.trycua.lume.content.uncompressed-size": "\(chunk.uncompressedSize)",
"org.trycua.lume.content.uncompressed-digest": chunk.uncompressedDigest,
OCIAnnotation.partNumber: "\(chunk.partNumber)",
OCIAnnotation.partTotal: "\(totalParts)",
OCIAnnotation.partOffset: "\(chunk.diskOffset)",
OCIAnnotation.chunkSize: "\(chunk.uncompressedSize)",
],
]
}
var manifestAnnotations: [String: String] = [
"org.trycua.lume.upload-time": ISO8601DateFormatter().string(from: Date()),
"org.trycua.lume.total-uncompressed-size": "\(totalUncompressedSize)",
]
if let cfg = vmConfig {
manifestAnnotations["org.trycua.lume.os"] = cfg.os
if let v = cfg.cpuCount { manifestAnnotations["org.trycua.lume.cpu-count"] = "\(v)" }
if let v = cfg.memorySize { manifestAnnotations["org.trycua.lume.memory-size"] = "\(v)" }
if let v = cfg.diskSize { manifestAnnotations["org.trycua.lume.disk-size"] = "\(v)" }
manifestAnnotations["org.trycua.lume.display"] = cfg.display.string
manifestAnnotations["org.trycua.lume.network-mode"] = cfg.networkMode.description
}
return [
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": configEntry,
"layers": [nvramLayer] + diskChunkLayers,
"annotations": manifestAnnotations,
]
}
/// Push a VM in OCI-compliant format (kubelet-compatible).
private func pushOCI(
vmDirPath: String,
imageName: String,
tags: [String],
chunkSizeMb: Int = 512,
singleLayer: Bool = false,
verbose: Bool,
dryRun: Bool
) async throws {
let chunkSize = UInt64(chunkSizeMb) * 1024 * 1024
Logger.debug(
"Pushing VM in OCI-compliant format\(singleLayer ? " (single-layer)" : " (chunked)")",
metadata: [
"vm_path": vmDirPath,
"imageName": imageName,
"tags": tags.joined(separator: ", "),
"chunk_size": "\(chunkSizeMb)MB",
"single_layer": "\(singleLayer)",
"dry_run": "\(dryRun)",
])
if !dryRun {
let (username, token) = getCredentialsFromEnvironment()
guard username != nil, token != nil else {
Logger.error(
"Missing GitHub credentials. Set GITHUB_USERNAME and GITHUB_TOKEN env vars.")
throw PushError.authenticationFailed
}
}
var token = ""
if !dryRun {
Logger.debug("Getting registry authentication token")
token = try await getToken(
repository: "\(self.organization)/\(imageName)",
scopes: ["pull", "push"],
requireAllScopes: true)
}
let vmDirURL = URL(fileURLWithPath: vmDirPath)
let diskPath = vmDirURL.appendingPathComponent("disk.img")
let nvramPath = vmDirURL.appendingPathComponent("nvram.bin")
let configPath = vmDirURL.appendingPathComponent("config.json")
let workDir = vmDirURL.appendingPathComponent(".lume_oci_push_cache")
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
let repository = "\(self.organization)/\(imageName)"
// ── Config ──────────────────────────────────────────────────────────
let vmConfig = try? JSONDecoder().decode(VMConfig.self, from: Data(contentsOf: configPath))
let fallbackConfig = try VMConfig(os: "darwin", display: "1920x1080")
let configData = try createOCIConfigData(vmConfig ?? fallbackConfig)
let configDigest = "sha256:" + configData.sha256String()
let configSize = configData.count
if !dryRun {
if !(try await blobExists(repository: repository, digest: configDigest, token: token)) {
Logger.debug("Uploading OCI config blob")
_ = try await uploadBlobFromData(
repository: repository, data: configData, token: token)
} else {
Logger.debug("OCI config blob already exists")
}
}
// ── NVRAM ────────────────────────────────────────────────────────────
guard FileManager.default.fileExists(atPath: nvramPath.path) else {
throw PushError.fileCreationFailed(nvramPath.path)
}
let nvramData = try Data(contentsOf: nvramPath)
let nvramDigest = "sha256:" + nvramData.sha256String()
let nvramSize = nvramData.count
if !dryRun {
if !(try await blobExists(repository: repository, digest: nvramDigest, token: token)) {
Logger.debug("Uploading nvram blob")
_ = try await uploadBlobFromData(
repository: repository, data: nvramData, token: token)
} else {
Logger.debug("NVRAM blob already exists")
}
}
// ── Disk ─────────────────────────────────────────────────────────────
guard FileManager.default.fileExists(atPath: diskPath.path) else {
throw PushError.fileCreationFailed(diskPath.path)
}
let diskAttrs = try FileManager.default.attributesOfItem(atPath: diskPath.path)
let diskSize = diskAttrs[.size] as? UInt64 ?? 0
let manifest: [String: Any]
if singleLayer {
// ── Single-layer mode (kubelet-compatible, no chunking) ──────────
Logger.debug("Disk size: \(diskSize) bytes, compressing as single layer")
let singleProgress = LayerProgressDisplay()
await singleProgress.setTotalUncompressed(Int64(diskSize))
await singleProgress.addLayer(id: "config", label: "config.json", totalBytes: Int64(configSize))
await singleProgress.markDone(id: "config")
await singleProgress.addLayer(id: "nvram", label: "nvram.bin", totalBytes: Int64(nvramSize))
await singleProgress.markDone(id: "nvram")
await singleProgress.addLayer(id: "disk", label: "disk.img", totalBytes: Int64(diskSize))
await singleProgress.updateStatus(id: "disk", status: .compressing)
let gzDiskPath = workDir.appendingPathComponent("disk.img.gz")
let (compDigest, compSize, uncompDigest, uncompSize) =
try gzipFile(inputPath: diskPath, outputPath: gzDiskPath) { bytesRead, totalBytes in
Task {
await singleProgress.reportCompressBytes(id: "disk", Int64(bytesRead))
await singleProgress.updateProgress(
id: "disk", completedBytes: Int64(bytesRead),
totalBytes: Int64(totalBytes))
}
}
if !dryRun {
if !(try await blobExists(repository: repository, digest: compDigest, token: token)) {
await singleProgress.registerUploadWork(compressedBytes: Int64(compSize), uncompressedBytes: Int64(uncompSize))
await singleProgress.updateStatus(id: "disk", status: .pushing)
await singleProgress.updateProgress(
id: "disk", completedBytes: 0, totalBytes: Int64(compSize))
_ = try await uploadBlobFromPath(
repository: repository,
path: gzDiskPath,
digest: compDigest,
token: token,
onProgress: { sent, total in
Task {
await singleProgress.reportUploadBytes(id: "disk", sent)
await singleProgress.updateProgress(
id: "disk", completedBytes: sent, totalBytes: total)
}
})
await singleProgress.reportUploadDone(Int64(compSize))
await singleProgress.markDone(id: "disk", bytes: Int64(compSize))
} else {
await singleProgress.markExists(id: "disk")
}
} else {
await singleProgress.markDone(id: "disk", bytes: Int64(compSize))
}
await singleProgress.finish()
try? FileManager.default.removeItem(at: gzDiskPath)
manifest = createOCIManifest(
configDigest: configDigest, configSize: configSize,
nvramDigest: nvramDigest, nvramSize: nvramSize,
diskDigest: compDigest, diskSize: compSize,
uncompressedDiskDigest: uncompDigest, uncompressedDiskSize: uncompSize,
vmConfig: vmConfig
)
} else {
// ── Chunked mode (default, parallel) ─────────────────────────────
let chunkCount = Int((diskSize + chunkSize - 1) / chunkSize)
Logger.debug("Disk size: \(diskSize) bytes, splitting into \(chunkCount) chunks of \(chunkSizeMb) MB")
let progress = LayerProgressDisplay()
await progress.setTotalUncompressed(Int64(diskSize))
await progress.addLayer(id: "config", label: "config.json", totalBytes: Int64(configSize))
await progress.markDone(id: "config")
await progress.addLayer(id: "nvram", label: "nvram.bin", totalBytes: Int64(nvramSize))
await progress.markDone(id: "nvram")
for i in 0..<chunkCount {
let estSize = Int64(min(chunkSize, diskSize - UInt64(i) * chunkSize))
await progress.addLayer(
id: "chunk-\(i)", label: "disk layer \(i + 1)/\(chunkCount)",
totalBytes: estSize)
}
let chunkCollector = ChunkCollector(count: chunkCount)
// Track seen digests for deduplication (content-addressable)
let seenDigests = DigestTracker()
// Compressed chunk ready for upload
struct CompressedChunk: Sendable {
let partNumber: Int
let chunkId: String
let gzPath: URL
let compDigest: String
let compSize: Int
let uncompDigest: String
let uncompSize: UInt64
let diskOffset: UInt64
let isDuplicate: Bool
}
let maxCompressWorkers = 4
let maxUploadWorkers = 4
let capturedToken = token
// Channel connecting compress workers → upload workers
let (uploadStream, uploadContinuation) = AsyncStream<CompressedChunk>.makeStream(
bufferingPolicy: .unbounded)
// ── Run compress + upload pipelines concurrently ──
try await withThrowingTaskGroup(of: Void.self) { pipeline in
// ── Compression pipeline: N parallel workers ──
pipeline.addTask { [self] in
try await withThrowingTaskGroup(
of: CompressedChunk.self
) { compressGroup in
var enqueued = 0
for partNumber in 0..<chunkCount {
// Throttle compress workers
if enqueued >= maxCompressWorkers {
if let result = try await compressGroup.next() {
uploadContinuation.yield(result)
}
}
let offset = UInt64(partNumber) * chunkSize
let thisChunkSize = min(chunkSize, diskSize - offset)
let chunkId = "chunk-\(partNumber)"
compressGroup.addTask { [self] in
await progress.updateStatus(id: chunkId, status: .compressing)
let handle = try FileHandle(forReadingFrom: diskPath)
try handle.seek(toOffset: offset)
let chunkData = handle.readData(ofLength: Int(thisChunkSize))
try handle.close()
let chunkPath = workDir.appendingPathComponent(
"disk.img.part.\(partNumber)")
let gzChunkPath = workDir.appendingPathComponent(
"disk.img.part.\(partNumber).gz")
try chunkData.write(to: chunkPath)
let (compDigest, compSize, uncompDigest, uncompSize) =
try self.gzipFile(
inputPath: chunkPath, outputPath: gzChunkPath
) { bytesRead, totalBytes in
Task {
await progress.reportCompressBytes(
id: chunkId, Int64(bytesRead))
await progress.updateProgress(
id: chunkId, completedBytes: Int64(bytesRead),
totalBytes: Int64(totalBytes))
}
}
try? FileManager.default.removeItem(at: chunkPath)
let isDuplicate = await seenDigests.markSeen(digest: compDigest)
await progress.setDigest(id: chunkId, digest: compDigest)
if isDuplicate {
await progress.registerSkipped(compressedBytes: Int64(compSize), uncompressedBytes: Int64(thisChunkSize))
await progress.markExists(id: chunkId)
} else {
await progress.updateStatus(
id: chunkId, status: .waitingUpload)
}
return CompressedChunk(
partNumber: partNumber,
chunkId: chunkId,
gzPath: gzChunkPath,
compDigest: compDigest,
compSize: compSize,
uncompDigest: uncompDigest,
uncompSize: uncompSize,
diskOffset: offset,
isDuplicate: isDuplicate
)
}
enqueued += 1
}
// Drain remaining compress results
for try await result in compressGroup {
uploadContinuation.yield(result)
}
}
// Signal no more chunks to upload
uploadContinuation.finish()
}
// ── Upload pipeline: N parallel workers consuming from queue ──
pipeline.addTask { [self] in
try await withThrowingTaskGroup(
of: (Int, DiskChunkDescriptor).self
) { uploadGroup in
var enqueued = 0
for await chunk in uploadStream {
let desc = DiskChunkDescriptor(
partNumber: chunk.partNumber,
compressedDigest: chunk.compDigest,
compressedSize: chunk.compSize,
uncompressedDigest: chunk.uncompDigest,
uncompressedSize: chunk.uncompSize,
diskOffset: chunk.diskOffset
)
// Duplicate or dry-run: no upload needed
if chunk.isDuplicate || dryRun {
if !chunk.isDuplicate {
await progress.markDone(
id: chunk.chunkId, bytes: Int64(chunk.compSize))
}
try? FileManager.default.removeItem(at: chunk.gzPath)
await chunkCollector.set(index: chunk.partNumber, desc: desc)
continue
}
// Throttle upload workers
if enqueued >= maxUploadWorkers {
if let (idx, d) = try await uploadGroup.next() {
await chunkCollector.set(index: idx, desc: d)
}
}
let chunkCopy = chunk
uploadGroup.addTask { [self] in
let token = capturedToken
if !(try await self.blobExists(
repository: repository, digest: chunkCopy.compDigest,
token: token))
{
await progress.registerUploadWork(compressedBytes: Int64(chunkCopy.compSize), uncompressedBytes: Int64(chunkCopy.uncompSize))
await progress.updateStatus(
id: chunkCopy.chunkId, status: .pushing)
await progress.updateProgress(
id: chunkCopy.chunkId, completedBytes: 0,
totalBytes: Int64(chunkCopy.compSize))
_ = try await self.uploadBlobFromPath(
repository: repository,
path: chunkCopy.gzPath,
digest: chunkCopy.compDigest,
token: token,
onProgress: { sent, total in
Task {
await progress.reportUploadBytes(
id: chunkCopy.chunkId, sent)
await progress.updateProgress(
id: chunkCopy.chunkId, completedBytes: sent,
totalBytes: total)
}
})
await progress.reportUploadDone(Int64(chunkCopy.compSize))
await progress.markDone(
id: chunkCopy.chunkId, bytes: Int64(chunkCopy.compSize))
} else {
await progress.registerSkipped(compressedBytes: Int64(chunkCopy.compSize), uncompressedBytes: Int64(chunkCopy.uncompSize))
await progress.markExists(id: chunkCopy.chunkId)
}
try? FileManager.default.removeItem(at: chunkCopy.gzPath)
return (
chunkCopy.partNumber,
DiskChunkDescriptor(
partNumber: chunkCopy.partNumber,
compressedDigest: chunkCopy.compDigest,
compressedSize: chunkCopy.compSize,
uncompressedDigest: chunkCopy.uncompDigest,
uncompressedSize: chunkCopy.uncompSize,
diskOffset: chunkCopy.diskOffset
)
)
}
enqueued += 1
}
// Drain remaining uploads
for try await (idx, desc) in uploadGroup {
await chunkCollector.set(index: idx, desc: desc)
}
}
}
}
await progress.finish()
// Never publish a manifest that leaves part of the disk out.
let diskChunks = await chunkCollector.getAll()
if let gap = diskChunkCoverageGap(
diskChunks.map { (offset: $0.diskOffset, size: $0.uncompressedSize) }, total: diskSize)
{
let have = Swift.Set(diskChunks.map(\.partNumber))
let missing = (0..<chunkCount).first { !have.contains($0) } ?? 0
Logger.error(
"Disk chunks do not cover the disk; not pushing the manifest",
metadata: ["gap": gap, "chunks": "\(diskChunks.count)/\(chunkCount)"])
throw PushError.missingPart(missing)
}
manifest = createOCIManifest(
configDigest: configDigest, configSize: configSize,
nvramDigest: nvramDigest, nvramSize: nvramSize,
diskChunks: diskChunks,
totalUncompressedSize: diskSize,
vmConfig: vmConfig
)
}
// ── Push manifest ────────────────────────────────────────────────────
if !dryRun {
let manifestData = try JSONSerialization.data(
withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys])
for tag in tags {
Logger.info("Pushing OCI manifest for tag: \(tag)")
try await pushManifest(
repository: repository, tag: tag, manifest: manifestData, token: token)
}
Logger.info("OCI push complete\(singleLayer ? " (single layer)" : "")")
} else {
Logger.info("Dry-run complete — manifest not uploaded")
}
}
private func downloadOCIChunkGroup(
_ chunkGroup: OCIChunkGroup,
repository: String,
token: String,
manifestId: String,
tempDir: URL,
pullProgress: LayerProgressDisplay
) async throws -> (String, URL) {
for reference in chunkGroup.references {
await pullProgress.updateStatus(
id: "chunk-\(reference.index)", status: .downloading)
}
let chunk = chunkGroup.layer
let cachedChunkPath = cachingEnabled
? getCachedLayerPath(manifestId: manifestId, digest: chunk.digest)
: nil
let blobDest = tempDir.appendingPathComponent(
chunk.digest.replacingOccurrences(of: ":", with: "_") + ".gz")
if let cached = cachedChunkPath,
FileManager.default.fileExists(atPath: cached.path)
{
Logger.info(
"Chunk found in cache, skipping download (\(chunk.digest.prefix(19))…)"
)
await downloadProgress.addProgress(Int64(chunk.size))
// Each pull gets its own path so the sibling `.raw` file created by
// sparse decompression cannot race with another Lume process.
try FileManager.default.copyItem(at: cached, to: blobDest)
} else {
let referenceIds = chunkGroup.references.map { "chunk-\($0.index)" }
try await downloadLayer(
repository: repository,
digest: chunk.digest,
mediaType: chunk.mediaType,
token: token,
to: blobDest,
maxRetries: 5,
progress: downloadProgress,
onBytes: { bytes in
Task {
for id in referenceIds {
await pullProgress.updateProgress(id: id, completedBytes: bytes)
}
}
}
)
if let cached = cachedChunkPath {
try? storeVerifiedLayer(from: blobDest, inCacheAt: cached)
}
}
return (chunk.digest, blobDest)
}
/// Pull an OCI-compliant image (kubelet format) into `destination` as a Lume VM directory.
/// Refuses a chunked manifest whose disk layers leave part of the disk
/// out: reassembling it would leave those ranges zero (a corrupt guest).
/// Manifests without offset annotations (older pushes) are not checked.
static func checkDiskCoverage(_ manifest: Manifest) throws {
let diskLayers = manifest.layers.filter { $0.mediaType == OCIMediaType.disk }
guard diskLayers.contains(where: { $0.annotations?[OCIAnnotation.partNumber] != nil }),
let totalStr = manifest.annotations?["org.trycua.lume.total-uncompressed-size"],
let total = UInt64(totalStr)
else { return }
let spans: [(offset: UInt64, size: UInt64)] = diskLayers.compactMap { layer in
guard let offset = layer.annotations?[OCIAnnotation.partOffset].flatMap(UInt64.init),
let size = layer.annotations?["org.trycua.lume.content.uncompressed-size"]
.flatMap(UInt64.init)
else { return nil }
return (offset: offset, size: size)
}
guard spans.count == diskLayers.count, let gap = diskChunkCoverageGap(spans, total: total)
else { return }
throw PullError.reassemblyFailed(
"the image is incomplete (\(gap)); it was published with missing disk layers, "
+ "so pull a different tag or ask its publisher to push it again")
}
private func pullOCI(
manifest: Manifest,
manifestId: String,
imageName: String,
repository: String,
token: String,
to destination: URL
) async throws {
try Self.checkDiskCoverage(manifest)
Logger.info("Downloading OCI-compliant layers")
try FileManager.default.createDirectory(
at: destination, withIntermediateDirectories: true)
// ── Top-level OCI cache check ─────────────────────────────────────────
if cachingEnabled && validateOCICache(manifest: manifest, manifestId: manifestId) {
Logger.info("OCI cache hit — copying from cache instead of downloading")
try copyFromOCICache(manifest: manifest, manifestId: manifestId, to: destination)
Logger.info("OCI cache copy complete")
try cleanupOldVersions(currentManifestId: manifestId, image: imageName)
try saveImageMetadata(image: imageName, manifestId: manifestId)
return
}
// Ensure cache directory exists for this image when caching is enabled
if cachingEnabled {
let cacheDir = getImageCacheDirectory(manifestId: manifestId)
try FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true)
}
let tempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("lume_oci_\(UUID().uuidString)")
try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: tempDir) }
// ── Detect format: single-blob vs chunked ────────────────────────────
let diskLayers = manifest.layers.filter { $0.mediaType == OCIMediaType.disk }
let isChunked = diskLayers.count > 1
|| (diskLayers.count == 1 && diskLayers[0].annotations?[OCIAnnotation.partNumber] != nil)
// Set total download size so progress % is meaningful
let allLayers = manifest.layers + (manifest.config.map { [$0] } ?? [])
let downloadableLayers = uniqueLayersByDigest(
allLayers.filter { $0.mediaType != "application/vnd.oci.empty.v1+json" })
let totalDownloadBytes = downloadableLayers.reduce(Int64(0)) {
$0 + Int64($1.size)
}
let totalFiles = downloadableLayers.count
await downloadProgress.setTotal(totalDownloadBytes, files: totalFiles)
// ── Download config & aux (shared by both paths) ─────────────────────
var configData: Data?
if let configLayer = manifest.config {
let cachedConfigPath = cachingEnabled
? getCachedLayerPath(manifestId: manifestId, digest: configLayer.digest) : nil
let blobDest: URL
if let cached = cachedConfigPath,
FileManager.default.fileExists(atPath: cached.path)
{
Logger.info("Config layer found in cache, skipping download (\(configLayer.digest.prefix(19))…)")
await downloadProgress.addProgress(Int64(configLayer.size))
blobDest = cached
} else {
blobDest = tempDir.appendingPathComponent(
configLayer.digest.replacingOccurrences(of: ":", with: "_"))
Logger.info("Downloading config layer (\(configLayer.digest.prefix(19))…)")
try await downloadLayer(
repository: repository,
digest: configLayer.digest,
mediaType: configLayer.mediaType,
token: token,
to: blobDest,
maxRetries: 5,
progress: downloadProgress
)
// Save to cache
if let cached = cachedConfigPath {
try? storeVerifiedLayer(from: blobDest, inCacheAt: cached)
}
}
configData = try Data(contentsOf: blobDest)
}
var nvramBlobPath: URL?
if let nvramLayer = manifest.layers.first(where: { $0.mediaType == OCIMediaType.nvram }) {
let cachedNvramPath = cachingEnabled
? getCachedLayerPath(manifestId: manifestId, digest: nvramLayer.digest) : nil
let blobDest: URL
if let cached = cachedNvramPath,
FileManager.default.fileExists(atPath: cached.path)
{
Logger.info("Nvram layer found in cache, skipping download (\(nvramLayer.digest.prefix(19))…)")
await downloadProgress.addProgress(Int64(nvramLayer.size))
blobDest = cached
} else {
blobDest = tempDir.appendingPathComponent(
nvramLayer.digest.replacingOccurrences(of: ":", with: "_"))
Logger.info("Downloading nvram layer (\(nvramLayer.digest.prefix(19))…)")
try await downloadLayer(
repository: repository,
digest: nvramLayer.digest,
mediaType: nvramLayer.mediaType,
token: token,
to: blobDest,
maxRetries: 5,
progress: downloadProgress
)
// Save to cache
if let cached = cachedNvramPath {
try? storeVerifiedLayer(from: blobDest, inCacheAt: cached)
}
}
nvramBlobPath = blobDest
}
// ── Process config ────────────────────────────────────────────────────
var vmConfig: VMConfig?
var diskUncompressedSize: UInt64?
if let data = configData {
Logger.info("Config layer raw JSON: \(String(data: data, encoding: .utf8) ?? "<not utf8>")")
}
Logger.info("Manifest layers: \(manifest.layers.map { "\($0.mediaType) size=\($0.size)" }.joined(separator: ", "))")
Logger.info("Manifest config mediaType: \(manifest.config?.mediaType ?? "nil")")
if let data = configData {
do {
let ociCfg = try JSONDecoder().decode(LumeOCIConfig.self, from: data)
Logger.info("Decoded LumeOCIConfig: os=\(ociCfg.os) hardwareModel=\(ociCfg.hardwareModel.prefix(20))...")
_ = ociCfg // used below in the outer block
} catch {
Logger.info("WARNING: Failed to decode LumeOCIConfig: \(error)")
}
}
if let data = configData,
let ociCfg = try? JSONDecoder().decode(LumeOCIConfig.self, from: data)
{
let hardwareModel = Data(base64Encoded: ociCfg.hardwareModel)
let machineIdentifier = Data(base64Encoded: ociCfg.machineIdentifier)
let ann = manifest.annotations
let cpuCount = ann?["org.trycua.lume.cpu-count"].flatMap(Int.init)
let memorySize = ann?["org.trycua.lume.memory-size"].flatMap(UInt64.init)
let display = ann?["org.trycua.lume.display"] ?? "1920x1080"
let netModeStr = ann?["org.trycua.lume.network-mode"] ?? "nat"
// For disk size, prefer manifest annotation, then sum of chunk sizes
if let totalSizeStr = ann?["org.trycua.lume.total-uncompressed-size"],
let totalSize = UInt64(totalSizeStr) {
diskUncompressedSize = totalSize
} else if isChunked {
diskUncompressedSize = diskLayers.compactMap {
$0.annotations?["org.trycua.lume.content.uncompressed-size"].flatMap(UInt64.init)
}.reduce(0, +)
} else if let singleLayer = diskLayers.first,
let sizeStr = singleLayer.annotations?["org.trycua.lume.content.uncompressed-size"],
let size = UInt64(sizeStr) {
diskUncompressedSize = size
}
let diskSize = ann?["org.trycua.lume.disk-size"].flatMap(UInt64.init)
?? diskUncompressedSize
vmConfig = try? VMConfig(
os: ociCfg.os,
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display,
hardwareModel: hardwareModel,
machineIdentifier: machineIdentifier,
networkMode: NetworkMode.parse(netModeStr) ?? .nat
)
}
// Write config.json
let configDest = destination.appendingPathComponent("config.json")
if let cfg = vmConfig {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(cfg)
try data.write(to: configDest)
Logger.info("Wrote config.json")
} else {
Logger.info("WARNING: vmConfig is nil, skipping config.json write")
}
// ── Process nvram ────────────────────────────────────────────────────
if let nvramPath = nvramBlobPath {
let nvramDest = destination.appendingPathComponent("nvram.bin")
try FileManager.default.copyItem(at: nvramPath, to: nvramDest)
Logger.info("Saved nvram.bin")
} else {
Logger.info("WARNING: nvramBlobPath is nil, skipping nvram.bin write")
}
// ── Process disk ──────────────────────────────────────────────────────
let diskDest = destination.appendingPathComponent("disk.img")
if isChunked {
// ── Chunked path: parallel download + sparse reassembly ──────────
let sortedChunks = diskLayers.sorted {
let a = Int($0.annotations?[OCIAnnotation.partNumber] ?? "0") ?? 0
let b = Int($1.annotations?[OCIAnnotation.partNumber] ?? "0") ?? 0
return a < b
}
// Compute total uncompressed size from chunks if not already known
let totalSize = diskUncompressedSize ?? sortedChunks.compactMap {
$0.annotations?["org.trycua.lume.content.uncompressed-size"].flatMap(UInt64.init)
}.reduce(0, +)
Logger.info("Chunked disk: \(sortedChunks.count) parts, total uncompressed size: \(totalSize)")
// Create sparse output file pre-sized to total
FileManager.default.createFile(atPath: diskDest.path, contents: nil)
let diskHandle = try FileHandle(forWritingTo: diskDest)
try diskHandle.truncate(atOffset: totalSize)
try diskHandle.close()
let pullProgress = LayerProgressDisplay()
for (idx, chunk) in sortedChunks.enumerated() {
await pullProgress.addLayer(
id: "chunk-\(idx)",
label: "disk layer \(idx + 1)/\(sortedChunks.count)",
totalBytes: Int64(chunk.size),
mode: .pull)
}
let chunkGroups = groupOCIChunksByDigest(sortedChunks)
let chunkGroupsByDigest = Dictionary(
uniqueKeysWithValues: chunkGroups.map { ($0.layer.digest, $0) })
if chunkGroups.count < sortedChunks.count {
Logger.info(
"Reusing \(chunkGroups.count) unique blobs across \(sortedChunks.count) disk parts"
)
}
// Download up to four unique blobs concurrently. As each blob
// arrives, write every logical part that references it before
// removing the per-pull copy.
try await withThrowingTaskGroup(of: (String, URL).self) { group in
let initialCount = min(4, chunkGroups.count)
for groupIndex in 0..<initialCount {
let chunkGroup = chunkGroups[groupIndex]
group.addTask {
try await self.downloadOCIChunkGroup(
chunkGroup,
repository: repository,
token: token,
manifestId: manifestId,
tempDir: tempDir,
pullProgress: pullProgress)
}
}
var nextGroupIndex = initialCount
while let (completedDigest, completedPath) = try await group.next() {
try Task.checkCancellation()
guard let completedGroup = chunkGroupsByDigest[completedDigest] else {
throw PullError.reassemblyFailed(
"Downloaded an unexpected OCI blob \(completedDigest)")
}
// Keep downloads flowing while this blob is written out.
if nextGroupIndex < chunkGroups.count {
let chunkGroup = chunkGroups[nextGroupIndex]
nextGroupIndex += 1
group.addTask {
try await self.downloadOCIChunkGroup(
chunkGroup,
repository: repository,
token: token,
manifestId: manifestId,
tempDir: tempDir,
pullProgress: pullProgress)
}
}
// Decompress the blob once and write it at every part that uses it.
for reference in completedGroup.references {
await pullProgress.updateStatus(
id: "chunk-\(reference.index)", status: .decompressing)
}
let handle = try FileHandle(forWritingTo: diskDest)
do {
let _ = try gunzipChunkAndWriteSparse(
inputPath: completedPath,
outputHandle: handle,
startOffsets: completedGroup.references.map(\.offset))
try handle.close()
} catch {
try? handle.close()
throw error
}
for reference in completedGroup.references {
await pullProgress.markDone(id: "chunk-\(reference.index)")
}
try? FileManager.default.removeItem(at: completedPath)
}
}
await pullProgress.finish()
Logger.info("Disk image reassembled from \(sortedChunks.count) chunks")
} else if let singleDiskLayer = diskLayers.first {
// ── Single-blob fallback (backward compat) ───────────────────────
let cachedDiskPath = cachingEnabled
? getCachedLayerPath(manifestId: manifestId, digest: singleDiskLayer.digest) : nil
let blobDest: URL
if let cached = cachedDiskPath,
FileManager.default.fileExists(atPath: cached.path)
{
Logger.info(
"Single disk layer found in cache, skipping download (\(singleDiskLayer.digest.prefix(19))…)"
)
await downloadProgress.addProgress(Int64(singleDiskLayer.size))
// Copy to a unique temp path to avoid sibling .raw race when
// multiple pulls decompress the same cached file concurrently.
let tmpCopy = tempDir.appendingPathComponent(UUID().uuidString + ".gz")
try FileManager.default.copyItem(at: cached, to: tmpCopy)
blobDest = tmpCopy
} else {
blobDest = tempDir.appendingPathComponent(
singleDiskLayer.digest.replacingOccurrences(of: ":", with: "_"))
Logger.info(
"Downloading single disk layer (\(singleDiskLayer.digest.prefix(19))…)")
try await downloadLayer(
repository: repository,
digest: singleDiskLayer.digest,
mediaType: singleDiskLayer.mediaType,
token: token,
to: blobDest,
maxRetries: 5,
progress: downloadProgress
)
// Save to cache
if let cached = cachedDiskPath {
try? storeVerifiedLayer(from: blobDest, inCacheAt: cached)
}
}
let uncompSizeStr = singleDiskLayer.annotations?["org.trycua.lume.content.uncompressed-size"]
if let sizeStr = uncompSizeStr, let uncompSize = UInt64(sizeStr), uncompSize > 0 {
Logger.info("Decompressing disk image (gzip, sparse-aware)…")
FileManager.default.createFile(atPath: diskDest.path, contents: nil)
let diskHandle = try FileHandle(forWritingTo: diskDest)
try diskHandle.truncate(atOffset: uncompSize)
let _ = try gunzipChunkAndWriteSparse(
inputPath: blobDest, outputHandle: diskHandle, startOffset: 0)
try diskHandle.close()
Logger.info("Disk image decompressed (sparse)")
} else {
try FileManager.default.copyItem(at: blobDest, to: diskDest)
Logger.info("Saved disk.img (uncompressed)")
}
}
// Register this OCI image in metadata so getImages() can discover it and
// cleanupOldVersions can remove superseded manifests.
if cachingEnabled {
try cleanupOldVersions(currentManifestId: manifestId, image: imageName)
try saveImageMetadata(image: imageName, manifestId: manifestId)
}
Logger.info("OCI pull complete")
}
/// Returns true when every OCI layer for this manifest is already in the local cache.
/// When this returns true, `copyFromOCICache` can reconstruct the VM directory without
/// any network activity.
private func validateOCICache(manifest: Manifest, manifestId: String) -> Bool {
guard cachingEnabled else { return false }
// Check config layer
if let configLayer = manifest.config {
let cached = getCachedLayerPath(manifestId: manifestId, digest: configLayer.digest)
guard FileManager.default.fileExists(atPath: cached.path) else { return false }
}
// Check all disk / nvram layers
for layer in manifest.layers {
guard layer.mediaType != "application/vnd.oci.empty.v1+json" else { continue }
let cached = getCachedLayerPath(manifestId: manifestId, digest: layer.digest)
guard FileManager.default.fileExists(atPath: cached.path) else {
Logger.debug("OCI cache miss for layer \(layer.digest.prefix(19))…")
return false
}
}
Logger.debug("OCI cache fully valid for manifestId: \(manifestId)")
return true
}
/// Copies all OCI layers from the local cache into `destination`, producing the same
/// VM directory layout that `pullOCI` would create via network download.
private func copyFromOCICache(manifest: Manifest, manifestId: String, to destination: URL)
throws
{
Logger.info("Copying OCI image from layer cache")
// ── Config ────────────────────────────────────────────────────────────
if let configLayer = manifest.config {
let cached = getCachedLayerPath(manifestId: manifestId, digest: configLayer.digest)
let configData = try Data(contentsOf: cached)
if let ociCfg = try? JSONDecoder().decode(LumeOCIConfig.self, from: configData) {
let hardwareModel = Data(base64Encoded: ociCfg.hardwareModel)
let machineIdentifier = Data(base64Encoded: ociCfg.machineIdentifier)
let ann = manifest.annotations
let cpuCount = ann?["org.trycua.lume.cpu-count"].flatMap(Int.init)
let memorySize = ann?["org.trycua.lume.memory-size"].flatMap(UInt64.init)
let display = ann?["org.trycua.lume.display"] ?? "1920x1080"
let netModeStr = ann?["org.trycua.lume.network-mode"] ?? "nat"
let diskLayers = manifest.layers.filter { $0.mediaType == OCIMediaType.disk }
var diskUncompressedSize: UInt64?
if let totalSizeStr = ann?["org.trycua.lume.total-uncompressed-size"],
let totalSize = UInt64(totalSizeStr)
{
diskUncompressedSize = totalSize
} else {
diskUncompressedSize = diskLayers.compactMap {
$0.annotations?["org.trycua.lume.content.uncompressed-size"].flatMap(
UInt64.init)
}.reduce(0, +)
}
let diskSize =
ann?["org.trycua.lume.disk-size"].flatMap(UInt64.init) ?? diskUncompressedSize
if let vmConfig = try? VMConfig(
os: ociCfg.os,
cpuCount: cpuCount,
memorySize: memorySize,
diskSize: diskSize,
display: display,
hardwareModel: hardwareModel,
machineIdentifier: machineIdentifier,
networkMode: NetworkMode.parse(netModeStr) ?? .nat
) {
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
try encoder.encode(vmConfig).write(
to: destination.appendingPathComponent("config.json"))
Logger.info("Wrote config.json from cache")
}
}
}
// ── NVRAM ─────────────────────────────────────────────────────────────
if let nvramLayer = manifest.layers.first(where: { $0.mediaType == OCIMediaType.nvram }) {
let cached = getCachedLayerPath(manifestId: manifestId, digest: nvramLayer.digest)
try FileManager.default.copyItem(
at: cached, to: destination.appendingPathComponent("nvram.bin"))
Logger.info("Copied nvram.bin from cache")
}
// ── Disk ──────────────────────────────────────────────────────────────
let diskDest = destination.appendingPathComponent("disk.img")
let diskLayers = manifest.layers.filter { $0.mediaType == OCIMediaType.disk }
let isChunked =
diskLayers.count > 1
|| (diskLayers.count == 1
&& diskLayers[0].annotations?[OCIAnnotation.partNumber] != nil)
if isChunked {
let sortedChunks = diskLayers.sorted {
let a = Int($0.annotations?[OCIAnnotation.partNumber] ?? "0") ?? 0
let b = Int($1.annotations?[OCIAnnotation.partNumber] ?? "0") ?? 0
return a < b
}
let ann = manifest.annotations
let totalSize: UInt64
if let totalSizeStr = ann?["org.trycua.lume.total-uncompressed-size"],
let ts = UInt64(totalSizeStr)
{
totalSize = ts
} else {
totalSize = sortedChunks.compactMap {
$0.annotations?["org.trycua.lume.content.uncompressed-size"].flatMap(
UInt64.init)
}.reduce(0, +)
}
FileManager.default.createFile(atPath: diskDest.path, contents: nil)
let diskHandle = try FileHandle(forWritingTo: diskDest)
try diskHandle.truncate(atOffset: totalSize)
try diskHandle.close()
let copyTempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("lume_oci_copy_\(UUID().uuidString)")
try FileManager.default.createDirectory(
at: copyTempDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: copyTempDir) }
for (idx, chunk) in sortedChunks.enumerated() {
let cached = getCachedLayerPath(manifestId: manifestId, digest: chunk.digest)
let chunkOffset = UInt64(chunk.annotations?[OCIAnnotation.partOffset] ?? "0") ?? 0
Logger.info(
"Decompressing cached chunk \(idx + 1)/\(sortedChunks.count) from cache")
// Copy to unique temp path to avoid sibling .raw race with concurrent pulls.
let tmpCopy = copyTempDir.appendingPathComponent(UUID().uuidString + ".gz")
try FileManager.default.copyItem(at: cached, to: tmpCopy)
defer { try? FileManager.default.removeItem(at: tmpCopy) }
let handle = try FileHandle(forWritingTo: diskDest)
let _ = try gunzipChunkAndWriteSparse(
inputPath: tmpCopy, outputHandle: handle, startOffset: chunkOffset)
try handle.close()
}
Logger.info("Disk image reassembled from \(sortedChunks.count) cached chunks")
} else if let singleDiskLayer = diskLayers.first {
let cached = getCachedLayerPath(manifestId: manifestId, digest: singleDiskLayer.digest)
let uncompSizeStr = singleDiskLayer.annotations?[
"org.trycua.lume.content.uncompressed-size"]
if let sizeStr = uncompSizeStr, let uncompSize = UInt64(sizeStr), uncompSize > 0 {
FileManager.default.createFile(atPath: diskDest.path, contents: nil)
let diskHandle = try FileHandle(forWritingTo: diskDest)
try diskHandle.truncate(atOffset: uncompSize)
// Copy to unique temp path to avoid sibling .raw race with concurrent pulls.
let singleCopyTempDir = FileManager.default.temporaryDirectory
.appendingPathComponent("lume_oci_copy_\(UUID().uuidString)")
try FileManager.default.createDirectory(
at: singleCopyTempDir, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: singleCopyTempDir) }
let tmpCopy = singleCopyTempDir.appendingPathComponent(UUID().uuidString + ".gz")
try FileManager.default.copyItem(at: cached, to: tmpCopy)
let _ = try gunzipChunkAndWriteSparse(
inputPath: tmpCopy, outputHandle: diskHandle, startOffset: 0)
try diskHandle.close()
Logger.info("Disk image decompressed (sparse) from cache")
} else {
try FileManager.default.copyItem(at: cached, to: diskDest)
Logger.info("Saved disk.img (uncompressed) from cache")
}
}
}
}
/// Delegate that tracks upload byte progress via URLSession callbacks.
final class UploadProgressDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
private let totalBytes: Int64
private let onProgress: (@Sendable (Int64, Int64) -> Void)?
init(totalBytes: Int64, onProgress: (@Sendable (Int64, Int64) -> Void)?) {
self.totalBytes = totalBytes
self.onProgress = onProgress
}
func urlSession(
_ session: URLSession, task: URLSessionTask,
didSendBodyData bytesSent: Int64, totalBytesSent: Int64,
totalBytesExpectedToSend: Int64
) {
onProgress?(totalBytesSent, totalBytes)
}
}
/// Thread-safe collector for chunk descriptors from parallel workers.
actor ChunkCollector {
private var chunks: [DiskChunkDescriptor?]
init(count: Int) {
chunks = [DiskChunkDescriptor?](repeating: nil, count: count)
}
func set(index: Int, desc: DiskChunkDescriptor) {
chunks[index] = desc
}
func getAll() -> [DiskChunkDescriptor] {
chunks.compactMap { $0 }
}
}
/// Tracks seen digests for content-addressable deduplication across chunks.
actor DigestTracker {
private var seen: Swift.Set<String> = []
/// Returns true if the digest was already seen (duplicate), false if first time.
func markSeen(digest: String) -> Bool {
if seen.contains(digest) {
return true
}
seen.insert(digest)
return false
}
}
/// Docker-style multi-line progress display for concurrent layer operations.
/// Each layer gets its own line, updated in-place using ANSI escape codes.
actor LayerProgressDisplay {
enum LayerStatus {
case waiting
case compressing
case waitingUpload
case pushing
case downloading
case decompressing
case exists
case done
case error(String)
}
enum LayerMode {
case push
case pull
}
struct LayerState {
let label: String
var totalBytes: Int64
var completedBytes: Int64 = 0
var status: LayerStatus = .waiting
var digest: String?
var mode: LayerMode = .push
}
private var layers: [String: LayerState] = [:]
private var layerOrder: [String] = []
private var lineCount = 0
private var lastRenderTime: Date = .distantPast
private var startTime: Date = Date()
// Separate throughput tracking for compress vs upload
// Per-layer byte counters for accurate parallel tracking
private var layerCompressedBytes: [String: Int64] = [:]
private var layerUploadedBytes: [String: Int64] = [:]
private var lastCompressedTotal: Int64 = 0
private var lastUploadedTotal: Int64 = 0
private var lastSpeedTime: Date = Date()
private var compressSpeed: Double = 0
private var uploadSpeed: Double = 0
private var smoothedOverallSpeed: Double = 0
private var lastTotalDone: Int64 = 0
private var hasSeenUpload: Bool = false
private var smoothedUploadSpeed: Double = 0
private var smoothedCompressSpeed: Double = 0
// Track compressed bytes for upload ETA
private var totalUploadBytes: Int64 = 0 // compressed bytes registered for upload
private var totalUploadedBytes: Int64 = 0 // compressed bytes actually uploaded
private var totalUncompressedRegistered: Int64 = 0 // uncompressed bytes of registered layers
private var totalUncompressedAll: Int64 = 0 // total uncompressed bytes across all layers
private var skippedBytes: Int64 = 0 // compressed bytes of dedup/exists layers (no upload)
func addLayer(id: String, label: String, totalBytes: Int64 = 0, mode: LayerMode = .push) {
layers[id] = LayerState(label: label, totalBytes: totalBytes, mode: mode)
layerOrder.append(id)
}
func setDigest(id: String, digest: String) {
layers[id]?.digest = digest
}
func updateStatus(id: String, status: LayerStatus) {
layers[id]?.status = status
render()
}
func updateProgress(id: String, completedBytes: Int64, totalBytes: Int64? = nil) {
if let total = totalBytes {
layers[id]?.totalBytes = total
}
layers[id]?.completedBytes = completedBytes
render()
}
func setTotalUncompressed(_ bytes: Int64) {
totalUncompressedAll = bytes
}
func registerUploadWork(compressedBytes: Int64, uncompressedBytes: Int64) {
totalUploadBytes += compressedBytes
totalUncompressedRegistered += uncompressedBytes
}
func registerSkipped(compressedBytes: Int64, uncompressedBytes: Int64) {
skippedBytes += compressedBytes
totalUncompressedRegistered += uncompressedBytes
}
func reportUploadDone(_ bytes: Int64) {
totalUploadedBytes += bytes
}
func reportCompressBytes(id: String, _ bytes: Int64) {
layerCompressedBytes[id] = bytes
}
func reportUploadBytes(id: String, _ bytes: Int64) {
layerUploadedBytes[id] = bytes
}
func markDone(id: String, bytes: Int64? = nil) {
if let b = bytes { layers[id]?.completedBytes = b }
layers[id]?.status = .done
let current = layers[id]?.completedBytes ?? 0
if current == 0 {
let total = layers[id]?.totalBytes ?? 0
layers[id]?.completedBytes = total
}
render()
}
func markExists(id: String) {
layers[id]?.status = .exists
let total = layers[id]?.totalBytes ?? 0
layers[id]?.completedBytes = total
render()
}
func finish() {
forceRender()
print() // Final newline
}
private func render() {
let now = Date()
guard now.timeIntervalSince(lastRenderTime) >= 0.15 else { return }
lastRenderTime = now
forceRender()
}
private func forceRender() {
// Get terminal height to cap output
var ws = winsize()
let termHeight: Int
if ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_row > 0 {
termHeight = Int(ws.ws_row) - 1 // leave 1 line margin
} else {
termHeight = 40 // fallback
}
// Move cursor up to overwrite previous render
if lineCount > 0 {
print("\u{1B}[\(lineCount)A", terminator: "")
}
var doneCount = 0
var doneLayers: [LayerState] = []
var waitingUploadLayers: [LayerState] = []
var activeLayers: [LayerState] = []
var isCompressing = false
for id in layerOrder {
guard let layer = layers[id] else { continue }
switch layer.status {
case .waiting:
break
case .done, .exists:
doneCount += 1
doneLayers.append(layer)
case .waitingUpload:
waitingUploadLayers.append(layer)
case .compressing:
isCompressing = true
default:
activeLayers.append(layer)
}
}
// Build all output lines into an array, then cap to terminal height
var outputLines: [String] = []
// Done layers: deduplicate by digest, then first 10 ... last 10
if !doneLayers.isEmpty {
var seenDigests = Swift.Set<String>()
var uniqueDone: [LayerState] = []
for layer in doneLayers {
let key = layer.digest ?? layer.label
if !seenDigests.contains(key) {
seenDigests.insert(key)
uniqueDone.append(layer)
}
}
let showDone: [LayerState]
if uniqueDone.count <= 20 {
showDone = uniqueDone
} else {
showDone = Array(uniqueDone.prefix(10)) + Array(uniqueDone.suffix(10))
}
for (i, layer) in showDone.enumerated() {
if uniqueDone.count > 20 && i == 10 {
outputLines.append("...")
}
outputLines.append(formatLayer(layer))
}
}
// Aggregate compression progress as single line
if isCompressing && totalUncompressedAll > 0 {
let totalCompressed = layerCompressedBytes.values.reduce(Int64(0), +)
let pct = Double(totalCompressed) / Double(totalUncompressedAll)
let bar = progressBar(progress: pct)
let label = "disk.img".padding(toLength: 12, withPad: " ", startingAt: 0)
outputLines.append("\(label): Compressing \(bar) \(formatBytes(totalCompressed))/\(formatBytes(totalUncompressedAll))")
}
// Waiting-for-upload layers
for layer in waitingUploadLayers {
outputLines.append(formatLayer(layer))
}
// Active layers (uploading, downloading, etc.)
for layer in activeLayers {
outputLines.append(formatLayer(layer))
}
// Reserve 1 line for summary
let maxLayerLines = termHeight - 1
if outputLines.count > maxLayerLines {
// Keep last N lines (active/uploading are most important, at the end)
let overflow = outputLines.count - maxLayerLines
outputLines = ["... (\(overflow) more)"] + Array(outputLines.suffix(maxLayerLines - 1))
}
// Print all lines, clearing each
var lines = 0
for line in outputLines {
print("\u{1B}[2K\(line)")
lines += 1
}
// Update throughput tracking
let now = Date()
let elapsed = now.timeIntervalSince(startTime)
let dt = now.timeIntervalSince(lastSpeedTime)
if dt >= 0.5 {
let compressedTotal = layerCompressedBytes.values.reduce(Int64(0), +)
let uploadedTotal = layerUploadedBytes.values.reduce(Int64(0), +)
let dCompress = Double(compressedTotal - lastCompressedTotal)
let dUpload = Double(uploadedTotal - lastUploadedTotal)
// Exponential smoothing for display speed (responsive, alpha=0.3)
let alpha = 0.3
compressSpeed = alpha * (dCompress / dt) + (1 - alpha) * compressSpeed
uploadSpeed = alpha * (dUpload / dt) + (1 - alpha) * uploadSpeed
// Heavier smoothing for ETA speeds (alpha=0.1) — stable, won't flicker
// Only decay toward zero slowly; between-chunk gaps won't kill the estimate
let etaAlpha = 0.1
if dUpload > 0 {
hasSeenUpload = true
smoothedUploadSpeed = smoothedUploadSpeed > 0
? etaAlpha * (dUpload / dt) + (1 - etaAlpha) * smoothedUploadSpeed
: dUpload / dt
} else if smoothedUploadSpeed > 0 {
// Decay very slowly when no upload data (gap between chunks)
smoothedUploadSpeed *= 0.98
}
if dCompress > 0 {
smoothedCompressSpeed = smoothedCompressSpeed > 0
? etaAlpha * (dCompress / dt) + (1 - etaAlpha) * smoothedCompressSpeed
: dCompress / dt
} else if smoothedCompressSpeed > 0 {
smoothedCompressSpeed *= 0.98
}
lastCompressedTotal = compressedTotal
lastUploadedTotal = uploadedTotal
lastSpeedTime = now
}
let totalDone = layers.values.reduce(Int64(0)) { $0 + $1.completedBytes }
let totalAll = layers.values.reduce(Int64(0)) { $0 + $1.totalBytes }
let total = layers.count
var summary = "\u{1B}[2K\(doneCount)/\(total) done"
summary += " | \(formatBytes(totalDone))/\(formatBytes(totalAll))"
// ETA first
if hasSeenUpload && smoothedUploadSpeed > 0 {
// Estimate total compressed upload size using observed compression ratio
// ratio = total_compressed_seen / total_uncompressed_seen
let seenCompressed = totalUploadBytes + skippedBytes
let ratio = totalUncompressedRegistered > 0
? Double(seenCompressed) / Double(totalUncompressedRegistered)
: 0.5
// Extrapolate total compressed bytes for all layers (minus skipped)
let estimatedTotalUpload = Double(totalUncompressedAll) * ratio - Double(skippedBytes)
let remaining = max(0, estimatedTotalUpload - Double(totalUploadedBytes))
let eta = remaining / smoothedUploadSpeed
summary += " | ETA \(formatTime(eta)) (uploading)"
} else if smoothedCompressSpeed > 0 && totalDone > 0 && totalAll > totalDone {
let eta = Double(totalAll - totalDone) / smoothedCompressSpeed
summary += " | ETA \(formatTime(eta)) (compressing)"
} else {
summary += " | \(formatTime(elapsed))"
}
// Speeds after ETA
if compressSpeed > 0 {
summary += " | 🗜 \(formatSpeed(compressSpeed))"
}
if uploadSpeed > 0 {
summary += " | ⬆ \(formatSpeed(uploadSpeed))"
}
print(summary)
lines += 1
// Clear any leftover lines from previous render that had more lines
if lines < lineCount {
for _ in 0..<(lineCount - lines) {
print("\u{1B}[2K")
}
// Move back up to just after our content
let extra = lineCount - lines
if extra > 0 {
print("\u{1B}[\(extra)A", terminator: "")
}
}
lineCount = lines
fflush(stdout)
}
private func formatLayer(_ layer: LayerState) -> String {
// For digest-based labels (upload/download/done), use first 12 chars of digest
// For compression, use the chunk label
let id: String
if let digest = layer.digest {
let short = digest.hasPrefix("sha256:")
? String(digest.dropFirst(7).prefix(12))
: String(digest.prefix(12))
id = short.padding(toLength: 12, withPad: " ", startingAt: 0)
} else {
let short = layer.label.count > 12
? String(layer.label.prefix(12))
: layer.label
id = short.padding(toLength: 12, withPad: " ", startingAt: 0)
}
switch layer.status {
case .waiting:
return "\(id): Waiting"
case .compressing:
if layer.totalBytes > 0 && layer.completedBytes > 0 {
let pct = Double(layer.completedBytes) / Double(layer.totalBytes)
let bar = progressBar(progress: pct)
return "\(id): Compressing \(bar) \(formatBytes(layer.completedBytes))/\(formatBytes(layer.totalBytes))"
}
return "\(id): Compressing..."
case .waitingUpload:
return "\(id): Waiting"
case .pushing:
let pct = layer.totalBytes > 0
? Double(layer.completedBytes) / Double(layer.totalBytes) : 0
let bar = progressBar(progress: pct)
return "\(id): Uploading \(bar) \(formatBytes(layer.completedBytes))/\(formatBytes(layer.totalBytes))"
case .downloading:
let pct = layer.totalBytes > 0
? Double(layer.completedBytes) / Double(layer.totalBytes) : 0
let bar = progressBar(progress: pct)
return "\(id): Downloading \(bar) \(formatBytes(layer.completedBytes))/\(formatBytes(layer.totalBytes))"
case .decompressing:
return "\(id): Extracting..."
case .exists:
return "\(id): Already exists"
case .done:
let action = layer.mode == .push ? "Push complete" : "Pull complete"
return "\(id): \(action)"
case .error(let msg):
return "\(id): Error: \(msg)"
}
}
private func progressBar(progress: Double, width: Int = 25) -> String {
let filled = Int(progress * Double(width))
let empty = width - filled
return
"[" + String(repeating: "█", count: max(0, filled))
+ String(repeating: "░", count: max(0, empty)) + "]"
}
private func formatBytes(_ bytes: Int64) -> String {
let units = ["B", "KB", "MB", "GB"]
var size = Double(bytes)
var idx = 0
while size > 1024 && idx < units.count - 1 {
size /= 1024
idx += 1
}
return String(format: "%.1f %@", size, units[idx])
}
private func formatSpeed(_ bytesPerSec: Double) -> String {
return formatBytes(Int64(bytesPerSec)) + "/s"
}
private func formatTime(_ seconds: TimeInterval) -> String {
let total = Int(seconds)
if total >= 3600 {
let hrs = total / 3600
let mins = (total % 3600) / 60
let secs = total % 60
return String(format: "%dh %dm %ds", hrs, mins, secs)
} else if total >= 60 {
let mins = total / 60
let secs = total % 60
return String(format: "%dm %ds", mins, secs)
} else {
return String(format: "%ds", total)
}
}
}
actor UploadProgressTracker {
private var totalBytes: Int64 = 0
private var uploadedBytes: Int64 = 0 // Renamed
private var progressLogger = ProgressLogger(threshold: 0.01)
private var totalFiles: Int = 0 // Keep track of total items
private var completedFiles: Int = 0 // Keep track of completed items
// Upload speed tracking
private var startTime: Date = Date()
private var lastUpdateTime: Date = Date()
private var lastUpdateBytes: Int64 = 0
private var speedSamples: [Double] = []
private var peakSpeed: Double = 0
private var totalElapsedTime: TimeInterval = 0
// Smoothing factor for speed calculation
private var speedSmoothing: Double = 0.3
private var smoothedSpeed: Double = 0
func setTotal(_ total: Int64, files: Int) {
totalBytes = total
totalFiles = files
startTime = Date()
lastUpdateTime = startTime
uploadedBytes = 0 // Reset uploaded bytes
completedFiles = 0 // Reset completed files
smoothedSpeed = 0
speedSamples = []
peakSpeed = 0
totalElapsedTime = 0
}
func addProgress(_ bytes: Int64) {
uploadedBytes += bytes
completedFiles += 1 // Increment completed files count
let now = Date()
let elapsed = now.timeIntervalSince(lastUpdateTime)
// Show first progress update immediately, then throttle updates
let shouldUpdate =
(uploadedBytes <= bytes) || (elapsed >= 0.5) || (completedFiles == totalFiles)
if shouldUpdate && totalBytes > 0 { // Ensure totalBytes is set
let currentSpeed = Double(uploadedBytes - lastUpdateBytes) / max(elapsed, 0.001)
speedSamples.append(currentSpeed)
// Cap samples array
if speedSamples.count > 20 {
speedSamples.removeFirst(speedSamples.count - 20)
}
peakSpeed = max(peakSpeed, currentSpeed)
// Apply exponential smoothing
if smoothedSpeed == 0 {
smoothedSpeed = currentSpeed
} else {
smoothedSpeed = speedSmoothing * currentSpeed + (1 - speedSmoothing) * smoothedSpeed
}
let recentAvgSpeed = calculateAverageSpeed()
let totalElapsed = now.timeIntervalSince(startTime)
let overallAvgSpeed = totalElapsed > 0 ? Double(uploadedBytes) / totalElapsed : 0
let progress = totalBytes > 0 ? Double(uploadedBytes) / Double(totalBytes) : 1.0 // Avoid division by zero
logSpeedProgress(
current: progress,
currentSpeed: currentSpeed,
averageSpeed: recentAvgSpeed,
smoothedSpeed: smoothedSpeed,
overallSpeed: overallAvgSpeed,
peakSpeed: peakSpeed,
context: "Uploading Image" // Changed context
)
lastUpdateTime = now
lastUpdateBytes = uploadedBytes
totalElapsedTime = totalElapsed
}
}
private func calculateAverageSpeed() -> Double {
guard !speedSamples.isEmpty else { return 0 }
var totalWeight = 0.0
var weightedSum = 0.0
let samples = speedSamples.suffix(min(8, speedSamples.count))
for (index, speed) in samples.enumerated() {
let weight = Double(index + 1)
weightedSum += speed * weight
totalWeight += weight
}
return totalWeight > 0 ? weightedSum / totalWeight : 0
}
// Use the UploadStats struct
func getUploadStats() -> UploadStats {
let avgSpeed = totalElapsedTime > 0 ? Double(uploadedBytes) / totalElapsedTime : 0
return UploadStats(
totalBytes: totalBytes,
uploadedBytes: uploadedBytes, // Renamed
elapsedTime: totalElapsedTime,
averageSpeed: avgSpeed,
peakSpeed: peakSpeed
)
}
private func logSpeedProgress(
current: Double,
currentSpeed: Double,
averageSpeed: Double,
smoothedSpeed: Double,
overallSpeed: Double,
peakSpeed: Double,
context: String
) {
let progressPercent = Int(current * 100)
// let currentSpeedStr = formatByteSpeed(currentSpeed) // Removed unused
let avgSpeedStr = formatByteSpeed(averageSpeed)
// let peakSpeedStr = formatByteSpeed(peakSpeed) // Removed unused
let remainingBytes = totalBytes - uploadedBytes
let speedForEta = max(smoothedSpeed, averageSpeed * 0.8)
let etaSeconds = speedForEta > 0 ? Double(remainingBytes) / speedForEta : 0
let etaStr = formatTimeRemaining(etaSeconds)
let progressBar = createProgressBar(progress: current)
let fileProgress = "(\(completedFiles)/\(totalFiles))" // Add file count
print(
"\r\(progressBar) \(progressPercent)% \(fileProgress) | Speed: \(avgSpeedStr) (Avg) | ETA: \(etaStr) ", // Simplified output
terminator: "")
fflush(stdout)
}
// Helper methods (createProgressBar, formatByteSpeed, formatTimeRemaining) remain the same
private func createProgressBar(progress: Double, width: Int = 30) -> String {
let completedWidth = Int(progress * Double(width))
let remainingWidth = width - completedWidth
let completed = String(repeating: "█", count: completedWidth)
let remaining = String(repeating: "░", count: remainingWidth)
return "[\(completed)\(remaining)]"
}
private func formatByteSpeed(_ bytesPerSecond: Double) -> String {
let units = ["B/s", "KB/s", "MB/s", "GB/s"]
var speed = bytesPerSecond
var unitIndex = 0
while speed > 1024 && unitIndex < units.count - 1 {
speed /= 1024
unitIndex += 1
}
return String(format: "%.1f %@", speed, units[unitIndex])
}
private func formatTimeRemaining(_ seconds: Double) -> String {
if seconds.isNaN || seconds.isInfinite || seconds <= 0 { return "calculating..." }
let hours = Int(seconds) / 3600
let minutes = (Int(seconds) % 3600) / 60
let secs = Int(seconds) % 60
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, minutes, secs)
} else {
return String(format: "%d:%02d", minutes, secs)
}
}
}