Vendor apple/containerization with a VM-extensions forwarding patch
Switch the containerization dependency from the github URL to a vendored copy (third_party/containerization, upstream commit 6b7b42ca) referenced by path, so we can carry a small local patch that upstream lacks: LinuxContainer.Configuration gains a `vmExtensions` field forwarded into VMConfiguration.extensions. Upstream already supports VMConfiguration.extensions + the VZInstanceExtension hook, but LinuxContainer — our only entry point — never forwarded them, so there was no way to attach a device (e.g. a memory balloon) to a container's VM. Tests/, docs/, examples/, images/ and the corresponding test targets are trimmed for footprint (we never build the dependency's tests). See PATCHES.md for the full diff vs. upstream and the re-vendoring procedure. Also adds the ContainerizationExtras product to NucleicCore (AddressAllocator, named in the configureVZ signature). Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import ContainerizationArchive
|
||||
import ContainerizationError
|
||||
import ContainerizationExtras
|
||||
import ContainerizationOCI
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
extension Application {
|
||||
struct Images: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "images",
|
||||
abstract: "Manage images",
|
||||
subcommands: [
|
||||
Get.self,
|
||||
Delete.self,
|
||||
Pull.self,
|
||||
Tag.self,
|
||||
Push.self,
|
||||
Save.self,
|
||||
Load.self,
|
||||
]
|
||||
)
|
||||
|
||||
func run() async throws {
|
||||
let store = Application.imageStore
|
||||
let images = try await store.list()
|
||||
|
||||
print("REFERENCE\tMEDIA TYPE\tDIGEST")
|
||||
for image in images {
|
||||
print("\(image.reference)\t\(image.mediaType)\t\(image.digest)")
|
||||
}
|
||||
}
|
||||
|
||||
struct Delete: AsyncParsableCommand {
|
||||
@Argument var reference: String
|
||||
|
||||
func run() async throws {
|
||||
let store = Application.imageStore
|
||||
try await store.delete(reference: reference)
|
||||
}
|
||||
}
|
||||
|
||||
struct Tag: AsyncParsableCommand {
|
||||
@Argument var old: String
|
||||
@Argument var new: String
|
||||
|
||||
func run() async throws {
|
||||
let store = Application.imageStore
|
||||
_ = try await store.tag(existing: old, new: new)
|
||||
}
|
||||
}
|
||||
|
||||
struct Get: AsyncParsableCommand {
|
||||
@Argument var reference: String
|
||||
|
||||
func run() async throws {
|
||||
let store = Application.imageStore
|
||||
let image = try await store.get(reference: reference)
|
||||
|
||||
let index = try await image.index()
|
||||
|
||||
let enc = JSONEncoder()
|
||||
enc.outputFormatting = .prettyPrinted
|
||||
let data = try enc.encode(ImageDisplay(reference: image.reference, index: index))
|
||||
print(String(data: data, encoding: .utf8)!)
|
||||
}
|
||||
}
|
||||
|
||||
struct ImageDisplay: Codable {
|
||||
let reference: String
|
||||
let index: Index
|
||||
}
|
||||
|
||||
struct Pull: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "pull",
|
||||
abstract: "Pull an image's contents into a content store"
|
||||
)
|
||||
|
||||
@Argument var ref: String
|
||||
|
||||
@Option(name: .customLong("platform"), help: "Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'") var platformString: String?
|
||||
|
||||
@Option(
|
||||
name: .customLong("unpack-path"), help: "Path to a new directory to unpack the image into",
|
||||
transform: { str in
|
||||
URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)
|
||||
})
|
||||
var unpackPath: String?
|
||||
|
||||
@Flag(help: "Pull via plain text http") var http: Bool = false
|
||||
|
||||
func run() async throws {
|
||||
let imageStore = Application.imageStore
|
||||
let platform: Platform? = try {
|
||||
if let platformString {
|
||||
return try Platform(from: platformString)
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
|
||||
let reference = try Reference.parse(ref)
|
||||
reference.normalize()
|
||||
let normalizedReference = reference.description
|
||||
if normalizedReference != ref {
|
||||
print("Reference resolved to \(reference.description)")
|
||||
}
|
||||
|
||||
var startTime = ContinuousClock.now
|
||||
let image = try await Images.withAuthentication(ref: normalizedReference) { auth in
|
||||
try await imageStore.pull(reference: normalizedReference, platform: platform, insecure: http, auth: auth)
|
||||
}
|
||||
|
||||
guard let image else {
|
||||
print("image pull failed")
|
||||
Application.exit(withError: POSIXError(.EACCES))
|
||||
}
|
||||
|
||||
var duration = ContinuousClock.now - startTime
|
||||
print("Image pull took: \(duration)\n")
|
||||
|
||||
guard let unpackPath else {
|
||||
return
|
||||
}
|
||||
guard !FileManager.default.fileExists(atPath: unpackPath) else {
|
||||
throw ContainerizationError(.exists, message: "directory already exists at \(unpackPath)")
|
||||
}
|
||||
let unpackUrl = URL(filePath: unpackPath)
|
||||
try FileManager.default.createDirectory(at: unpackUrl, withIntermediateDirectories: true)
|
||||
|
||||
let unpacker = EXT4Unpacker.init(blockSizeInBytes: 2.gib())
|
||||
|
||||
startTime = ContinuousClock.now
|
||||
if let platform {
|
||||
let name = platform.description.replacingOccurrences(of: "/", with: "-")
|
||||
let _ = try await unpacker.unpack(image, for: platform, at: unpackUrl.appending(component: name))
|
||||
} else {
|
||||
for descriptor in try await image.index().manifests {
|
||||
if let referenceType = descriptor.annotations?["vnd.docker.reference.type"], referenceType == "attestation-manifest" {
|
||||
continue
|
||||
}
|
||||
guard let descPlatform = descriptor.platform else {
|
||||
continue
|
||||
}
|
||||
let name = descPlatform.description.replacingOccurrences(of: "/", with: "-")
|
||||
let _ = try await unpacker.unpack(image, for: descPlatform, at: unpackUrl.appending(component: name))
|
||||
print("created snapshot for platform \(descPlatform.description)")
|
||||
}
|
||||
}
|
||||
duration = ContinuousClock.now - startTime
|
||||
print("\nUnpacking took: \(duration)")
|
||||
}
|
||||
}
|
||||
|
||||
struct Push: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "push",
|
||||
abstract: "Push an image to a remote registry"
|
||||
)
|
||||
|
||||
@Option(help: "Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'") var platformString: String?
|
||||
|
||||
@Flag(help: "Push via plain text http") var http: Bool = false
|
||||
|
||||
@Argument var ref: String
|
||||
|
||||
func run() async throws {
|
||||
let imageStore = Application.imageStore
|
||||
let platform: Platform? = try {
|
||||
if let platformString {
|
||||
return try Platform(from: platformString)
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
|
||||
let reference = try Reference.parse(ref)
|
||||
reference.normalize()
|
||||
let normalizedReference = reference.description
|
||||
if normalizedReference != ref {
|
||||
print("Reference resolved to \(reference.description)")
|
||||
}
|
||||
|
||||
try await Images.withAuthentication(ref: normalizedReference) { auth in
|
||||
try await imageStore.push(reference: normalizedReference, platform: platform, insecure: http, auth: auth)
|
||||
}
|
||||
print("image pushed")
|
||||
}
|
||||
}
|
||||
|
||||
struct Save: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "save",
|
||||
abstract: "Save one or more images to a tar archive"
|
||||
)
|
||||
|
||||
@Option(help: "Platform string in the form 'os/arch/variant'. Example 'linux/arm64/v8', 'linux/amd64'") var platform: String?
|
||||
|
||||
@Option(name: .shortAndLong, help: "Path to tar archive")
|
||||
var output: String
|
||||
|
||||
@Argument var reference: [String]
|
||||
|
||||
func run() async throws {
|
||||
var p: Platform? = nil
|
||||
if let platform {
|
||||
p = try Platform(from: platform)
|
||||
}
|
||||
let store = Application.imageStore
|
||||
let tempDir = FileManager.default.uniqueTemporaryDirectory()
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: tempDir)
|
||||
}
|
||||
try await store.save(references: reference, out: tempDir, platform: p)
|
||||
let writer = try ArchiveWriter(format: .pax, filter: .none, file: URL(filePath: output))
|
||||
try writer.archiveDirectory(tempDir)
|
||||
try writer.finishEncoding()
|
||||
print("image exported")
|
||||
}
|
||||
}
|
||||
|
||||
struct Load: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "load",
|
||||
abstract: "Load one or more images from a tar archive"
|
||||
)
|
||||
|
||||
@Option(name: .shortAndLong, help: "Path to tar archive")
|
||||
var input: String
|
||||
|
||||
func run() async throws {
|
||||
let store = Application.imageStore
|
||||
let tarFile = URL(fileURLWithPath: input)
|
||||
let reader = try ArchiveReader(file: tarFile.absoluteURL)
|
||||
let tempDir = FileManager.default.uniqueTemporaryDirectory()
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: tempDir)
|
||||
}
|
||||
let rejectedPaths = try reader.extractContents(to: tempDir)
|
||||
let imported = try await store.load(from: tempDir)
|
||||
for image in imported {
|
||||
print("imported \(image.reference)")
|
||||
}
|
||||
for rejectedPath in rejectedPaths {
|
||||
print("warning: skipped image archive member \(rejectedPath)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static func withAuthentication<T>(
|
||||
ref: String, _ body: @Sendable @escaping (_ auth: Authentication?) async throws -> T?
|
||||
) async throws -> T? {
|
||||
var authentication: Authentication?
|
||||
let ref = try Reference.parse(ref)
|
||||
guard let host = ref.resolvedDomain else {
|
||||
throw ContainerizationError(.invalidArgument, message: "no host specified in image reference")
|
||||
}
|
||||
authentication = Self.authenticationFromEnv(host: host)
|
||||
if let authentication {
|
||||
return try await body(authentication)
|
||||
}
|
||||
let keychain = KeychainHelper(securityDomain: Application.keychainID)
|
||||
authentication = try? keychain.lookup(hostname: host)
|
||||
return try await body(authentication)
|
||||
}
|
||||
|
||||
private static func authenticationFromEnv(host: String) -> Authentication? {
|
||||
let env = ProcessInfo.processInfo.environment
|
||||
guard env["REGISTRY_HOST"] == host else {
|
||||
return nil
|
||||
}
|
||||
guard let user = env["REGISTRY_USERNAME"], let password = env["REGISTRY_TOKEN"] else {
|
||||
return nil
|
||||
}
|
||||
return BasicAuthentication(username: user, password: password)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,81 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import Foundation
|
||||
|
||||
extension Application {
|
||||
struct KernelCommand: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "kernel",
|
||||
abstract: "Manage kernel images",
|
||||
subcommands: [
|
||||
Create.self
|
||||
]
|
||||
)
|
||||
|
||||
struct Create: AsyncParsableCommand {
|
||||
@Option(name: .shortAndLong, help: "Name for the kernel image")
|
||||
var name: String
|
||||
|
||||
@Option(name: .long, help: "Labels to add to the built image of the form <key1>=<value1>, [<key2>=<value2>,...]")
|
||||
var labels: [String] = []
|
||||
|
||||
@Argument var kernels: [String]
|
||||
|
||||
func run() async throws {
|
||||
let imageStore = Application.imageStore
|
||||
let contentStore = Application.contentStore
|
||||
let labels = Application.parseKeyValuePairs(from: labels)
|
||||
let binaries = try parseBinaries()
|
||||
_ = try await KernelImage.create(
|
||||
reference: name,
|
||||
binaries: binaries,
|
||||
labels: labels,
|
||||
imageStore: imageStore,
|
||||
contentStore: contentStore
|
||||
)
|
||||
}
|
||||
|
||||
func parseBinaries() throws -> [Kernel] {
|
||||
var binaries = [Kernel]()
|
||||
for rawBinary in kernels {
|
||||
let parts = rawBinary.split(separator: ":")
|
||||
guard parts.count == 2 else {
|
||||
throw "invalid binary format: \(rawBinary)"
|
||||
}
|
||||
let platform: SystemPlatform
|
||||
switch parts[1] {
|
||||
case "arm64":
|
||||
platform = .linuxArm
|
||||
case "amd64":
|
||||
platform = .linuxAmd
|
||||
default:
|
||||
fatalError("unsupported platform \(parts[1])")
|
||||
}
|
||||
binaries.append(
|
||||
.init(
|
||||
path: URL(fileURLWithPath: String(parts[0])),
|
||||
platform: platform
|
||||
)
|
||||
)
|
||||
}
|
||||
return binaries
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import ContainerizationError
|
||||
import ContainerizationExtras
|
||||
import ContainerizationOCI
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
extension Application {
|
||||
struct Login: AsyncParsableCommand {
|
||||
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "login",
|
||||
abstract: "Login to a registry"
|
||||
)
|
||||
|
||||
@OptionGroup() var application: Application
|
||||
|
||||
@Option(name: .shortAndLong, help: "Username")
|
||||
var username: String = ""
|
||||
|
||||
@Flag(help: "Take the password from stdin")
|
||||
var passwordStdin: Bool = false
|
||||
|
||||
@Argument(help: "Registry server name")
|
||||
var server: String
|
||||
|
||||
@Flag(help: "Use plain text http to authenticate") var http: Bool = false
|
||||
|
||||
func run() async throws {
|
||||
var username = self.username
|
||||
var password = ""
|
||||
if passwordStdin {
|
||||
if username == "" {
|
||||
throw ContainerizationError(.invalidArgument, message: "must provide --username with --password-stdin")
|
||||
}
|
||||
guard let passwordData = try FileHandle.standardInput.readToEnd() else {
|
||||
throw ContainerizationError(.invalidArgument, message: "failed to read password from stdin")
|
||||
}
|
||||
password = String(decoding: passwordData, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
}
|
||||
let keychain = KeychainHelper(securityDomain: Application.keychainID)
|
||||
if username == "" {
|
||||
username = try keychain.userPrompt(hostname: server)
|
||||
}
|
||||
if password == "" {
|
||||
password = try keychain.passwordPrompt()
|
||||
print()
|
||||
}
|
||||
|
||||
let server = Reference.resolveDomain(domain: self.server)
|
||||
let scheme = http ? "http" : "https"
|
||||
let client = RegistryClient(
|
||||
host: server,
|
||||
scheme: scheme,
|
||||
authentication: BasicAuthentication(username: username, password: password),
|
||||
retryOptions: .init(
|
||||
maxRetries: 10,
|
||||
retryInterval: 300_000_000,
|
||||
shouldRetry: ({ response in
|
||||
response.status.code >= 500
|
||||
})
|
||||
),
|
||||
tlsConfiguration: TLSUtils.makeEnvironmentAwareTLSConfiguration(),
|
||||
)
|
||||
try await client.ping()
|
||||
try keychain.save(hostname: server, username: username, password: password)
|
||||
print("Login succeeded")
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,180 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import ContainerizationArchive
|
||||
import ContainerizationEXT4
|
||||
import ContainerizationError
|
||||
import ContainerizationOCI
|
||||
import ContainerizationOS
|
||||
import Foundation
|
||||
|
||||
extension Application {
|
||||
struct Rootfs: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "rootfs",
|
||||
abstract: "Manage the root filesystem for a container",
|
||||
subcommands: [
|
||||
Create.self
|
||||
]
|
||||
)
|
||||
|
||||
struct Create: AsyncParsableCommand {
|
||||
@Option(name: [.short, .customLong("add-file")], help: "Additional file to add (format src-path:dst-path)")
|
||||
var addFiles: [String] = []
|
||||
|
||||
@Option(name: .customLong("ext4"), help: "The path to an ext4 image to create.")
|
||||
var ext4File: String?
|
||||
|
||||
@Option(name: .customLong("image"), help: "The name of the image to produce.")
|
||||
var imageName: String?
|
||||
|
||||
@Option(name: .customLong("label"), help: "Label to add to the image (format: key=value)")
|
||||
var labels: [String] = []
|
||||
|
||||
@Option(name: .long, help: "Platform of the built binaries being packaged into the block")
|
||||
var platformString: String = Platform.current.description
|
||||
|
||||
@Option(name: .long, help: "Path to vmexec")
|
||||
var vmexec: String
|
||||
|
||||
@Option(name: .long, help: "Path to vminitd")
|
||||
var vminitd: String
|
||||
|
||||
@Option(name: .long, help: "Path to OCI runtime")
|
||||
var ociRuntime: String?
|
||||
|
||||
// The path where the intermediate tar archive is created.
|
||||
@Argument var tarPath: String
|
||||
|
||||
private static let directories = [
|
||||
"bin",
|
||||
"sbin",
|
||||
"dev",
|
||||
"sys",
|
||||
"proc/self", // hack for swift init's booting
|
||||
"run",
|
||||
"tmp",
|
||||
"mnt",
|
||||
"var",
|
||||
]
|
||||
|
||||
func run() async throws {
|
||||
let path = URL(filePath: self.tarPath)
|
||||
try await writeArchive(path: path)
|
||||
|
||||
if let image = self.imageName {
|
||||
print("creating initfs image \(image)...")
|
||||
try await outputImage(
|
||||
path: path,
|
||||
reference: image
|
||||
)
|
||||
}
|
||||
|
||||
if let ext4Path = self.ext4File {
|
||||
print("creating initfs ext4 image at \(ext4Path)...")
|
||||
try await outputExt4(
|
||||
archive: path,
|
||||
to: URL(filePath: ext4Path)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func outputExt4(archive: URL, to path: URL) async throws {
|
||||
let unpacker = EXT4Unpacker(blockSizeInBytes: 256.mib())
|
||||
try await unpacker.unpack(archive: archive, compression: .gzip, at: path)
|
||||
}
|
||||
|
||||
private func outputImage(path: URL, reference: String) async throws {
|
||||
let p = try Platform(from: platformString)
|
||||
let parsedLabels = Application.parseKeyValuePairs(from: labels)
|
||||
_ = try await InitImage.create(
|
||||
reference: reference,
|
||||
rootfs: path,
|
||||
platform: p,
|
||||
labels: parsedLabels,
|
||||
imageStore: Application.imageStore,
|
||||
contentStore: Application.contentStore
|
||||
)
|
||||
}
|
||||
|
||||
private func writeArchive(path: URL) async throws {
|
||||
let writer = try ArchiveWriter(
|
||||
format: .pax,
|
||||
filter: .gzip,
|
||||
file: path,
|
||||
)
|
||||
let ts = Date()
|
||||
let entry = WriteEntry()
|
||||
entry.permissions = 0o755
|
||||
entry.modificationDate = ts
|
||||
entry.creationDate = ts
|
||||
entry.group = 0
|
||||
entry.owner = 0
|
||||
entry.fileType = .directory
|
||||
|
||||
// create the initial directory structure.
|
||||
for dir in Self.directories {
|
||||
entry.path = dir
|
||||
try writer.writeEntry(entry: entry, data: nil)
|
||||
}
|
||||
|
||||
entry.fileType = .regular
|
||||
entry.path = "sbin/vminitd"
|
||||
|
||||
var src = URL(fileURLWithPath: vminitd)
|
||||
var data = try Data(contentsOf: src)
|
||||
entry.size = Int64(data.count)
|
||||
try writer.writeEntry(entry: entry, data: data)
|
||||
|
||||
src = URL(fileURLWithPath: vmexec)
|
||||
data = try Data(contentsOf: src)
|
||||
entry.path = "sbin/vmexec"
|
||||
entry.size = Int64(data.count)
|
||||
try writer.writeEntry(entry: entry, data: data)
|
||||
|
||||
if let ociRuntimePath = self.ociRuntime {
|
||||
src = URL(fileURLWithPath: ociRuntimePath)
|
||||
let fileName = src.lastPathComponent
|
||||
data = try Data(contentsOf: src)
|
||||
entry.path = "sbin/\(fileName)"
|
||||
entry.size = Int64(data.count)
|
||||
try writer.writeEntry(entry: entry, data: data)
|
||||
}
|
||||
|
||||
for addFile in addFiles {
|
||||
let paths = addFile.components(separatedBy: ":")
|
||||
guard paths.count == 2 else {
|
||||
throw ContainerizationError(.invalidArgument, message: "use src-path:dst-path for --add-file")
|
||||
}
|
||||
src = URL(fileURLWithPath: paths[0])
|
||||
data = try Data(contentsOf: src)
|
||||
entry.path = paths[1]
|
||||
entry.size = Int64(data.count)
|
||||
try writer.writeEntry(entry: entry, data: data)
|
||||
}
|
||||
|
||||
entry.fileType = .symbolicLink
|
||||
entry.path = "proc/self/exe"
|
||||
entry.symlinkTarget = "sbin/vminitd"
|
||||
entry.size = nil
|
||||
try writer.writeEntry(entry: entry, data: nil)
|
||||
try writer.finishEncoding()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import ContainerizationError
|
||||
import ContainerizationExtras
|
||||
import ContainerizationOCI
|
||||
import ContainerizationOS
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
extension Application {
|
||||
struct Run: AsyncParsableCommand {
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "run",
|
||||
abstract: "Run a container"
|
||||
)
|
||||
|
||||
@Option(name: [.customLong("image"), .customShort("i")], help: "Image reference to base the container on")
|
||||
var imageReference: String = "docker.io/library/alpine:3.16"
|
||||
|
||||
@Option(name: .long, help: "id for the container")
|
||||
var id: String = "cctl"
|
||||
|
||||
@Option(name: [.customLong("cpus"), .customShort("c")], help: "Number of CPUs to allocate to the container")
|
||||
var cpus: Int = 2
|
||||
|
||||
@Option(name: [.customLong("memory"), .customShort("m")], help: "Amount of memory in megabytes")
|
||||
var memory: UInt64 = 1024
|
||||
|
||||
@Option(name: .customLong("fs-size"), help: "The size to create the block filesystem as")
|
||||
var fsSizeInMB: UInt64 = 2048
|
||||
|
||||
@Flag(name: .customLong("rosetta"), help: "Enable rosetta x64 emulation")
|
||||
var rosetta = false
|
||||
|
||||
@Option(name: .customLong("mount"), help: "Directory to share into the container (Example: /foo:/bar)")
|
||||
var mounts: [String] = []
|
||||
|
||||
@Option(name: .customLong("ns"), help: "Nameserver addresses")
|
||||
var nameservers: [String] = []
|
||||
|
||||
@Option(name: .long, help: "Path to OCI runtime to use for spawning the container")
|
||||
var ociRuntimePath: String?
|
||||
|
||||
@Flag(name: .long, help: "Make rootfs readonly")
|
||||
var readOnly: Bool = false
|
||||
|
||||
@Flag(name: .long, help: "Run with an init process for signal forwarding and zombie reaping")
|
||||
var `init`: Bool = false
|
||||
|
||||
@Option(
|
||||
name: [.customLong("kernel"), .customShort("k")], help: "Kernel binary path", completion: .file(),
|
||||
transform: { str in
|
||||
URL(fileURLWithPath: str, relativeTo: .currentDirectory()).absoluteURL.path(percentEncoded: false)
|
||||
})
|
||||
public var kernel: String
|
||||
|
||||
@Option(name: .long, help: "Current working directory")
|
||||
var cwd: String = "/"
|
||||
|
||||
@Argument(parsing: .captureForPassthrough)
|
||||
var arguments: [String] = ["/bin/sh"]
|
||||
|
||||
func run() async throws {
|
||||
let kernel = Kernel(
|
||||
path: URL(fileURLWithPath: kernel),
|
||||
platform: .linuxArm
|
||||
)
|
||||
|
||||
// Choose network implementation based on macOS version
|
||||
let network: Network?
|
||||
if #available(macOS 26, *) {
|
||||
network = try VmnetNetwork()
|
||||
} else {
|
||||
network = nil
|
||||
}
|
||||
|
||||
var manager = try await ContainerManager(
|
||||
kernel: kernel,
|
||||
initfsReference: "vminit:latest",
|
||||
network: network,
|
||||
rosetta: rosetta
|
||||
)
|
||||
let sigwinchStream = AsyncSignalHandler.create(notify: [SIGWINCH])
|
||||
|
||||
let current = try Terminal.current
|
||||
try current.setraw()
|
||||
defer { current.tryReset() }
|
||||
|
||||
let container = try await manager.create(
|
||||
id,
|
||||
reference: imageReference,
|
||||
rootfsSizeInBytes: fsSizeInMB.mib(),
|
||||
readOnly: readOnly,
|
||||
networking: true
|
||||
) { config in
|
||||
config.cpus = cpus
|
||||
config.memoryInBytes = memory.mib()
|
||||
config.process.setTerminalIO(terminal: current)
|
||||
config.process.arguments = arguments
|
||||
config.process.workingDirectory = cwd
|
||||
config.process.capabilities = .allCapabilities
|
||||
|
||||
for mount in self.mounts {
|
||||
let paths = mount.split(separator: ":")
|
||||
if paths.count != 2 {
|
||||
throw ContainerizationError(
|
||||
.invalidArgument,
|
||||
message: "incorrect mount format detected: \(mount)"
|
||||
)
|
||||
}
|
||||
let host = String(paths[0])
|
||||
let guest = String(paths[1])
|
||||
let czMount = Containerization.Mount.share(
|
||||
source: host,
|
||||
destination: guest
|
||||
)
|
||||
config.mounts.append(czMount)
|
||||
}
|
||||
|
||||
var hosts = Hosts.default
|
||||
if !nameservers.isEmpty {
|
||||
if #available(macOS 26, *) {
|
||||
config.dns = DNS(nameservers: nameservers)
|
||||
} else {
|
||||
print("Warning: Networking not supported on macOS < 26, ignoring DNS configuration")
|
||||
}
|
||||
}
|
||||
|
||||
// Add host entry for the container using just the IP (not CIDR)
|
||||
if #available(macOS 26, *), !config.interfaces.isEmpty {
|
||||
let interface = config.interfaces[0]
|
||||
hosts.entries.append(
|
||||
Hosts.Entry(
|
||||
ipAddress: interface.ipv4Address.address.description,
|
||||
hostnames: [id]
|
||||
))
|
||||
}
|
||||
|
||||
config.hosts = hosts
|
||||
if let ociRuntimePath {
|
||||
config.ociRuntimePath = ociRuntimePath
|
||||
config.mounts = LinuxContainer.defaultOCIMounts()
|
||||
}
|
||||
|
||||
config.useInit = self.`init`
|
||||
}
|
||||
|
||||
defer {
|
||||
try? manager.delete(id)
|
||||
}
|
||||
|
||||
try await container.create()
|
||||
try await container.start()
|
||||
|
||||
// Resize the containers pty to the current terminal window.
|
||||
try? await container.resize(to: try current.size)
|
||||
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
group.addTask {
|
||||
for await _ in sigwinchStream.signals {
|
||||
try await container.resize(to: try current.size)
|
||||
}
|
||||
}
|
||||
|
||||
try await container.wait()
|
||||
group.cancelAll()
|
||||
|
||||
try await container.stop()
|
||||
}
|
||||
}
|
||||
|
||||
private static let appRoot: URL = {
|
||||
FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first!
|
||||
.appendingPathComponent("com.apple.containerization")
|
||||
}()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,53 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import Containerization
|
||||
import ContainerizationError
|
||||
import ContainerizationOCI
|
||||
import Foundation
|
||||
|
||||
extension Application {
|
||||
static func fetchImage(reference: String, store: ImageStore) async throws -> Containerization.Image {
|
||||
do {
|
||||
return try await store.get(reference: reference)
|
||||
} catch let error as ContainerizationError {
|
||||
if error.code == .notFound {
|
||||
return try await store.pull(reference: reference)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
static func parseKeyValuePairs(from items: [String]) -> [String: String] {
|
||||
var parsedLabels: [String: String] = [:]
|
||||
for item in items {
|
||||
let parts = item.split(separator: "=", maxSplits: 1)
|
||||
guard parts.count == 2 else {
|
||||
continue
|
||||
}
|
||||
let key = String(parts[0])
|
||||
let val = String(parts[1])
|
||||
parsedLabels[key] = val
|
||||
}
|
||||
return parsedLabels
|
||||
}
|
||||
}
|
||||
|
||||
extension ContainerizationOCI.Platform {
|
||||
static var arm64: ContainerizationOCI.Platform {
|
||||
.init(arch: "arm64", os: "linux", variant: "v8")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
// Copyright © 2025-2026 Apple Inc. and the Containerization project authors.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import ArgumentParser
|
||||
import Containerization
|
||||
import ContainerizationOCI
|
||||
import Foundation
|
||||
import Logging
|
||||
|
||||
let log = {
|
||||
LoggingSystem.bootstrap(StreamLogHandler.standardError)
|
||||
var log = Logger(label: "com.apple.containerization")
|
||||
log.logLevel = .debug
|
||||
return log
|
||||
}()
|
||||
|
||||
@main
|
||||
struct Application: AsyncParsableCommand {
|
||||
static let keychainID = "com.apple.containerization"
|
||||
static let appRoot: URL = {
|
||||
FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first!
|
||||
.appendingPathComponent("com.apple.containerization")
|
||||
}()
|
||||
|
||||
private static let _contentStore: ContentStore = {
|
||||
try! LocalContentStore(path: appRoot.appendingPathComponent("content"))
|
||||
}()
|
||||
|
||||
private static let _imageStore: ImageStore = {
|
||||
try! ImageStore(
|
||||
path: appRoot,
|
||||
contentStore: contentStore
|
||||
)
|
||||
}()
|
||||
|
||||
static var imageStore: ImageStore {
|
||||
_imageStore
|
||||
}
|
||||
|
||||
static var contentStore: ContentStore {
|
||||
_contentStore
|
||||
}
|
||||
|
||||
static let configuration = CommandConfiguration(
|
||||
commandName: "cctl",
|
||||
abstract: "Utility CLI for Containerization",
|
||||
version: "2.0.0",
|
||||
subcommands: {
|
||||
var commands: [any ParsableCommand.Type] = [
|
||||
Rootfs.self
|
||||
]
|
||||
#if os(macOS)
|
||||
commands += [
|
||||
Images.self,
|
||||
Login.self,
|
||||
Run.self,
|
||||
]
|
||||
#endif
|
||||
return commands
|
||||
}()
|
||||
)
|
||||
}
|
||||
|
||||
extension String {
|
||||
var absoluteURL: URL {
|
||||
URL(fileURLWithPath: self).absoluteURL
|
||||
}
|
||||
}
|
||||
|
||||
extension String: Swift.Error {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user