Commit Graph
547 Commits
Author SHA1 Message Date
Aditya Ramani d55cc188ce Allow setting log level for vminitd (#772)
The `--log-level` option when running the agent sub-command for vminitd
was being silently ignored cause of the way the agent is being run. As a
workaround we need to read `/proc/self/cmdline` to get the right args
2026-06-16 18:04:31 -07:00
Mojtaba HosseiniandJ Logan 7e2ae5a170 docs: fix traversal in a public method's documentation (#770)
Seems like a typo.
The change only affected a comment and does not disturb the code at all
(backward compatible).

Co-authored-by: J Logan <john_logan@apple.com>
2026-06-16 12:41:46 -07:00
Michael Crosby ddd19a61a8 add x86 kernel config (#765)
Add x86 kernel config and build scripts.

Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-06-16 12:47:20 -04:00
J Logan e29657b86e Pin macOS CI builds to Swift 6.3 for now. (#771)
- CI runners moved to the Xcode developer beta as the default, but macOS
builds are failing with a conflicting options error for
`-warnings-as-errors` and `-suppress-warnings`.
2026-06-16 11:44:27 -04:00
Vitor Hugo 4f6df44c2a fix(Platform): make arm64 nil-variant and v8 hash identically (#764)
## Summary

`Platform.==` treats `arm64` with `nil` variant as equal to `arm64/v8`,
but `hash(into:)` used `description` which serializes them differently
(`linux/arm64` vs `linux/arm64/v8`). This violates the `Hashable`
contract — equal values must produce the same hash.

### Root cause

```swift
// == returns true for these two
let a = Platform(arch: "arm64", os: "linux", variant: nil)
let b = Platform(arch: "arm64", os: "linux", variant: "v8")
a == b // true ✓

// but hash was different — broken
a.hashValue == b.hashValue // false ✗ (before this fix)
```

This mismatch caused `Set<Platform>` and `Dictionary<Platform, ...>`
lookups to silently miss entries when one platform was decoded from JSON
(no `variant` field in the manifest) and another was created via
`Platform(from:)` or `Platform.current` (which both set `variant =
"v8"`).

### Practical consequence

In `apple/container`, this manifests as inconsistent platform-string
normalization across stages of a single `container build` — some stages
log `linux/arm64`, others `linux/arm64/v8` — which can cause `COPY
--from=<stage>` to fail to resolve the source stage under concurrent
builds. See apple/container#1542.

### Fix

`hash(into:)` now normalizes `arm64` with `nil` variant to `"v8"` before
hashing, matching the existing `==` behavior.
2026-06-16 10:06:06 -04:00
Kathryn Baldauf 1437c67f5a Update github actions to use SHA versions (#763)
Related to https://github.com/apple/container/pull/1649. This PR updates
the GitHub workflows to ensure all imported actions are referenced by
commit SHA.

Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2026-06-04 15:08:22 -07:00
Danny Canter 9275f365dd [Experimental] Add Sandboxy binary (#607)
Sandboxy is an example tool to run isolated coding agents.
2026-06-03 12:27:49 -04:00
e1e31b7ae9 add IPv6 support (#752)
Extends the network plumbing to support per-interface IPv6 address
configuration.
The `Interface` protocol supports `ipv6Address` and `ipv6Gateway`.
The agent's networking RPCs carry per-family fields via new
`InterfaceAddress`, `LinkRoute`, and `DefaultRoute` types in
`ContainerizationExtras`.
`NetlinkSession` adds IPv6 methods for address and route operations.

---------

Co-authored-by: michael_crosby <michael_crosby@apple.com>
Co-authored-by: Michael Crosby <crosbymichael@gmail.com>
2026-06-03 12:07:20 -04:00
Yibo Zhuang 72043f90ac ContentStore: Fix totalAllocatedSize on Linux (#761)
`.totalFileAllocatedSizeKey` returns nil for directories on Darwin but
on Linux it returns `st_blocks * st_blksize` (4 KB each) in Foundation.
The empty-store test summed three directory inodes on Linux and failed
with `#expect(size == 0)`. This change adds filter on the enumerator to
regular files only so the totals are content-only and will work for both
Darwin and Linux.
2026-06-01 17:06:09 -07:00
Raj a2a1add6c7 Add totalAllocatedSize to ContentStore (#760)
This PR adds `totalAllocatedSize()` to the `ContentStore` protocol so it
can be used to get the on-disk footprint without reaching past the
abstraction. `LocalContentStore` implements it by walking its base path,
covering both committed blobs and active ingest sessions.
2026-06-01 14:22:04 -07:00
Danny Canter 6cb66583e2 Stats: Expose more memory stats (#758) 2026-06-01 11:52:53 -07:00
Danny Canter b1e779eb2a Cgroup2: Add ability to filter stats (#757) 2026-06-01 11:51:50 -07:00
mlsad3 fd820380a6 Fix head-of-line blocking and resource leak in BidirectionalRelay (#713)
- Closes #712.
- Replace synchronous `write()` calls in
  `BidirectionalRelay` with non-blocking I/O
  and `DispatchSourceWrite` backpressure
  handling. Under concurrent vsock proxy load,
  a single blocked write on the shared serial
  dispatch queue would freeze all relay
  connections permanently, including unrelated
  new connections.
- Set relay file descriptors to `O_NONBLOCK`
  and handle `EAGAIN` by suspending reads and
  installing a write source to drain pending data.
- Give each `BidirectionalRelay` its own serial queue
  instead of sharing one from `UnixSocketRelayManager`,
  eliminating cross-connection blocking.
- Resume suspended read sources before cancelling
  in `stop()` — GCD does not deliver cancel handlers
  on suspended dispatch sources, which caused file
  descriptor and memory leaks on teardown under
  backpressure.
- Guard-unwrap `buf.baseAddress` in
  `drainPendingWrite`.
2026-06-01 10:33:36 -07:00
Saehej Kang 2550dd49f1 [os]: add FilePathOps utility type + initial absolute path function (#751)
- Closes #744
- Adds the initial `FilePathOps` utility type
- Adds the `absolutePath` implementation
- Adds the `FilePathOpsTests` file and initial test cases
2026-05-27 08:27:28 -07:00
pickle-RickAandpickle-RickA 565e8a3e02 Improve documentation formatting and consistency (#633)
Small documentation improvements for better consistency:

- Fixed capitalization (url → URL) in kernel README
- Added bash syntax highlighting to code block in lab.md  
- Improved formatting consistency in ctr-example README (added colon +
code fence)

Co-authored-by: pickle-RickA <273219719+pickle-RickA@users.noreply.github.com>
2026-05-27 00:23:39 -07:00
Aditya Singh d09a1026b7 Fix incorrect byte shift in IPv4Address byte-array initializer (#754)
The `IPv4Address(_ bytes: [UInt8])` initializer in
ContainerizationExtras shifts the third octet by 16 bits instead of 8:

```swift
self.value =
    (UInt32(bytes[0]) << 24)
    | (UInt32(bytes[1]) << 16)
    | (UInt32(bytes[2]) << 16)   // should be << 8
    | UInt32(bytes[3])
```

Because `bytes[2]` lands in the same bit range as `bytes[1]`, the second
octet gets corrupted by the OR, the third octet is dropped, and bits 8
through 15 are always left zero. Concretely, decoding `[192, 168, 1, 1]`
yields `192.169.0.1` instead of `192.168.1.1`, and `[18, 52, 86, 120]`
yields `18.118.0.120` instead of `18.52.86.120`.

This went unnoticed because the `bytes` computed property getter uses
the correct `>> 8` for the third octet, but there was no test exercising
the byte-array initializer, so the encode and decode paths were never
checked against each other. The sibling `IPv6Address(_ bytes:)`
initializer uses the correct descending shifts (`<< 120, << 112, ... <<
8, << 0`), which is what the IPv4 version should mirror.

The fix changes the third octet shift to 8 bits so the initializer is
the exact inverse of the `bytes` property. I also added two tests to the
initializer suite: a valid-input test that asserts both the resulting
`value` and that `init(bytes).bytes == bytes` round-trips, and an
invalid-length test. The round-trip test fails on the current code and
passes with the fix.

Verification: `swift test --filter ContainerizationExtrasTests` passes
221 tests in 26 suites (the IPv4Address suite goes from 23 to 25 tests).
The new round-trip test fails before the one-line change and passes
after.

Signed-off-by: Aditya Singh <adisin650@gmail.com>
2026-05-26 13:38:05 -07:00
David Palma 25558e6b85 ImageStore: Preserve source index mediaType on push (#750)
- Closes #749.
- ExportOperation hardcoded the pushed index descriptor's
  mediaType to the OCI image index type. RegistryClient.push
  uses that descriptor's mediaType as the HTTP Content-Type
  header. When the source index was in
  Docker manifest.list.v2+json format (the common case for
  images pulled from Docker Hub and other public registries),
  the body's embedded mediaType field disagreed with the
  header, and OCI registries rejected the index PUT with
  HTTP 400 MANIFEST_INVALID.
- Use the source index's mediaType for the pushed descriptor
  so the header always matches the body. Per-architecture
  child manifests are unaffected because they were already
  pushed with their actual mediaType.
- Add a parameterized unit test for ExportOperation.export
  covering both Docker manifest.list
2026-05-21 17:48:40 -07:00
Dmitry Kovba 9205a76630 Keep CVersion in the vminitd package (#747)
Moves `CVersion` back to the `vminitd` package. This is a follow-up for
apple/containerization#742.
2026-05-20 20:17:26 -07:00
Shaurya Singh 485a1a3735 Fix missing apostrophes in Image scope-walk comment (#741)
- Grammar fix in comment.
2026-05-20 16:28:07 -07:00
J Logan d3d7d2143c Adds FileDescriptor-based enumerate(). (#746)
- Closes #745.
- Facilitates TOCTOU-safe recursion over directory contents.
- Replace FileDescriptor extensions with a static utility type to
prevent potential namespacing issues as this project and Swift evolve.
2026-05-20 15:55:29 -07:00
Dmitry Kovba c8fe3bbef9 Move the VminitdCore library to the top-level package (#742)
External Swift Package Manager consumers can only see products declared
in the top-level `Package.swift`. The `VminitdCore` library was declared
inside the `vminitd` subpackage, so it was impossible to build a custom
`vminitd` against it via a URL dependency on `containerization`. This
change moves the `VminitdCore` to the top-level `Package.swift`.
2026-05-20 15:46:32 -07:00
Simone Panico db5b5b9840 Add path resolution for CopyIn using Stat (#727)
This pull request enhances the handling of file and directory copy
operations in Linux containers, particularly by improving destination
path resolution and error handling for the `copyIn` operation with the
`Stat RPC`

This PR is needed for
[container#1190](https://github.com/apple/container/pull/1190)
2026-05-19 10:25:43 -07:00
Michael Crosby 872f601f93 add hotplug interfaces for vmms (#740)
Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-05-18 10:29:36 -07:00
jwhur f8a18e8dcd Make maxIDLength public (#734) 2026-05-11 16:31:30 -07:00
Danny Canter ece8f984b3 vminitd: Fix UDS length issue with large container IDs (#731)
Today we craft the proxied sockets we create at a path that contains the
container ID. This is normally completely fine, except if the ID is
enormous, as it can cause the UDS path to be longer than the allowed
length.
2026-05-11 15:26:31 -07:00
Danny Canter 737bd37777 LinuxContainer/LinuxPod: Add ID length restriction (#733)
I think realistically we should have a limit on this. Technically today
the ID length restriction is whatever our grpc buffer length is..

I think 64 is long enough so that folks could use an entire hex based
sha256, any uuid, and also sethostname has a length restriction of 64
anyways.
2026-05-11 14:47:20 -07:00
J Logan 3ff7321562 Set devcontainer Swift image version to 6.3.0. (#732)
- We were using Swift 6.3, which can pick up a newer version that is out
of sync of both the `.swift-version` file for the project and the Swift
SDK downloaded in the Dockerfile.
2026-05-09 17:38:24 -07:00
Dmitry Kovba e9f4ece2bb Skip comment lines when parsing the passwd and group files (#728)
Skips comment lines when parsing the `passwd` and `group` files.
2026-05-08 12:22:20 -07:00
Yibo Zhuang 03280f3952 refactor memory alignment to VZVirtualMachineInstance (#725)
Move the MiB rounding from LinuxContainer into
`VZVirtualMachineInstance`, so all callers are covered in one place and
the alignment constraint stays with the VMM layer that owns it.

This will also ensure LinuxPod can get memory alignment for free.
2026-05-06 07:36:10 -07:00
Danny Canter 8140499b4f TerminalIO: Fix ebadf on close (#719)
The stdout and stdin IOPairs in TerminalIO share the same Terminal fd.
Closing stdin first would close the Terminal, causing stdout to read -1
from fileDescriptor and fail to unregister from epoll. This left stale
handler closures (capturing the IOPair) in ProcessSupervisor.handlers
indefinitely.

Additionally, vsock sockets created in TerminalIO.start() with
closeOnDeinit disabled were never closed if the process exited before
attach() created IOPairs.
2026-05-04 10:35:41 -07:00
Tony Coconate 9d2b5794e3 Enable CIFS/SMB kernel support in arm64 config (#681)
## Summary

Enables CIFS (SMB) filesystem support in the arm64 kernel config,
required for the SMB volume driver added in apple/container#1414.

Without this change, SMB mounts fail at runtime with `errno 19
(ENODEV)`.

## Changes

- `kernel/config-arm64`: enable `CONFIG_CIFS=y` and related options
(`CIFS_ALLOW_INSECURE_LEGACY`, `CIFS_UPCALL`, `CIFS_XATTR`,
`CIFS_POSIX`, `CIFS_DFS_UPCALL`)
2026-05-02 18:04:14 -07:00
Kathryn Baldauf c519d57609 Add unit tests for AsyncLock (#720)
These tests were requested as part of a test change in
https://github.com/apple/container/pull/1497. These tests mimic a lot of
the tests in
https://github.com/apple/containerization/blob/main/Tests/ContainerizationExtrasTests/AsyncMutexTests.swift
where possible/appropriate.

Signed-off-by: Kathryn Baldauf <k_baldauf@apple.com>
2026-05-01 16:05:49 -07:00
Danny Canter dc710a32a6 AsyncSignalHandler: Add helper to catch all signals (#722) 2026-05-01 15:02:34 -07:00
Danny Canter 57d157c82a Signal: Expose helpful helper methods (#721)
- Method to grab the signal name
- Convert macOS signal to linux equivalent
2026-05-01 14:51:40 -07:00
jwhur f2c42402e7 Refactor ArchiveWriter to expose archiving each path independently (#693)
This PR refactors `ArchiveWriter` to add an API `archive(_ paths:
base:)`. This API is used to archive the contents at each path
independently, similar to doing `tar -cvf archive.tar foo.bin
/bar/baz.txt`.
2026-04-30 18:23:47 -07:00
Sidhartha Mani df125a2300 Prevent recursion attacks in EXT4Formatter.unlink (#415)
This issue doesn't affect any of our existing products. This is a
preemptive fix for downstream consumers of EXT4.format where, in some
platforms, leading `//` in the path could get resolved into a FileTree
that looks like this

```sh
/ 
 └──  / 
 └── usr
```
2026-04-30 12:01:32 -07:00
ChengHao Yang de075fff8a Fix: bad request will remove header and retry login (#711)
If you're requesting on `/v2/` with basic auth, AWS ECR will return 400
Bad Request and won't provide `www-authenticate` information.

Retry the request after removing the Authorization header.

Continue PR #429

Fixed apple/container#847

Signed-off-by: ChengHao Yang <17496418+tico88612@users.noreply.github.com>
2026-04-29 15:29:54 -04:00
Michael CrosbyandDanny Canter b62edd2e2d make vminitd package for extensions (#708)
Signed-off-by: michael_crosby <michael_crosby@apple.com>
Co-authored-by: Danny Canter <danny_canter@apple.com>
2026-04-29 14:43:52 -04:00
Danny Canter 0e469481f5 LinuxContainer: Allow cpu/mem overhead to be configurable (#710)
If someone wanted to use a custom guest agent/guest image in general the
overhead we chose is kind of a nuisance.. This allows the values to be
configurable, and raises the default to 128, and vminitds cgroup
monitoring to 80.
2026-04-29 10:33:44 -04:00
Yibo Zhuang 6c827ee3ad Add additional NBD integration test for raw block (#707)
This change adds an additional unit test to test
attaching a raw block device to a container to ensure raw block works
without API changes. We just need to set format to none and bind mount
the raw block device to the container path
2026-04-28 14:58:15 -07:00
Yibo Zhuang 9a6f0d4c52 Add support for network block device (NBD) (#690)
This change adds support for attaching network block device (NBD) to
both LinuxContainer and LinuxPod.

For LinuxContainer, whether to use the underlying
`VZNetworkBlockDeviceStorageDeviceAttachment` is determined by the URL
of the container Mount source.

For LinuxPod, adds additional API to support pod-level volumes that can
be mounted into multiple containers. The PodVolume type provides enum to
support multiple types of volume source. LinuxContainer can reference
the pod level volume using the `Mount.sharedMount()` constructor with
the name referencing the name of the pod volume. This will allow the NBD
to be attached to the pod at the VM level and then bind-mounted into the
container.

For integration tests, added a lightweight NBD server implementation in
swift that speaks the NBD protocol to ensure there is sufficient
coverage for the changes introduced.

Apple Virtualization NBD support documentation:

https://developer.apple.com/documentation/virtualization/vznetworkblockdevicestoragedeviceattachment
2026-04-28 10:56:17 -07:00
Michael Crosby 5fef4e0e10 produce initfs.ext4 for package creation (#706)
This does not break and prevent any other asset from being produced.

Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-04-28 09:54:41 -07:00
Dmitry Kovba 3ef9976d38 Fix compilation warnings (#696)
Fix compilation warnings:

```
.../Sources/Containerization/LinuxContainer.swift:877:35: warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope [#ImplicitStrongCapture]
 851 |     /// via the `start` method.
 852 |     public func exec(_ id: String, configuration: @Sendable @escaping (inout LinuxProcessConfiguration) throws -> Void) async throws -> LinuxProcess {
 853 |         try await self.state.withLock { state in
     |                                       |- note: 'self' implicitly strongly captured here
     |                                       `- note: add 'self' as a capture list item to silence
 854 |             var startedState = try state.startedState("exec")
 855 | 
     :
 875 |                 vm: startedState.vm,
 876 |                 logger: self.logger,
 877 |                 onDelete: { [weak self] in
     |                                   |- warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope [#ImplicitStrongCapture]
     |                                   `- note: explicitly assign the capture list item to silence
 878 |                     await self?.removeProcess(id: id)
 879 |                 }

.../Sources/Containerization/LinuxContainer.swift:914:35: warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope [#ImplicitStrongCapture]
 890 |     /// via the `start` method.
 891 |     public func exec(_ id: String, configuration: LinuxProcessConfiguration) async throws -> LinuxProcess {
 892 |         try await self.state.withLock {
     |                                       |- note: 'self' implicitly strongly captured here
     |                                       `- note: add 'self' as a capture list item to silence
 893 |             var state = try $0.startedState("exec")
 894 | 
     :
 912 |                 vm: state.vm,
 913 |                 logger: self.logger,
 914 |                 onDelete: { [weak self] in
     |                                   |- warning: 'weak' ownership of capture 'self' differs from implicitly-captured strong reference in outer scope [#ImplicitStrongCapture]
     |                                   `- note: explicitly assign the capture list item to silence
 915 |                     await self?.removeProcess(id: id)
 916 |                 }

[#ImplicitStrongCapture]: <https://docs.swift.org/compiler/documentation/diagnostics/implicit-strong-capture>
```
2026-04-28 11:18:13 -04:00
Danny Canter 56f1c83a14 Rework signals usage/parsing (#704)
Replace the old platform-gated Signals helper in ContainerizationOS with
a Signal struct in Containerization. Signal provides named constants for
common signals (.kill, .term, etc.), platform-specific namespaces
(Signal.Linux for rtmin/stkflt/pwr, Signal.Darwin for emt/info), string
parsing, and ExpressibleByIntegerLiteral support.

LinuxContainer, LinuxProcess, and LinuxPod kill APIs now take Signal
instead of raw Int32.
2026-04-28 11:15:13 -04:00
jwhur b770cd2a02 Add stat RPC (#614)
Add `Stat` RPC to vminitd.

`Stat` RPC is used to stat file system objects in the VM. It accepts the
path to the object (resolved against VM root) and returns the stat
result.
2026-04-27 14:44:33 -07:00
Michael Crosby 59f599eed5 allow filter of descriptors on push (#703)
Signed-off-by: michael_crosby <michael_crosby@apple.com>
2026-04-27 16:57:20 -04:00
Danny Canter 46c8fd3269 LinuxContainer/LinuxPod: Expose withVirtualMachineInstance (#701) 2026-04-27 12:17:12 -07:00
Danny Canter 0891bf399d OCI: Change hook to hooks (#702) 2026-04-27 11:47:36 -07:00
Dmitry Kovba 41ffd07f3e Add a default route to the first interface only (#697)
Adds a default route to the first interface only.
2026-04-23 11:05:25 -04:00
Dmitry Kovba bbea928c9e Add a public constructor to HTTP2ConnectBufferingHandler.swift (#695)
Adds a public constructor to `HTTP2ConnectBufferingHandler.swift`. This
is a follow-up to https://github.com/apple/containerization/pull/694.
2026-04-21 15:57:25 -07:00