Compare commits

...
50 Commits
Author SHA1 Message Date
Nikolay Edigaryev 537f0ae5db OCI storage: unconditionally remove the old link when link()'ing (#686) 2023-12-08 17:20:49 +04:00
Fedor Korotkov 02f1ff5238 Fixed image url 2023-12-08 03:23:54 -05:00
Fedor Korotkov 9c9bcd586e Highlight AWS Marketplace availability (#683)
* Highlight AWS Marketplace availability

* Updated image

* Changed height
2023-12-08 10:44:41 +04:00
Fedor Korotkov 60f0eac7a8 Cache only non-empty archives (#685)
Fixes #684. But I'm not sure how it got into this state in the first place. `URLSession.shared.data` should've throw.
2023-12-08 10:43:43 +04:00
Andrew Malchuk 35377a3475 Fix the filesystem corruption on Linux VMs (#675)
* Use NVMe drive, cached mode and full synchronization mode on Linux

* Inline getting storage device attachment
2023-12-01 15:56:58 +00:00
Nikolay Edigaryev dda4e91a91 Document Buildkite Tart Plugin (#677)
* Document Buildkite Tart Plugin

* Fix cropped screenshot
2023-12-01 15:35:45 +00:00
Nikolay Edigaryev ac5f794e6d tart delete: prevent the deletion of running VMs (#676)
And introduce a VMDirectory.lock() method to avoid duplication of
the PIDLock(lockURL: vmDir.configURL) snippet.
2023-12-01 09:33:01 -05:00
Nikolay Edigaryev 5bcbc77249 Document available VM images on the website (#674)
* Document available VM images on the website

* Fix indents
2023-11-28 16:31:39 +00:00
Fedor Korotkov bf03873c8d Validate that a disk is not amd64 (#673)
To improve UX for cases like #672
2023-11-28 14:55:34 +00:00
Nikolay Edigaryev bad37b129c DiskV2: write layers sparsely to avoid unnecessary disk usage (#671) 2023-11-27 23:27:07 +04:00
Nikolay Edigaryev 0f47cca746 MAC address resolver: skip expired leases (#669) 2023-11-27 10:12:36 -05:00
Fedor Korotkov d70eca4484 Document Cirrus Runners Discounts (#663) 2023-11-22 20:00:45 +04:00
Fedor Korotkov 25887b075f Use ssh from our tap (#662)
Fixes #661
2023-11-20 20:01:57 +00:00
Simon B. Støvring 8c011623be Adds Shape logo to README (#658) 2023-11-15 14:51:10 +00:00
Fedor Korotkov 2dccdfb306 Document ECR Public Mirror (#656)
Fixes https://github.com/cirruslabs/tart/discussions/652
2023-11-13 18:18:51 +00:00
Fedor KorotkovandNikolay Edigaryev aca768a838 Print put errors from Docker Helpers (#654)
* Print put errors from Docker Helpers

* Update Sources/tart/Credentials/DockerConfigCredentialsProvider.swift

Co-authored-by: Nikolay Edigaryev <edigaryev@gmail.com>

* Check output data is not empty

---------

Co-authored-by: Nikolay Edigaryev <edigaryev@gmail.com>
2023-11-10 22:44:51 +04:00
Tor Arne Vestbø 68b3557747 Hide dock icon in no graphics mode (#653)
* Package tart binary into app bundle when running via run-signed.sh

This is what happens when installing the tart application package
as built by CI. We should stay as close as possible to the install
situation during development, so that we get bug/behavior parity.

For example, an app bundle behaves differently than a standalone
executable when it comes to bringing up a Dock icon for the app.

* Set activation policy to prohibited when starting in no graphics mode

This ensures that the Dock icon is hidden.
2023-11-10 09:05:20 -05:00
Fedor Korotkov b2c923f2fe Properly enter main even loop in headless mode (#651)
Fixes #638
2023-11-09 00:05:00 +04:00
Fedor Korotkov c75009e46f Introduce --capture-system-keys flag (#650)
To allow guest to capture things like Cmd+Tab.

Fixes #636
2023-11-08 20:21:55 +04:00
Riain Condon 43e74ab769 fix docs to specify inside VM for gitlab runner (#649)
just adds specifically VM in the gitlab runner docs to avoid confusion of where the build and cache dirs are
2023-11-08 09:05:19 -05:00
Fedor Korotkov 1338864ed6 Don't install Sentry CLI via brew (#648)
Seems it installas 1.x version instead of 2.x. Sentry's documentation [recommends to use their script](https://docs.sentry.io/product/cli/installation/?original_referrer=https%3A%2F%2Fwww.google.com%2F#automatic-installation).
2023-11-07 16:23:20 +00:00
Nikolay Edigaryev 70040b633c Introduce AuthenticationKeeper actor to serialize authn modification (#647) 2023-11-06 14:58:23 -05:00
Nikolay Edigaryev f4bc02d175 DiskV2.push(): map disk into memory to avoid large allocations (#645) 2023-11-03 17:13:10 +04:00
Fedor Korotkov 6c24aa639a [blog] New dashboard with insights into performance of Cirrus Runners (#644) 2023-11-03 12:17:40 +04:00
Nikolay Edigaryev d8b69de52d Fetcher.fetchViaFile(): use an mmap(2)-ed file, similarly to DiskV1 (#641)
* Fetcher.fetchViaFile(): use an mmap(2)-ed file, similarly to DiskV1

* No need to convert Data to Data
2023-11-01 15:00:48 +04:00
Nikolay Edigaryev c4c2bfeded tart-dev.entitlements: add "com.apple.security.get-task-allow" (#642) 2023-11-01 14:35:55 +04:00
Fedor Korotkov b95585b56b Don't forget to finalize output stream (#640)
There is a suspicion that this might leak memory
2023-11-01 12:19:11 +04:00
Fedor Korotkov 8d5574ed3f Removed usage of deprecated APIs (#628)
See https://developer.apple.com/documentation/virtualization/vzmacauxiliarystorage/3816043-init
2023-10-11 17:05:49 -04:00
Fedor Korotkov 457c2bc7db Adjusted live installation counter (#627) 2023-10-11 20:55:51 +00:00
Fedor Korotkov 4bf9bdd531 Document Tart on AWS (#625)
Fixes #581
2023-10-07 12:06:06 +04:00
Fedor Korotkov 8e9d61d5f5 Validate that a suspendable VM doesn't have shared directories (#623) 2023-10-04 20:21:45 +04:00
Fedor KorotkovandNikolay Edigaryev 71d03226fe Support mounting remote archives (#620)
* Support mounting remote archives

Allow to pass an HTTPS link instead of a local path to `tart run --dir` argument. HTTPS link should point to a gzipped Tar archive aka `*.tar.gz` file.

In this situation Tart will download an archive by the link if necessary, will cache it and will unarchive it into a temporary folder inside `$TART_HOME` to be mounted to the VM.

This use case is useful for mounting something external that updates faster than the VM itself. For example, GitHub Actions Runner installation.

* Don't use async/await APIs to prevent from deadlocks because of the MainActor thing

* Prefer cached data

* Moved comment

* Fix URLCache caching files in memory instead of on-disk (#622)

* Fix URLCache caching files in memory instead of on-disk

* Fix disk capacity typo

* Moved log

* Moved fetching logic to `DirectoryShare#createConfiguration` method

---------

Co-authored-by: Nikolay Edigaryev <edigaryev@gmail.com>
2023-10-03 23:01:29 +04:00
Nikolay Edigaryev 36dab9878d tart: bump max password characters from 256 to 1024 (#618) 2023-10-02 13:58:55 +00:00
Nikolay Edigaryev f634002813 tart run: disable console device when --suspendable is requested (#615) 2023-09-30 21:13:44 +04:00
Fedor Korotkov 8e79669afb Configure Markdown Linter (#614) 2023-09-29 03:35:17 -04:00
Fedor KorotkovandNikolay Edigaryev 2da8bc0fb5 Document XL Cirrus Runners (#613)
* Document XL Cirrus Runners

Also tried to put everything about Cirrus Runners in one place rather than having the information spreaded between https://tart.run and https://github.com/apps/cirrus-runners.

Plus updated docs to use Sonoma.

* Apply suggestions from code review

Co-authored-by: Nikolay Edigaryev <edigaryev@gmail.com>

---------

Co-authored-by: Nikolay Edigaryev <edigaryev@gmail.com>
2023-09-28 15:53:13 -04:00
Nikolay Edigaryev 2d984ba194 .cirrus.yml: add an execution_lock: for integration tests (#610)
* .cirrus.yml: add an execution_lock: for integration tests

* Use Persistent Worker's resources instead of grabbing an execution lock
2023-09-22 22:52:52 +04:00
Fedor Korotkov 50ce44c3eb Support block devices on Sonoma (#611)
* Support block devices on Sonoma

* Updated docs

* Removed unused error
2023-09-22 22:30:18 +04:00
Fedor Korotkov c9e49ceb39 Missing user
So it's an even number of them
2023-09-22 12:10:13 -04:00
Fedor Korotkov 6df50e55d8 --suspendable devices fallback on Ventura host (#605)
Fixes #604
2023-09-22 07:38:13 -04:00
Nikolay Edigaryev 1fd710d00d web: fix GitLab Runner integration link (#608)
Resolves https://github.com/cirruslabs/tart/issues/607.
2023-09-22 07:38:02 -04:00
Rui Marinho 4f6c7e79e1 Add Uphold as a Tart user (#606) 2023-09-22 07:37:02 -04:00
fedor 1afb43e85b Updated announcement link 2023-09-20 10:58:17 -04:00
Alex Clay 954cac3bee Change brew update to brew upgrade (#602) 2023-09-20 14:35:03 +00:00
Nikolay Edigaryev 3ff4fc34c6 Improved format for fast and efficient pulls from remote OCI-registry (#589)
* Improved format for fast and efficient pulls from remote OCI-registry

* Tests: introduce fileWithRandomData() helper function

* Remove useless continuation

* --concurrency should be an option, not an argument

* --v2-disk-format → --old-disk-format and use the new V2 by default

* Reduce LZ4 buffer size from 64 to 4 MiB

* --old-disk-format → --disk-format=...
2023-09-20 10:14:05 -04:00
Fedor Korotkov e118b42b1f Tart 2.0.0 blog post (#601) 2023-09-20 10:13:42 -04:00
Fedor Korotkov f823190039 Build with the release version of Xcode 15 (#600) 2023-09-19 14:34:21 +00:00
Nikolay Edigaryev 27cadc3f3b tart create --from-ipsw: do a HEAD instead of a GET first (#599) 2023-09-14 17:16:08 +00:00
Nikolay Edigaryev d4d3852745 Return exit code 2 on RuntimeError.VMDoesNotExist (#597)
* Return exit code 2 on RuntimeError.VMDoesNotExist

* Upgrade isFileNotFound() do detect underlying errors
2023-09-12 13:56:49 +04:00
Fedor Korotkov 4bb248e7b4 Support wildcards in credHelpers (#592)
* Support wildcards in `credHelpers`

With #591 `tart pull` fails when for example you have `ecr-login` set as the default `credsStore` but you try to pull our images from `ghcr.io`.

This change reverts #591 and instead supports regex in `credHelpers`. This is not supported by Docker itself but highly demanded in https://github.com/docker/cli/issues/2928

I think it's fine to support it for Tart.

Additionally this change bumps the minimum host macOS version to Ventura in order to bring `Regex`. Yes, `Regex` only supported in Swift for macOS 13+ 🤦‍♂️I think it's fine in the light of Sonoma release and Tart 2.0.0.

* Removed Monterey mentions from docs
2023-08-28 11:37:49 -04:00
63 changed files with 1425 additions and 298 deletions
+18 -13
View File
@@ -1,15 +1,16 @@
use_compute_credits: true use_compute_credits: true
env: env:
XCODE_TAG: 15-beta-5 XCODE_TAG: 15
task: task:
name: Test on Ventura name: Test on Sonoma
alias: test alias: test
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
persistent_worker: persistent_worker:
labels: labels:
name: dev-mini name: dev-mini
resources:
tart-vms: 1
test_script: test_script:
- swift test - swift test
integration_test_script: integration_test_script:
@@ -28,12 +29,19 @@ task:
path: "integration-tests/pytest-junit.xml" path: "integration-tests/pytest-junit.xml"
format: junit format: junit
task:
name: Markdown Lint
only_if: $CIRRUS_BRANCH != 'gh-pages' && changesInclude('**.md')
container:
image: node:latest
install_script: npm install -g markdownlint-cli
lint_script: markdownlint --config=docs/.markdownlint.yml docs/
task: task:
name: Lint name: Lint
alias: lint alias: lint
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
macos_instance: macos_instance:
image: ghcr.io/cirruslabs/macos-ventura-xcode:$XCODE_TAG image: ghcr.io/cirruslabs/macos-sonoma-xcode:$XCODE_TAG
lint_script: lint_script:
- swift package plugin --allow-writing-to-package-directory swiftformat --cache ignore --lint --report swiftformat.json . - swift package plugin --allow-writing-to-package-directory swiftformat --cache ignore --lint --report swiftformat.json .
always: always:
@@ -45,9 +53,8 @@ task:
only_if: $CIRRUS_TAG == '' only_if: $CIRRUS_TAG == ''
name: Build name: Build
alias: build alias: build
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
macos_instance: macos_instance:
image: ghcr.io/cirruslabs/macos-ventura-xcode:$XCODE_TAG image: ghcr.io/cirruslabs/macos-sonoma-xcode:$XCODE_TAG
build_script: swift build --product tart build_script: swift build --product tart
sign_script: codesign --sign - --entitlements Resources/tart-dev.entitlements --force .build/debug/tart sign_script: codesign --sign - --entitlements Resources/tart-dev.entitlements --force .build/debug/tart
binary_artifacts: binary_artifacts:
@@ -59,9 +66,8 @@ task:
depends_on: depends_on:
- lint - lint
- build - build
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
macos_instance: macos_instance:
image: ghcr.io/cirruslabs/macos-ventura-xcode:$XCODE_TAG image: ghcr.io/cirruslabs/macos-sonoma-xcode:$XCODE_TAG
env: env:
MACOS_CERTIFICATE: ENCRYPTED[552b9d275d1c2bdbc1bff778b104a8f9a53cbd0d59344d4b7f6d0ca3c811a5cefb97bef9ba0ef31c219cb07bdacdd2c2] MACOS_CERTIFICATE: ENCRYPTED[552b9d275d1c2bdbc1bff778b104a8f9a53cbd0d59344d4b7f6d0ca3c811a5cefb97bef9ba0ef31c219cb07bdacdd2c2]
AC_PASSWORD: ENCRYPTED[4a761023e7e06fe2eb350c8b6e8e7ca961af193cb9ba47605f25f1d353abc3142606f412e405be48fd897a78787ea8c2] AC_PASSWORD: ENCRYPTED[4a761023e7e06fe2eb350c8b6e8e7ca961af193cb9ba47605f25f1d353abc3142606f412e405be48fd897a78787ea8c2]
@@ -77,8 +83,9 @@ task:
- security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k password101 build.keychain - security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k password101 build.keychain
- xcrun notarytool store-credentials "notarytool" --apple-id "hello@cirruslabs.org" --team-id "9M2P8L4D89" --password $AC_PASSWORD - xcrun notarytool store-credentials "notarytool" --apple-id "hello@cirruslabs.org" --team-id "9M2P8L4D89" --password $AC_PASSWORD
install_script: install_script:
- brew install go goreleaser/tap/goreleaser-pro getsentry/tools/sentry-cli - brew install go goreleaser/tap/goreleaser-pro
- brew install mitchellh/gon/gon - brew install mitchellh/gon/gon
- curl -sL https://sentry.io/get-cli/ | sh
info_script: info_script:
- security find-identity -v - security find-identity -v
- xcodebuild -version - xcodebuild -version
@@ -95,9 +102,8 @@ task:
- lint - lint
- test - test
- build - build
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
macos_instance: macos_instance:
image: ghcr.io/cirruslabs/macos-ventura-xcode:$XCODE_TAG image: ghcr.io/cirruslabs/macos-sonoma-xcode:$XCODE_TAG
env: env:
MACOS_CERTIFICATE: ENCRYPTED[552b9d275d1c2bdbc1bff778b104a8f9a53cbd0d59344d4b7f6d0ca3c811a5cefb97bef9ba0ef31c219cb07bdacdd2c2] MACOS_CERTIFICATE: ENCRYPTED[552b9d275d1c2bdbc1bff778b104a8f9a53cbd0d59344d4b7f6d0ca3c811a5cefb97bef9ba0ef31c219cb07bdacdd2c2]
AC_PASSWORD: ENCRYPTED[4a761023e7e06fe2eb350c8b6e8e7ca961af193cb9ba47605f25f1d353abc3142606f412e405be48fd897a78787ea8c2] AC_PASSWORD: ENCRYPTED[4a761023e7e06fe2eb350c8b6e8e7ca961af193cb9ba47605f25f1d353abc3142606f412e405be48fd897a78787ea8c2]
@@ -142,7 +148,6 @@ task:
task: task:
name: Deploy Documentation name: Deploy Documentation
only_if: $CIRRUS_BRANCH == 'main' only_if: $CIRRUS_BRANCH == 'main'
use_compute_credits: $CIRRUS_USER_COLLABORATOR == 'true'
container: container:
image: ghcr.io/cirruslabs/mkdocs-material-insiders:latest image: ghcr.io/cirruslabs/mkdocs-material-insiders:latest
registry_config: ENCRYPTED[!cf1a0f25325aa75bad3ce6ebc890bc53eb0044c02efa70d8cefb83ba9766275a994b4831706c52630a0692b2fa9cfb9e!] registry_config: ENCRYPTED[!cf1a0f25325aa75bad3ce6ebc890bc53eb0044c02efa70d8cefb83ba9766275a994b4831706c52630a0692b2fa9cfb9e!]
+1 -1
View File
@@ -45,7 +45,7 @@ brews:
libexec.install Dir["*"] libexec.install Dir["*"]
bin.write_exec_script "#{libexec}/tart.app/Contents/MacOS/tart" bin.write_exec_script "#{libexec}/tart.app/Contents/MacOS/tart"
custom_block: | custom_block: |
depends_on :macos => :monterey depends_on :macos => :ventura
on_macos do on_macos do
unless Hardware::CPU.arm? unless Hardware::CPU.arm?
+9
View File
@@ -108,6 +108,15 @@
"version" : "0.50.6" "version" : "0.50.6"
} }
}, },
{
"identity" : "swiftradix",
"kind" : "remoteSourceControl",
"location" : "https://github.com/orchetect/SwiftRadix",
"state" : {
"revision" : "a52c37a4c213403f7377ae77b4c68451bcab8330",
"version" : "1.3.1"
}
},
{ {
"identity" : "texttable", "identity" : "texttable",
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
+3 -1
View File
@@ -4,7 +4,7 @@ import PackageDescription
let package = Package( let package = Package(
name: "Tart", name: "Tart",
platforms: [ platforms: [
.macOS(.v12) .macOS(.v13)
], ],
products: [ products: [
.executable(name: "tart", targets: ["tart"]) .executable(name: "tart", targets: ["tart"])
@@ -21,6 +21,7 @@ let package = Package(
.package(url: "https://github.com/getsentry/sentry-cocoa", from: "8.8.0"), .package(url: "https://github.com/getsentry/sentry-cocoa", from: "8.8.0"),
.package(url: "https://github.com/cfilipov/TextTable", branch: "master"), .package(url: "https://github.com/cfilipov/TextTable", branch: "master"),
.package(url: "https://github.com/sersoft-gmbh/swift-sysctl.git", from: "1.0.0"), .package(url: "https://github.com/sersoft-gmbh/swift-sysctl.git", from: "1.0.0"),
.package(url: "https://github.com/orchetect/SwiftRadix", from: "1.3.0")
], ],
targets: [ targets: [
.executableTarget(name: "tart", dependencies: [ .executableTarget(name: "tart", dependencies: [
@@ -34,6 +35,7 @@ let package = Package(
.product(name: "Sentry", package: "sentry-cocoa"), .product(name: "Sentry", package: "sentry-cocoa"),
.product(name: "TextTable", package: "TextTable"), .product(name: "TextTable", package: "TextTable"),
.product(name: "Sysctl", package: "swift-sysctl"), .product(name: "Sysctl", package: "swift-sysctl"),
.product(name: "SwiftRadix", package: "SwiftRadix"),
], exclude: [ ], exclude: [
"OCI/Reference/Makefile", "OCI/Reference/Makefile",
"OCI/Reference/Reference.g4", "OCI/Reference/Reference.g4",
+15 -3
View File
@@ -43,6 +43,9 @@ Many more companies are using Tart in their internal setups. Here are a few of t
<a href="https://mullvad.net/" target=_blank> <a href="https://mullvad.net/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Mullvad.png" height="65"/> <img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Mullvad.png" height="65"/>
</a> </a>
<a href="https://shape.dk/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/shape.png" height="65"/>
</a>
<a href="https://suran.com/" target=_blank> <a href="https://suran.com/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Suran.png" height="65"/> <img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Suran.png" height="65"/>
</a> </a>
@@ -52,6 +55,9 @@ Many more companies are using Tart in their internal setups. Here are a few of t
<a href="https://transloadit.com/" target=_blank> <a href="https://transloadit.com/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Transloadit.png" height="65"/> <img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Transloadit.png" height="65"/>
</a> </a>
<a href="https://uphold.com/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/Uphold.png" height="65"/>
</a>
<a href="https://www.pitsdatarecovery.net/" target=_blank> <a href="https://www.pitsdatarecovery.net/" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/PITSGlobalDataRecoveryServices.png" height="65"/> <img src="https://github.com/cirruslabs/tart/raw/main/Resources/Users/PITSGlobalDataRecoveryServices.png" height="65"/>
</a> </a>
@@ -59,14 +65,20 @@ Many more companies are using Tart in their internal setups. Here are a few of t
**Note:** If your company or project is using Tart please consider [adding yourself to the list above](/Resources/Users/HowToAddYourself.md). **Note:** If your company or project is using Tart please consider [adding yourself to the list above](/Resources/Users/HowToAddYourself.md).
<p align="center">
<a href="https://aws.amazon.com/marketplace/pp/prodview-qczco34wlkdws?utm_source=github&utm_medium=referral" target=_blank>
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/AWSMarkeplaceLogo.png" height="90"/>
</a>
</p>
## Usage ## Usage
Try running a Tart VM on your Apple Silicon device running macOS 12.0 (Monterey) or later (will download a 25 GB image): Try running a Tart VM on your Apple Silicon device running macOS 13.0 (Ventura) or later (will download a 25 GB image):
```bash ```bash
brew install cirruslabs/cli/tart brew install cirruslabs/cli/tart
tart clone ghcr.io/cirruslabs/macos-ventura-base:latest ventura-base tart clone ghcr.io/cirruslabs/macos-sonoma-base:latest sonoma-base
tart run ventura-base tart run sonoma-base
``` ```
Please check the [official documentation](https://tart.run) for more information and/or feel free to use [discussions](https://github.com/cirruslabs/tart/discussions) Please check the [official documentation](https://tart.run) for more information and/or feel free to use [discussions](https://github.com/cirruslabs/tart/discussions)
Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

+2
View File
@@ -4,5 +4,7 @@
<dict> <dict>
<key>com.apple.security.virtualization</key> <key>com.apple.security.virtualization</key>
<true/> <true/>
<key>com.apple.security.get-task-allow</key>
<true/>
</dict> </dict>
</plist> </plist>
+8 -1
View File
@@ -27,10 +27,17 @@ struct Clone: AsyncParsableCommand {
@Flag(help: "connect to the OCI registry via insecure HTTP protocol") @Flag(help: "connect to the OCI registry via insecure HTTP protocol")
var insecure: Bool = false var insecure: Bool = false
@Option(help: "network concurrency to use when pulling a remote VM from the OCI-compatible registry")
var concurrency: UInt = 4
func validate() throws { func validate() throws {
if newName.contains("/") { if newName.contains("/") {
throw ValidationError("<new-name> should be a local name") throw ValidationError("<new-name> should be a local name")
} }
if concurrency < 1 {
throw ValidationError("network concurrency cannot be less than 1")
}
} }
func run() async throws { func run() async throws {
@@ -40,7 +47,7 @@ struct Clone: AsyncParsableCommand {
if let remoteName = try? RemoteName(sourceName), !ociStorage.exists(remoteName) { if let remoteName = try? RemoteName(sourceName), !ociStorage.exists(remoteName) {
// Pull the VM in case it's OCI-based and doesn't exist locally yet // Pull the VM in case it's OCI-based and doesn't exist locally yet
let registry = try Registry(host: remoteName.host, namespace: remoteName.namespace, insecure: insecure) let registry = try Registry(host: remoteName.host, namespace: remoteName.namespace, insecure: insecure)
try await ociStorage.pull(remoteName, registry: registry) try await ociStorage.pull(remoteName, registry: registry, concurrency: concurrency)
} }
let sourceVM = try VMStorageHelper.open(sourceName) let sourceVM = try VMStorageHelper.open(sourceName)
+1 -5
View File
@@ -47,11 +47,7 @@ struct Create: AsyncParsableCommand {
} }
if linux { if linux {
if #available(macOS 13, *) { _ = try await VM.linux(vmDir: tmpVMDir, diskSizeGB: diskSize)
_ = try await VM.linux(vmDir: tmpVMDir, diskSizeGB: diskSize)
} else {
throw UnsupportedOSError("Linux VMs", "are")
}
} }
try VMStorageLocal().move(name, from: tmpVMDir) try VMStorageLocal().move(name, from: tmpVMDir)
+10 -1
View File
@@ -20,6 +20,15 @@ struct Pull: AsyncParsableCommand {
@Flag(help: "connect to the OCI registry via insecure HTTP protocol") @Flag(help: "connect to the OCI registry via insecure HTTP protocol")
var insecure: Bool = false var insecure: Bool = false
@Option(help: "network concurrency to use when pulling a remote VM from the OCI-compatible registry")
var concurrency: UInt = 4
func validate() throws {
if concurrency < 1 {
throw ValidationError("network concurrency cannot be less than 1")
}
}
func run() async throws { func run() async throws {
// Be more liberal when accepting local image as argument, // Be more liberal when accepting local image as argument,
// see https://github.com/cirruslabs/tart/issues/36 // see https://github.com/cirruslabs/tart/issues/36
@@ -34,6 +43,6 @@ struct Pull: AsyncParsableCommand {
defaultLogger.appendNewLine("pulling \(remoteName)...") defaultLogger.appendNewLine("pulling \(remoteName)...")
try await VMStorageOCI().pull(remoteName, registry: registry) try await VMStorageOCI().pull(remoteName, registry: registry, concurrency: concurrency)
} }
} }
+5 -1
View File
@@ -23,6 +23,9 @@ struct Push: AsyncParsableCommand {
""")) """))
var chunkSize: Int = 0 var chunkSize: Int = 0
@Option(help: .hidden)
var diskFormat: String = "v2"
@Flag(help: ArgumentHelp("cache pushed images locally", @Flag(help: ArgumentHelp("cache pushed images locally",
discussion: "Increases disk usage, but saves time if you're going to pull the pushed images later.")) discussion: "Increases disk usage, but saves time if you're going to pull the pushed images later."))
var populateCache: Bool = false var populateCache: Bool = false
@@ -69,7 +72,8 @@ struct Push: AsyncParsableCommand {
pushedRemoteName = try await localVMDir.pushToRegistry( pushedRemoteName = try await localVMDir.pushToRegistry(
registry: registry, registry: registry,
references: references, references: references,
chunkSizeMb: chunkSize chunkSizeMb: chunkSize,
diskFormat: diskFormat
) )
// Populate the local cache (if requested) // Populate the local cache (if requested)
if populateCache { if populateCache {
+176 -60
View File
@@ -1,5 +1,6 @@
import ArgumentParser import ArgumentParser
import Cocoa import Cocoa
import Darwin
import Dispatch import Dispatch
import SwiftUI import SwiftUI
import Virtualization import Virtualization
@@ -51,10 +52,17 @@ struct Run: AsyncParsableCommand {
var vncExperimental: Bool = false var vncExperimental: Bool = false
@Option(help: ArgumentHelp(""" @Option(help: ArgumentHelp("""
Additional disk attachments with an optional read-only specifier\n(e.g. --disk=\"disk.bin\" --disk=\"ubuntu.iso:ro\") Additional disk attachments with an optional read-only specifier\n(e.g. --disk=\"disk.bin\" --disk=\"ubuntu.iso:ro\" --disk=\"/dev/disk0\")
""", discussion: """ """, discussion: """
Can be either a disk image file or a block device like a local SSD on AWS EC2 Mac instances.
Learn how to create a disk image using Disk Utility here: Learn how to create a disk image using Disk Utility here:
https://support.apple.com/en-gb/guide/disk-utility/dskutl11888/mac https://support.apple.com/en-gb/guide/disk-utility/dskutl11888/mac
To work with block devices 'tart' binary must be executed as root which affects locating Tart VMs.
To workaround this issue pass TART_HOME explicitly:
sudo TART_HOME="$HOME/.tart" tart run sonoma --disk=/dev/disk0
""", valueName: "path[:ro]")) """, valueName: "path[:ro]"))
var disk: [String] = [] var disk: [String] = []
@@ -100,6 +108,10 @@ struct Run: AsyncParsableCommand {
@Flag(help: ArgumentHelp("Disables audio and entropy devices and switches to only Mac-specific input devices.", discussion: "Useful for running a VM that can be suspended via \"tart suspend\".")) @Flag(help: ArgumentHelp("Disables audio and entropy devices and switches to only Mac-specific input devices.", discussion: "Useful for running a VM that can be suspended via \"tart suspend\"."))
var suspendable: Bool = false var suspendable: Bool = false
@Flag(help: ArgumentHelp("Whether system hot keys should be sent to the guest instead of the host",
discussion: "If enabled then system hot keys like Cmd+Tab will be sent to the guest instead of the host."))
var captureSystemKeys: Bool = false
mutating func validate() throws { mutating func validate() throws {
if vnc && vncExperimental { if vnc && vncExperimental {
throw ValidationError("--vnc and --vnc-experimental are mutually exclusive") throw ValidationError("--vnc and --vnc-experimental are mutually exclusive")
@@ -113,11 +125,27 @@ struct Run: AsyncParsableCommand {
throw ValidationError("--graphics and --no-graphics are mutually exclusive") throw ValidationError("--graphics and --no-graphics are mutually exclusive")
} }
if (noGraphics || vnc || vncExperimental) && captureSystemKeys {
throw ValidationError("--captures-system-keys can only be used with the default VM view")
}
let localStorage = VMStorageLocal() let localStorage = VMStorageLocal()
let vmDir = try localStorage.open(name) let vmDir = try localStorage.open(name)
if try vmDir.state() == "suspended" { if try vmDir.state() == "suspended" {
suspendable = true suspendable = true
} }
if suspendable {
if dir.count > 0 {
throw ValidationError("Suspending VMs with shared directories is not supported")
}
}
for disk in disk {
if disk.hasSuffix("-amd64.iso") {
throw ValidationError("Seems you have a disk targeting x86 architecture (hence amd64 in the name). Please use an 'arm64' version of the disk.")
}
}
} }
@MainActor @MainActor
@@ -146,20 +174,6 @@ struct Run: AsyncParsableCommand {
let additionalDiskAttachments = try additionalDiskAttachments() let additionalDiskAttachments = try additionalDiskAttachments()
// Error out if the disk is locked by the host (e.g. it was mounted in Finder),
// see https://github.com/cirruslabs/tart/issues/323 for more details.
for additionalDiskAttachment in additionalDiskAttachments {
// Read-only attachments do not seem to acquire the lock
if additionalDiskAttachment.isReadOnly {
continue
}
if try !FileLock(lockURL: additionalDiskAttachment.url).trylock() {
throw RuntimeError.DiskAlreadyInUse("disk \(additionalDiskAttachment.url.path) seems to be already in use, "
+ "unmount it first in Finder")
}
}
var serialPorts: [VZSerialPortConfiguration] = [] var serialPorts: [VZSerialPortConfiguration] = []
if serial { if serial {
let tty_fd = createPTY() let tty_fd = createPTY()
@@ -181,7 +195,7 @@ struct Run: AsyncParsableCommand {
vm = try VM( vm = try VM(
vmDir: vmDir, vmDir: vmDir,
network: userSpecifiedNetwork(vmDir: vmDir) ?? NetworkShared(), network: userSpecifiedNetwork(vmDir: vmDir) ?? NetworkShared(),
additionalDiskAttachments: additionalDiskAttachments, additionalStorageDevices: additionalDiskAttachments,
directorySharingDevices: directoryShares() + rosettaDirectoryShare(), directorySharingDevices: directoryShares() + rosettaDirectoryShare(),
serialPorts: serialPorts, serialPorts: serialPorts,
suspendable: suspendable suspendable: suspendable
@@ -210,7 +224,7 @@ struct Run: AsyncParsableCommand {
// configuration file, otherwise we will loose the lock. // configuration file, otherwise we will loose the lock.
// //
// [1]: https://man.openbsd.org/fcntl // [1]: https://man.openbsd.org/fcntl
let lock = try PIDLock(lockURL: vmDir.configURL) let lock = try vmDir.lock()
if try !lock.trylock() { if try !lock.trylock() {
throw RuntimeError.VMAlreadyRunning("VM \"\(name)\" is already running!") throw RuntimeError.VMAlreadyRunning("VM \"\(name)\" is already running!")
} }
@@ -304,9 +318,13 @@ struct Run: AsyncParsableCommand {
let useVNCWithoutGraphics = (vnc || vncExperimental) && !graphics let useVNCWithoutGraphics = (vnc || vncExperimental) && !graphics
if noGraphics || useVNCWithoutGraphics { if noGraphics || useVNCWithoutGraphics {
dispatchMain() // enter the main even loop, without bringing up any UI,
// and just wait for the VM to exit.
let nsApp = NSApplication.shared
nsApp.setActivationPolicy(.prohibited)
nsApp.run()
} else { } else {
runUI(suspendable) runUI(suspendable, captureSystemKeys)
} }
} }
@@ -361,22 +379,43 @@ struct Run: AsyncParsableCommand {
} }
} }
func additionalDiskAttachments() throws -> [VZDiskImageStorageDeviceAttachment] { func additionalDiskAttachments() throws -> [VZStorageDeviceConfiguration] {
var result: [VZDiskImageStorageDeviceAttachment] = [] var result: [VZStorageDeviceConfiguration] = []
let readOnlySuffix = ":ro" let readOnlySuffix = ":ro"
let expandedDiskPaths = disk.map { NSString(string:$0).expandingTildeInPath } let expandedDiskPaths = disk.map { NSString(string:$0).expandingTildeInPath }
for rawDisk in expandedDiskPaths { for rawDisk in expandedDiskPaths {
if rawDisk.hasSuffix(readOnlySuffix) { let diskReadOnly = rawDisk.hasSuffix(readOnlySuffix)
result.append(try VZDiskImageStorageDeviceAttachment( let diskPath = diskReadOnly ? String(rawDisk.prefix(rawDisk.count - readOnlySuffix.count)) : rawDisk
url: URL(fileURLWithPath: String(rawDisk.prefix(rawDisk.count - readOnlySuffix.count))), let diskURL = URL(fileURLWithPath: diskPath)
readOnly: true
)) // check if `diskPath` is a block device or a directory
if pathHasMode(diskPath, mode: S_IFBLK) || pathHasMode(diskPath, mode: S_IFDIR) {
print("Using block device\n")
guard #available(macOS 14, *) else {
throw UnsupportedOSError("attaching block devices", "are")
}
let fileHandle = FileHandle(forUpdatingAtPath: diskPath)
guard fileHandle != nil else {
if ProcessInfo.processInfo.userName != "root" {
throw RuntimeError.VMConfigurationError("need to run as root to work with block devices")
}
throw RuntimeError.VMConfigurationError("block device \(diskURL.url.path) seems to be already in use, unmount it first via 'diskutil unmount'")
}
let attachment = try VZDiskBlockDeviceStorageDeviceAttachment(fileHandle: fileHandle!, readOnly: diskReadOnly, synchronizationMode: .full)
result.append(VZVirtioBlockDeviceConfiguration(attachment: attachment))
} else { } else {
result.append(try VZDiskImageStorageDeviceAttachment( // Error out if the disk is locked by the host (e.g. it was mounted in Finder),
url: URL(fileURLWithPath: rawDisk), // see https://github.com/cirruslabs/tart/issues/323 for more details.
readOnly: false if try !diskReadOnly && !FileLock(lockURL: diskURL).trylock() {
)) throw RuntimeError.DiskAlreadyInUse("disk \(diskURL.url.path) seems to be already in use, unmount it first in Finder")
}
let diskImageAttachment = try VZDiskImageStorageDeviceAttachment(
url: diskURL,
readOnly: diskReadOnly
)
result.append(VZVirtioBlockDeviceConfiguration(attachment: diskImageAttachment))
} }
} }
@@ -408,13 +447,13 @@ struct Run: AsyncParsableCommand {
let sharingDevice = VZVirtioFileSystemDeviceConfiguration(tag: automountTag) let sharingDevice = VZVirtioFileSystemDeviceConfiguration(tag: automountTag)
if allNamedShares { if allNamedShares {
var directories: [String : VZSharedDirectory] = Dictionary() var directories: [String : VZSharedDirectory] = Dictionary()
directoryShares.forEach { directories[$0.name!] = VZSharedDirectory(url: $0.path, readOnly: $0.readOnly) } try directoryShares.forEach { directories[$0.name!] = try $0.createConfiguration() }
sharingDevice.share = VZMultipleDirectoryShare(directories: directories) sharingDevice.share = VZMultipleDirectoryShare(directories: directories)
} else if dir.count > 1 { } else if dir.count > 1 {
throw ValidationError("invalid --dir syntax: for multiple directory shares each one of them should be named") throw ValidationError("invalid --dir syntax: for multiple directory shares each one of them should be named")
} else if dir.count == 1 { } else if dir.count == 1 {
let directoryShare = directoryShares.first! let directoryShare = directoryShares.first!
let singleDirectoryShare = VZSingleDirectoryShare(directory: VZSharedDirectory(url: directoryShare.path, readOnly: directoryShare.readOnly)) let singleDirectoryShare = VZSingleDirectoryShare(directory: try directoryShare.createConfiguration())
sharingDevice.share = singleDirectoryShare sharingDevice.share = singleDirectoryShare
} }
@@ -446,7 +485,7 @@ struct Run: AsyncParsableCommand {
return [device] return [device]
} }
private func runUI(_ suspendable: Bool) { private func runUI(_ suspendable: Bool, _ captureSystemKeys: Bool) {
let nsApp = NSApplication.shared let nsApp = NSApplication.shared
nsApp.setActivationPolicy(.regular) nsApp.setActivationPolicy(.regular)
nsApp.activate(ignoringOtherApps: true) nsApp.activate(ignoringOtherApps: true)
@@ -455,13 +494,14 @@ struct Run: AsyncParsableCommand {
struct MainApp: App { struct MainApp: App {
static var disappearSignal: Int32 = SIGINT static var disappearSignal: Int32 = SIGINT
static var capturesSystemKeys: Bool = false
@NSApplicationDelegateAdaptor private var appDelegate: MinimalMenuAppDelegate @NSApplicationDelegateAdaptor private var appDelegate: MinimalMenuAppDelegate
var body: some Scene { var body: some Scene {
WindowGroup(vm!.name) { WindowGroup(vm!.name) {
Group { Group {
VMView(vm: vm!).onAppear { VMView(vm: vm!, capturesSystemKeys: MainApp.capturesSystemKeys).onAppear {
NSWindow.allowsAutomaticWindowTabbing = false NSWindow.allowsAutomaticWindowTabbing = false
}.onDisappear { }.onDisappear {
let ret = kill(getpid(), MainApp.disappearSignal) let ret = kill(getpid(), MainApp.disappearSignal)
@@ -511,6 +551,7 @@ struct Run: AsyncParsableCommand {
} }
MainApp.disappearSignal = suspendable ? SIGUSR1 : SIGINT MainApp.disappearSignal = suspendable ? SIGUSR1 : SIGINT
MainApp.capturesSystemKeys = captureSystemKeys
MainApp.main() MainApp.main()
} }
} }
@@ -560,14 +601,12 @@ struct VMView: NSViewRepresentable {
typealias NSViewType = VZVirtualMachineView typealias NSViewType = VZVirtualMachineView
@ObservedObject var vm: VM @ObservedObject var vm: VM
var capturesSystemKeys: Bool
func makeNSView(context: Context) -> NSViewType { func makeNSView(context: Context) -> NSViewType {
let machineView = VZVirtualMachineView() let machineView = VZVirtualMachineView()
// Do not capture system keys so that shortcuts like machineView.capturesSystemKeys = capturesSystemKeys
// Shift-Command-4 + Space (capture a screenshot of window)
// work on the host instead of the guest
machineView.capturesSystemKeys = false
// Enable automatic display reconfiguration // Enable automatic display reconfiguration
// for guests that support it // for guests that support it
@@ -589,36 +628,113 @@ struct DirectoryShare {
let readOnly: Bool let readOnly: Bool
init(parseFrom: String) throws { init(parseFrom: String) throws {
let splits = parseFrom.split(maxSplits: 2) { $0 == ":" } let readOnlySuffix = ":ro"
readOnly = parseFrom.hasSuffix(readOnlySuffix)
let maybeNameAndURL = readOnly ? String(parseFrom.dropLast(readOnlySuffix.count)) : parseFrom
if splits.count == 3 { if maybeNameAndURL.starts(with: "https://") || maybeNameAndURL.starts(with: "http://") {
if splits[2] == "ro" { // just a URL
readOnly = true name = nil
} else { path = URL(string: maybeNameAndURL)!
throw ValidationError("invalid --dir syntax: optional read-only specifier can only be \"ro\"") return
} }
let splits = maybeNameAndURL.split(separator: ":", maxSplits: 1)
if splits.count == 2 {
name = String(splits[0]) name = String(splits[0])
path = String(splits[1]).toFilePathURL() path = String(splits[1]).toRemoteOrLocalURL()
} else if splits.count == 2 {
if splits[1] == "ro" {
name = nil
path = String(splits[0]).toFilePathURL()
readOnly = true
} else {
name = String(splits[0])
path = String(splits[1]).toFilePathURL()
readOnly = false
}
} else { } else {
name = nil name = nil
path = String(splits[0]).toFilePathURL() path = String(splits[0]).toRemoteOrLocalURL()
readOnly = false
} }
} }
func createConfiguration() throws -> VZSharedDirectory {
if (path.isFileURL) {
return VZSharedDirectory(url: path, readOnly: readOnly)
}
let urlCache = URLCache(memoryCapacity: 0, diskCapacity: 1 * 1024 * 1024 * 1024)
let archiveRequest = URLRequest(url: path, cachePolicy: .returnCacheDataElseLoad)
var response: CachedURLResponse? = urlCache.cachedResponse(for: archiveRequest)
if (response == nil || response?.data.isEmpty == true) {
print("Downloading \(path)...")
// download and unarchive remote directories if needed here
// use old school API to prevent deadlocks since we are running via MainActor
let downloadSemaphore = DispatchSemaphore(value: 0)
Task {
do {
let (archiveData, archiveResponse) = try await URLSession.shared.data(for: archiveRequest)
if archiveData.isEmpty {
print("Remote archive is empty!")
} else {
urlCache.storeCachedResponse(CachedURLResponse(response: archiveResponse, data: archiveData, storagePolicy: .allowed), for: archiveRequest)
print("Cached for future invocations!")
}
} catch {
print("Download failed: \(error)")
}
downloadSemaphore.signal()
}
downloadSemaphore.wait()
response = urlCache.cachedResponse(for: archiveRequest)
} else {
print("Using cached archive for \(path)...")
}
if (response == nil) {
throw ValidationError("Failed to fetch a remote archive!")
}
let temporaryLocation = try Config().tartTmpDir.appendingPathComponent(UUID().uuidString + ".volume")
try FileManager.default.createDirectory(atPath: temporaryLocation.path, withIntermediateDirectories: true)
let lock = try FileLock(lockURL: temporaryLocation)
try lock.lock()
guard let executableURL = resolveBinaryPath("tar") else {
throw ValidationError("tar not found in PATH")
}
let process = Process.init()
process.executableURL = executableURL
process.currentDirectoryURL = temporaryLocation
process.arguments = ["-xz"]
let inPipe = Pipe()
process.standardInput = inPipe
process.launch()
inPipe.fileHandleForWriting.write(response!.data)
try inPipe.fileHandleForWriting.close()
process.waitUntilExit()
if !(process.terminationReason == .exit && process.terminationStatus == 0) {
throw ValidationError("Unarchiving failed!")
}
print("Unarchived into a temporary directory!")
return VZSharedDirectory(url: temporaryLocation, readOnly: readOnly)
}
} }
extension String { extension String {
func toFilePathURL() -> URL { func toRemoteOrLocalURL() -> URL {
URL(fileURLWithPath: NSString(string: self).expandingTildeInPath) if (starts(with: "https://") || starts(with: "https://")) {
URL(string: self)!
} else {
URL(fileURLWithPath: NSString(string: self).expandingTildeInPath)
}
} }
} }
func pathHasMode(_ path: String, mode: mode_t) -> Bool {
var st = stat()
let statRes = stat(path, &st)
guard statRes != -1 else {
return false
}
return (Int32(st.st_mode) & Int32(mode)) == Int32(mode)
}
+2 -2
View File
@@ -29,12 +29,12 @@ struct Stop: AsyncParsableCommand {
} }
func stopRunning(_ vmDir: VMDirectory) async throws { func stopRunning(_ vmDir: VMDirectory) async throws {
let lock = try PIDLock(lockURL: vmDir.configURL) let lock = try vmDir.lock()
// Find the VM's PID // Find the VM's PID
var pid = try lock.pid() var pid = try lock.pid()
if pid == 0 { if pid == 0 {
throw RuntimeError.VMNotRunning("VM \"\(name)\" is not running") throw RuntimeError.VMNotRunning(name)
} }
// Try to gracefully terminate the VM // Try to gracefully terminate the VM
+1 -1
View File
@@ -11,7 +11,7 @@ struct Suspend: AsyncParsableCommand {
func run() async throws { func run() async throws {
let vmDir = try VMStorageLocal().open(name) let vmDir = try VMStorageLocal().open(name)
let lock = try PIDLock(lockURL: vmDir.configURL) let lock = try vmDir.lock()
// Find the VM's PID // Find the VM's PID
var pid = try lock.pid() var pid = try lock.pid()
@@ -11,14 +11,10 @@ class DockerConfigCredentialsProvider: CredentialsProvider {
if let credentialsFromAuth = config.auths?[host]?.decodeCredentials() { if let credentialsFromAuth = config.auths?[host]?.decodeCredentials() {
return credentialsFromAuth return credentialsFromAuth
} }
if let helperProgram = config.credHelpers?[host] { if let helperProgram = try config.findCredHelper(host: host) {
return try executeHelper(binaryName: "docker-credential-\(helperProgram)", host: host) return try executeHelper(binaryName: "docker-credential-\(helperProgram)", host: host)
} }
if let defaultCredsStore = config.credsStore {
return try executeHelper(binaryName: "docker-credential-\(defaultCredsStore)", host: host)
}
return nil return nil
} }
@@ -45,13 +41,18 @@ class DockerConfigCredentialsProvider: CredentialsProvider {
process.waitUntilExit() process.waitUntilExit()
let outputData = try outPipe.fileHandleForReading.readToEnd()
if !(process.terminationReason == .exit && process.terminationStatus == 0) { if !(process.terminationReason == .exit && process.terminationStatus == 0) {
if let outputData = outputData {
print(String(decoding: outputData, as: UTF8.self))
}
throw CredentialsProviderError.Failed(message: "Docker helper failed!") throw CredentialsProviderError.Failed(message: "Docker helper failed!")
} }
if outputData == nil || outputData?.count == 0 {
throw CredentialsProviderError.Failed(message: "Docker helper output is empty!")
}
let getOutput = try JSONDecoder().decode( let getOutput = try JSONDecoder().decode(DockerGetOutput.self, from: outputData!)
DockerGetOutput.self, from: outPipe.fileHandleForReading.readDataToEndOfFile()
)
return (getOutput.Username, getOutput.Secret) return (getOutput.Username, getOutput.Secret)
} }
@@ -63,7 +64,26 @@ class DockerConfigCredentialsProvider: CredentialsProvider {
struct DockerConfig: Codable { struct DockerConfig: Codable {
var auths: Dictionary<String, DockerAuthConfig>? = Dictionary() var auths: Dictionary<String, DockerAuthConfig>? = Dictionary()
var credHelpers: Dictionary<String, String>? = Dictionary() var credHelpers: Dictionary<String, String>? = Dictionary()
var credsStore: String? = nil
func findCredHelper(host: String) throws -> String? {
// Tart supports wildcards in credHelpers
// Similar to what is requested from Docker: https://github.com/docker/cli/issues/2928
guard let credHelpers else {
return nil
}
for (hostPattern, helperProgram) in credHelpers {
if (hostPattern == host) {
return helperProgram
}
let compiledPattern = try? Regex(hostPattern)
if (try compiledPattern?.wholeMatch(in: host) != nil) {
return helperProgram
}
}
return nil
}
} }
struct DockerAuthConfig: Codable { struct DockerAuthConfig: Codable {
@@ -13,7 +13,7 @@ class StdinCredentials {
return (user, password) return (user, password)
} }
private static func readStdinCredential(name: String, prompt: String, maxCharacters: Int = 255, isSensitive: Bool) throws -> String { private static func readStdinCredential(name: String, prompt: String, maxCharacters: Int = 1024, isSensitive: Bool) throws -> String {
var buf = [CChar](repeating: 0, count: maxCharacters + 1 /* sentinel */ + 1 /* NUL */) var buf = [CChar](repeating: 0, count: maxCharacters + 1 /* sentinel */ + 1 /* NUL */)
guard let rawCredential = readpassphrase(prompt, &buf, buf.count, isSensitive ? RPP_ECHO_OFF : RPP_ECHO_ON) else { guard let rawCredential = readpassphrase(prompt, &buf, buf.count, isSensitive ? RPP_ECHO_OFF : RPP_ECHO_ON) else {
throw StdinCredentialsError.CredentialRequired(which: name) throw StdinCredentialsError.CredentialRequired(which: name)
+3 -3
View File
@@ -35,12 +35,12 @@ class Fetcher {
// //
// This keeps a working reference to that file, yet we don't // This keeps a working reference to that file, yet we don't
// have to deal with the cleanup any more. // have to deal with the cleanup any more.
let fh = try FileHandle(forReadingFrom: fileURL) let mappedFile = try Data(contentsOf: fileURL, options: [.alwaysMapped])
try FileManager.default.removeItem(at: fileURL) try FileManager.default.removeItem(at: fileURL)
Task { Task {
while let data = try fh.read(upToCount: 64 * 1024 * 1024) { for chunk in (0 ..< mappedFile.count).chunks(ofCount: 64 * 1024 * 1024) {
await dataCh.send(data) await dataCh.send(mappedFile.subdata(in: chunk))
} }
dataCh.finish() dataCh.finish()
@@ -1,13 +1,17 @@
import Foundation
import Network import Network
import SwiftRadix
struct Lease { struct Lease {
var mac: MACAddress var mac: MACAddress
var ip: IPv4Address var ip: IPv4Address
var expiresAt: Date
init?(fromRawLease: [String : String]) { init?(fromRawLease: [String : String]) {
// Retrieve the required fields // Retrieve the required fields
guard let hwAddress = fromRawLease["hw_address"] else { return nil } guard let hwAddress = fromRawLease["hw_address"] else { return nil }
guard let ipAddress = fromRawLease["ip_address"] else { return nil } guard let ipAddress = fromRawLease["ip_address"] else { return nil }
guard let lease = fromRawLease["lease"] else { return nil }
// Parse MAC address // Parse MAC address
let hwAddressSplits = hwAddress.split(separator: ",") let hwAddressSplits = hwAddress.split(separator: ",")
@@ -26,7 +30,13 @@ struct Lease {
return nil return nil
} }
// Parse expiration timestamp
guard let leaseTimestamp = lease.hex?.value else {
return nil
}
self.ip = ip self.ip = ip
self.mac = mac self.mac = mac
self.expiresAt = Date(timeIntervalSince1970: TimeInterval(leaseTimestamp))
} }
} }
+9 -7
View File
@@ -37,13 +37,15 @@ class Leases {
} }
init(_ fromString: String) throws { init(_ fromString: String) throws {
var leases: [MACAddress : Lease] = Dictionary() let leases = try Self.retrieveRawLeases(fromString).compactMap({ rawLease in
Lease(fromRawLease: rawLease)
}).filter({ lease in
lease.expiresAt.isInFuture
}).map({ lease in
(lease.mac, lease)
})
for lease in try Self.retrieveRawLeases(fromString).compactMap({ Lease(fromRawLease: $0) }) { self.leases = Dictionary(uniqueKeysWithValues: leases)
leases[lease.mac] = lease
}
self.leases = leases
} }
/// Parse leases from the host cache similarly to the PLCache_read() function found in Apple's Open Source releases. /// Parse leases from the host cache similarly to the PLCache_read() function found in Apple's Open Source releases.
@@ -107,7 +109,7 @@ class Leases {
return rawLeases return rawLeases
} }
func ResolveMACAddress(macAddress: MACAddress) throws -> IPv4Address? { func ResolveMACAddress(macAddress: MACAddress) -> IPv4Address? {
leases[macAddress]?.ip leases[macAddress]?.ip
} }
} }
@@ -0,0 +1,25 @@
import Foundation
actor AuthenticationKeeper {
var authentication: Authentication? = nil
func set(_ authentication: Authentication) {
self.authentication = authentication
}
func header() -> (String, String)? {
if let authentication = authentication {
// Do not suggest any headers if the
// authentication token has expired
if !authentication.isValid() {
return nil
}
return authentication.header()
}
// Do not suggest any headers if the
// authentication token is not set
return nil
}
}
+36
View File
@@ -1,6 +1,11 @@
import Foundation import Foundation
import CryptoKit import CryptoKit
enum DigestError: Error {
case InvalidOffset
case InvalidSize
}
class Digest { class Digest {
var hash: SHA256 = SHA256() var hash: SHA256 = SHA256()
@@ -15,6 +20,37 @@ class Digest {
static func hash(_ data: Data) -> String { static func hash(_ data: Data) -> String {
SHA256.hash(data: data).hexdigest() SHA256.hash(data: data).hexdigest()
} }
static func hash(_ url: URL) throws -> String {
hash(try Data(contentsOf: url))
}
static func hash(_ url: URL, offset: UInt64, size: UInt64) throws -> String {
// Sanity check
let fhSanity = try FileHandle(forReadingFrom: url)
try fhSanity.seekToEnd()
let fileSize = try fhSanity.offset()
try fhSanity.close()
if offset > fileSize {
throw DigestError.InvalidOffset
}
if (offset + size) > fileSize {
throw DigestError.InvalidSize
}
// Read a chunk of size ``size`` at offset ``offset``
// and calculate it's digest
let fh = try FileHandle(forReadingFrom: url)
defer { try! fh.close() }
try fh.seek(toOffset: offset)
let data = try fh.read(upToCount: Int(size))!
return hash(data)
}
} }
extension SHA256.Digest { extension SHA256.Digest {
+6
View File
@@ -0,0 +1,6 @@
import Foundation
protocol Disk {
static func push(diskURL: URL, registry: Registry, chunkSizeMb: Int, progress: Progress) async throws -> [OCIManifestLayer]
static func pull(registry: Registry, diskLayers: [OCIManifestLayer], diskURL: URL, concurrency: UInt, progress: Progress) async throws
}
+75
View File
@@ -0,0 +1,75 @@
import Foundation
import Compression
class DiskV1: Disk {
private static let bufferSizeBytes = 4 * 1024 * 1024
private static let layerLimitBytes = 500 * 1000 * 1000
static func push(diskURL: URL, registry: Registry, chunkSizeMb: Int, progress: Progress) async throws -> [OCIManifestLayer] {
var pushedLayers: [OCIManifestLayer] = []
// Open the disk file
let mappedDisk = try Data(contentsOf: diskURL, options: [.alwaysMapped])
var mappedDiskReadOffset = 0
// Compress the disk file as a single stream
let compressingFilter = try InputFilter(.compress, using: .lz4, bufferCapacity: Self.bufferSizeBytes) { (length: Int) -> Data? in
// Determine the size of the next chunk
let bytesRead = min(length, mappedDisk.count - mappedDiskReadOffset)
// Read the next uncompressed chunk
let data = mappedDisk.subdata(in: mappedDiskReadOffset ..< mappedDiskReadOffset + bytesRead)
// Advance the offset
mappedDiskReadOffset += bytesRead
// Provide the uncompressed chunk to the compressing filter
return data
}
// Cut the compressed stream into layers, each equal exactly ``Self.layerLimitBytes`` bytes,
// except for the last one, which may be smaller
while let compressedData = try compressingFilter.readData(ofLength: Self.layerLimitBytes) {
let layerDigest = try await registry.pushBlob(fromData: compressedData, chunkSizeMb: chunkSizeMb)
pushedLayers.append(OCIManifestLayer(
mediaType: diskV1MediaType,
size: compressedData.count,
digest: layerDigest
))
// Update progress using an absolute value
progress.completedUnitCount = Int64(mappedDiskReadOffset)
}
return pushedLayers
}
static func pull(registry: Registry, diskLayers: [OCIManifestLayer], diskURL: URL, concurrency: UInt, progress: Progress) async throws {
if !FileManager.default.createFile(atPath: diskURL.path, contents: nil) {
throw OCIError.FailedToCreateVmFile
}
// Open the disk file
let disk = try FileHandle(forWritingTo: diskURL)
defer { try! disk.close() }
// Decompress the layers onto the disk in a single stream
let filter = try OutputFilter(.decompress, using: .lz4, bufferCapacity: Self.bufferSizeBytes) { data in
if let data = data {
disk.write(data)
}
}
for diskLayer in diskLayers {
try await registry.pullBlob(diskLayer.digest) { data in
try filter.write(data)
// Update the progress
progress.completedUnitCount += Int64(data.count)
}
}
try filter.finalize()
}
}
+188
View File
@@ -0,0 +1,188 @@
import Foundation
import Compression
class DiskV2: Disk {
private static let bufferSizeBytes = 4 * 1024 * 1024
private static let layerLimitBytes = 500 * 1000 * 1000
private static let holeGranularityBytes = 64 * 1024
static func push(diskURL: URL, registry: Registry, chunkSizeMb: Int, progress: Progress) async throws -> [OCIManifestLayer] {
var pushedLayers: [OCIManifestLayer] = []
// Open the disk file
var mappedDisk = try Data(contentsOf: diskURL, options: [.alwaysMapped])
// Compress the disk file as multiple individually decompressible streams,
// each equal ``Self.layerLimitBytes`` bytes or slightly larger due to the
// internal compressor's buffer
var offset: UInt64 = 0
while let (compressedData, uncompressedSize, uncompressedDigest) = try compressNextLayerOfLimitBytesOrMore(mappedDisk: mappedDisk, offset: offset) {
offset += uncompressedSize
let layerDigest = try await registry.pushBlob(fromData: compressedData, chunkSizeMb: chunkSizeMb)
pushedLayers.append(OCIManifestLayer(
mediaType: diskV2MediaType,
size: compressedData.count,
digest: layerDigest,
uncompressedSize: uncompressedSize,
uncompressedContentDigest: uncompressedDigest
))
// Update progress using a relative value
progress.completedUnitCount += Int64(uncompressedSize)
}
return pushedLayers
}
static func pull(registry: Registry, diskLayers: [OCIManifestLayer], diskURL: URL, concurrency: UInt, progress: Progress) async throws {
// Support resumable pulls
let pullResumed = FileManager.default.fileExists(atPath: diskURL.path)
if !pullResumed && !FileManager.default.createFile(atPath: diskURL.path, contents: nil) {
throw OCIError.FailedToCreateVmFile
}
// Calculate the uncompressed disk size
var uncompressedDiskSize: UInt64 = 0
for layer in diskLayers {
guard let uncompressedLayerSize = layer.uncompressedSize() else {
throw OCIError.LayerIsMissingUncompressedSizeAnnotation
}
uncompressedDiskSize += uncompressedLayerSize
}
// Truncate the target disk file so that it will be able
// to accomodate the uncompressed disk size
let disk = try FileHandle(forWritingTo: diskURL)
try disk.truncate(atOffset: uncompressedDiskSize)
try disk.close()
// Concurrently fetch and decompress layers
try await withThrowingTaskGroup(of: Void.self) { group in
var globalDiskWritingOffset: UInt64 = 0
for (index, diskLayer) in diskLayers.enumerated() {
// Respect the concurrency limit
if index >= concurrency {
try await group.next()
}
// Retrieve layer annotations
guard let uncompressedLayerSize = diskLayer.uncompressedSize() else {
throw OCIError.LayerIsMissingUncompressedSizeAnnotation
}
guard let uncompressedLayerContentDigest = diskLayer.uncompressedContentDigest() else {
throw OCIError.LayerIsMissingUncompressedDigestAnnotation
}
// Capture the current disk writing offset
let diskWritingOffset = globalDiskWritingOffset
// Launch a fetching and decompression task
group.addTask {
// No need to fetch and decompress anything if we've already done so
if try pullResumed && Digest.hash(diskURL, offset: diskWritingOffset, size: uncompressedLayerSize) == uncompressedLayerContentDigest {
// Update the progress
progress.completedUnitCount += Int64(diskLayer.size)
return
}
// Open the disk file
let disk = try FileHandle(forWritingTo: diskURL)
// A zero chunk for faster than byte-by-byte comparisons
//
// Assumes that the other Data(...) is equal in size, but it's fine to get a false-negative
// on the last block since it costs only 64 KiB of excess data per 500 MB layer.
//
// Some simple benchmarks ("sync && sudo purge" command was used to negate the disk caching effects):
// +--------------------------------------+---------------------------------------------------+
// | Operation | time(1) result |
// +--------------------------------------+---------------------------------------------------+
// | Data(...) == zeroChunk | 2.16s user 11.71s system 73% cpu 18.928 total |
// | Data(...).contains(where: {$0 != 0}) | 603.68s user 12.97s system 99% cpu 10:22.85 total |
// +--------------------------------------+---------------------------------------------------+
let zeroChunk = Data(count: holeGranularityBytes)
var diskWritingOffset = diskWritingOffset
// Pull and decompress a single layer into the specific offset on disk
let filter = try OutputFilter(.decompress, using: .lz4, bufferCapacity: Self.bufferSizeBytes) { data in
guard let data = data else {
return
}
for chunk in data.chunks(ofCount: holeGranularityBytes) {
// Only write chunks that are not zero
if chunk != zeroChunk {
try disk.seek(toOffset: diskWritingOffset)
disk.write(chunk)
}
diskWritingOffset += UInt64(chunk.count)
}
}
try await registry.pullBlob(diskLayer.digest) { data in
try filter.write(data)
// Update the progress
progress.completedUnitCount += Int64(data.count)
}
try filter.finalize()
try disk.close()
}
globalDiskWritingOffset += uncompressedLayerSize
}
}
}
private static func compressNextLayerOfLimitBytesOrMore(mappedDisk: Data, offset: UInt64) throws -> (Data, UInt64, String)? {
var compressedData = Data()
var bytesRead: UInt64 = 0
let digest = Digest()
// Create a compressing filter that we will terminate upon
// reaching ``Self.layerLimitBytes`` of compressed data
let compressingFilter = try InputFilter(.compress, using: .lz4, bufferCapacity: bufferSizeBytes) { (length: Int) -> Data? in
if compressedData.count >= Self.layerLimitBytes {
return nil
}
let readFromByte = Int(offset + bytesRead)
let numBytesToRead = min(mappedDisk.count - readFromByte, bufferSizeBytes)
if numBytesToRead == 0 {
return nil
}
let uncompressedChunk = mappedDisk.subdata(in: readFromByte ..< (readFromByte + numBytesToRead))
bytesRead += UInt64(uncompressedChunk.count)
digest.update(uncompressedChunk)
return uncompressedChunk
}
// Retrieve compressed data chunks, but normally no more than ``Self.layerLimitBytes`` bytes
while let compressedChunk = try compressingFilter.readData(ofLength: Self.bufferSizeBytes) {
compressedData.append(compressedChunk)
}
// Nothing was read this time from the disk,
// signal that to the consumer
if bytesRead == 0 {
return nil
}
return (compressedData, bytesRead, digest.finalize())
}
}
+43 -1
View File
@@ -1,12 +1,23 @@
import Foundation import Foundation
// OCI manifest and OCI config media types
let ociManifestMediaType = "application/vnd.oci.image.manifest.v1+json" let ociManifestMediaType = "application/vnd.oci.image.manifest.v1+json"
let ociConfigMediaType = "application/vnd.oci.image.config.v1+json" let ociConfigMediaType = "application/vnd.oci.image.config.v1+json"
// Annotations // Layer media types
let configMediaType = "application/vnd.cirruslabs.tart.config.v1"
let diskV1MediaType = "application/vnd.cirruslabs.tart.disk.v1"
let diskV2MediaType = "application/vnd.cirruslabs.tart.disk.v2"
let nvramMediaType = "application/vnd.cirruslabs.tart.nvram.v1"
// Manifest annotations
let uncompressedDiskSizeAnnotation = "org.cirruslabs.tart.uncompressed-disk-size" let uncompressedDiskSizeAnnotation = "org.cirruslabs.tart.uncompressed-disk-size"
let uploadTimeAnnotation = "org.cirruslabs.tart.upload-time" let uploadTimeAnnotation = "org.cirruslabs.tart.upload-time"
// Layer annotations
let uncompressedSizeAnnotation = "org.cirruslabs.tart.uncompressed-size"
let uncompressedContentDigestAnnotation = "org.cirruslabs.tart.uncompressed-content-digest"
struct OCIManifest: Codable, Equatable { struct OCIManifest: Codable, Equatable {
var schemaVersion: Int = 2 var schemaVersion: Int = 2
var mediaType: String = ociManifestMediaType var mediaType: String = ociManifestMediaType
@@ -71,6 +82,37 @@ struct OCIManifestLayer: Codable, Equatable {
var mediaType: String var mediaType: String
var size: Int var size: Int
var digest: String var digest: String
var annotations: Dictionary<String, String>?
init(mediaType: String, size: Int, digest: String, uncompressedSize: UInt64? = nil, uncompressedContentDigest: String? = nil) {
self.mediaType = mediaType
self.size = size
self.digest = digest
var annotations: [String: String] = [:]
if let uncompressedSize = uncompressedSize {
annotations[uncompressedSizeAnnotation] = String(uncompressedSize)
}
if let uncompressedContentDigest = uncompressedContentDigest {
annotations[uncompressedContentDigestAnnotation] = uncompressedContentDigest
}
self.annotations = annotations
}
func uncompressedSize() -> UInt64? {
guard let value = annotations?[uncompressedSizeAnnotation] else {
return nil
}
return UInt64(value)
}
func uncompressedContentDigest() -> String? {
annotations?[uncompressedContentDigestAnnotation]
}
} }
struct Descriptor: Equatable { struct Descriptor: Equatable {
+6 -13
View File
@@ -102,8 +102,7 @@ class Registry {
private let baseURL: URL private let baseURL: URL
let namespace: String let namespace: String
let credentialsProviders: [CredentialsProvider] let credentialsProviders: [CredentialsProvider]
let authenticationKeeper = AuthenticationKeeper()
var currentAuthToken: Authentication? = nil
var host: String? { var host: String? {
guard let host = baseURL.host else { return nil } guard let host = baseURL.host else { return nil }
@@ -242,7 +241,7 @@ class Registry {
return digest return digest
} }
public func pullBlob(_ digest: String, handler: (Data) throws -> Void) async throws { public func pullBlob(_ digest: String, handler: (Data) async throws -> Void) async throws {
let (channel, response) = try await channelRequest(.GET, endpointURL("\(namespace)/blobs/\(digest)"), viaFile: true) let (channel, response) = try await channelRequest(.GET, endpointURL("\(namespace)/blobs/\(digest)"), viaFile: true)
if response.statusCode != HTTPCode.Ok.rawValue { if response.statusCode != HTTPCode.Ok.rawValue {
let body = try await channel.asData().asText() let body = try await channel.asData().asText()
@@ -253,7 +252,7 @@ class Registry {
for try await part in channel { for try await part in channel {
try Task.checkCancellation() try Task.checkCancellation()
try handler(Data(part)) try await handler(part)
} }
} }
@@ -305,11 +304,6 @@ class Registry {
request.httpBody = body request.httpBody = body
} }
// Invalidate token if it has expired
if currentAuthToken?.isValid() == false {
currentAuthToken = nil
}
var (channel, response) = try await authAwareRequest(request: request, viaFile: viaFile) var (channel, response) = try await authAwareRequest(request: request, viaFile: viaFile)
if doAuth && response.statusCode == HTTPCode.Unauthorized.rawValue { if doAuth && response.statusCode == HTTPCode.Unauthorized.rawValue {
@@ -331,7 +325,7 @@ class Registry {
if wwwAuthenticate.scheme.lowercased() == "basic" { if wwwAuthenticate.scheme.lowercased() == "basic" {
if let (user, password) = try lookupCredentials() { if let (user, password) = try lookupCredentials() {
currentAuthToken = BasicAuthentication(user: user, password: password) await authenticationKeeper.set(BasicAuthentication(user: user, password: password))
} }
return return
@@ -378,7 +372,7 @@ class Registry {
+ "while retrieving an authentication token", details: data.asText()) + "while retrieving an authentication token", details: data.asText())
} }
currentAuthToken = try TokenResponse.parse(fromData: data) await authenticationKeeper.set(try TokenResponse.parse(fromData: data))
} }
private func lookupCredentials() throws -> (String, String)? { private func lookupCredentials() throws -> (String, String)? {
@@ -399,8 +393,7 @@ class Registry {
private func authAwareRequest(request: URLRequest, viaFile: Bool = false) async throws -> (AsyncThrowingChannel<Data, Error>, HTTPURLResponse) { private func authAwareRequest(request: URLRequest, viaFile: Bool = false) async throws -> (AsyncThrowingChannel<Data, Error>, HTTPURLResponse) {
var request = request var request = request
if let token = currentAuthToken { if let (name, value) = await authenticationKeeper.header() {
let (name, value) = token.header()
request.addValue(value, forHTTPHeaderField: name) request.addValue(value, forHTTPHeaderField: name)
} }
+8 -10
View File
@@ -60,7 +60,7 @@ struct Darwin: PlatformSuspendable {
let result = VZMacPlatformConfiguration() let result = VZMacPlatformConfiguration()
result.machineIdentifier = ecid result.machineIdentifier = ecid
result.auxiliaryStorage = VZMacAuxiliaryStorage(contentsOf: nvramURL) result.auxiliaryStorage = VZMacAuxiliaryStorage(url: nvramURL)
if !hardwareModel.isSupported { if !hardwareModel.isSupported {
// At the moment support of M1 chip is not yet dropped in any macOS version // At the moment support of M1 chip is not yet dropped in any macOS version
@@ -111,24 +111,22 @@ struct Darwin: PlatformSuspendable {
if #available(macOS 14, *) { if #available(macOS 14, *) {
return [VZMacKeyboardConfiguration()] return [VZMacKeyboardConfiguration()]
} else { } else {
return [] // fallback to the regular configuration
return keyboards()
} }
} }
func pointingDevices() -> [VZPointingDeviceConfiguration] { func pointingDevices() -> [VZPointingDeviceConfiguration] {
if #available(macOS 13, *) { // Trackpad is only supported by guests starting with macOS Ventura
// Trackpad is only supported by guests starting with macOS Ventura [VZMacTrackpadConfiguration(), VZUSBScreenCoordinatePointingDeviceConfiguration()]
return [VZMacTrackpadConfiguration(), VZUSBScreenCoordinatePointingDeviceConfiguration()]
} else {
return [VZUSBScreenCoordinatePointingDeviceConfiguration()]
}
} }
func pointingDevicesSuspendable() -> [VZPointingDeviceConfiguration] { func pointingDevicesSuspendable() -> [VZPointingDeviceConfiguration] {
if #available(macOS 13, *) { if #available(macOS 14, *) {
return [VZMacTrackpadConfiguration()] return [VZMacTrackpadConfiguration()]
} else { } else {
return [] // fallback to the regular configuration
return pointingDevices()
} }
} }
} }
+29 -20
View File
@@ -42,7 +42,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
init(vmDir: VMDirectory, init(vmDir: VMDirectory,
network: Network = NetworkShared(), network: Network = NetworkShared(),
additionalDiskAttachments: [VZDiskImageStorageDeviceAttachment] = [], additionalStorageDevices: [VZStorageDeviceConfiguration] = [],
directorySharingDevices: [VZDirectorySharingDeviceConfiguration] = [], directorySharingDevices: [VZDirectorySharingDeviceConfiguration] = [],
serialPorts: [VZSerialPortConfiguration] = [], serialPorts: [VZSerialPortConfiguration] = [],
suspendable: Bool = false suspendable: Bool = false
@@ -58,7 +58,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
self.network = network self.network = network
configuration = try Self.craftConfiguration(diskURL: vmDir.diskURL, configuration = try Self.craftConfiguration(diskURL: vmDir.diskURL,
nvramURL: vmDir.nvramURL, vmConfig: config, nvramURL: vmDir.nvramURL, vmConfig: config,
network: network, additionalDiskAttachments: additionalDiskAttachments, network: network, additionalStorageDevices: additionalStorageDevices,
directorySharingDevices: directorySharingDevices, directorySharingDevices: directorySharingDevices,
serialPorts: serialPorts, serialPorts: serialPorts,
suspendable: suspendable suspendable: suspendable
@@ -71,9 +71,11 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
static func retrieveIPSW(remoteURL: URL) async throws -> URL { static func retrieveIPSW(remoteURL: URL) async throws -> URL {
// Check if we already have this IPSW in cache // Check if we already have this IPSW in cache
let (channel, response) = try await Fetcher.fetch(URLRequest(url: remoteURL), viaFile: true) var headRequest = URLRequest(url: remoteURL)
headRequest.httpMethod = "HEAD"
let (_, headResponse) = try await Fetcher.fetch(headRequest, viaFile: false)
if let hash = response.value(forHTTPHeaderField: "x-amz-meta-digest-sha256") { if let hash = headResponse.value(forHTTPHeaderField: "x-amz-meta-digest-sha256") {
let ipswLocation = try IPSWCache().locationFor(fileName: "sha256:\(hash).ipsw") let ipswLocation = try IPSWCache().locationFor(fileName: "sha256:\(hash).ipsw")
if FileManager.default.fileExists(atPath: ipswLocation.path) { if FileManager.default.fileExists(atPath: ipswLocation.path) {
@@ -87,6 +89,8 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
// Download the IPSW // Download the IPSW
defaultLogger.appendNewLine("Fetching \(remoteURL.lastPathComponent)...") defaultLogger.appendNewLine("Fetching \(remoteURL.lastPathComponent)...")
let (channel, response) = try await Fetcher.fetch(URLRequest(url: remoteURL), viaFile: true)
let progress = Progress(totalUnitCount: response.expectedContentLength) let progress = Progress(totalUnitCount: response.expectedContentLength)
ProgressObserver(progress).log(defaultLogger) ProgressObserver(progress).log(defaultLogger)
@@ -138,7 +142,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
ipswURL: URL, ipswURL: URL,
diskSizeGB: UInt16, diskSizeGB: UInt16,
network: Network = NetworkShared(), network: Network = NetworkShared(),
additionalDiskAttachments: [VZDiskImageStorageDeviceAttachment] = [], additionalStorageDevices: [VZStorageDeviceConfiguration] = [],
directorySharingDevices: [VZDirectorySharingDeviceConfiguration] = [], directorySharingDevices: [VZDirectorySharingDeviceConfiguration] = [],
serialPorts: [VZSerialPortConfiguration] = [] serialPorts: [VZSerialPortConfiguration] = []
) async throws { ) async throws {
@@ -186,7 +190,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
self.network = network self.network = network
configuration = try Self.craftConfiguration(diskURL: vmDir.diskURL, nvramURL: vmDir.nvramURL, configuration = try Self.craftConfiguration(diskURL: vmDir.diskURL, nvramURL: vmDir.nvramURL,
vmConfig: config, network: network, vmConfig: config, network: network,
additionalDiskAttachments: additionalDiskAttachments, additionalStorageDevices: additionalStorageDevices,
directorySharingDevices: directorySharingDevices, directorySharingDevices: directorySharingDevices,
serialPorts: serialPorts serialPorts: serialPorts
) )
@@ -253,15 +257,9 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
@MainActor @MainActor
private func start(_ recovery: Bool) async throws { private func start(_ recovery: Bool) async throws {
if #available(macOS 13, *) { let startOptions = VZMacOSVirtualMachineStartOptions()
// new API introduced in Ventura startOptions.startUpFromMacOSRecovery = recovery
let startOptions = VZMacOSVirtualMachineStartOptions() try await virtualMachine.start(options: startOptions)
startOptions.startUpFromMacOSRecovery = recovery
try await virtualMachine.start(options: startOptions)
} else {
// use method that also available on Monterey
try await virtualMachine.start(recovery)
}
} }
@MainActor @MainActor
@@ -279,7 +277,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
nvramURL: URL, nvramURL: URL,
vmConfig: VMConfig, vmConfig: VMConfig,
network: Network = NetworkShared(), network: Network = NetworkShared(),
additionalDiskAttachments: [VZDiskImageStorageDeviceAttachment], additionalStorageDevices: [VZStorageDeviceConfiguration],
directorySharingDevices: [VZDirectorySharingDeviceConfiguration], directorySharingDevices: [VZDirectorySharingDeviceConfiguration],
serialPorts: [VZSerialPortConfiguration], serialPorts: [VZSerialPortConfiguration],
suspendable: Bool = false suspendable: Bool = false
@@ -328,9 +326,20 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
} }
// Storage // Storage
var attachments = [try VZDiskImageStorageDeviceAttachment(url: diskURL, readOnly: false)] let attachment: VZDiskImageStorageDeviceAttachment = vmConfig.os == .linux ?
attachments.append(contentsOf: additionalDiskAttachments) // Use "cached" caching mode for virtio drive to prevent fs corruption on linux
configuration.storageDevices = attachments.map { VZVirtioBlockDeviceConfiguration(attachment: $0) } try VZDiskImageStorageDeviceAttachment(url: diskURL, readOnly: false, cachingMode: .cached, synchronizationMode: .full) :
try VZDiskImageStorageDeviceAttachment(url: diskURL, readOnly: false)
var device: VZStorageDeviceConfiguration
if #available(macOS 14, *), vmConfig.os == .linux {
device = VZNVMExpressControllerDeviceConfiguration(attachment: attachment)
} else {
device = VZVirtioBlockDeviceConfiguration(attachment: attachment)
}
var devices: [VZStorageDeviceConfiguration] = [device]
devices.append(contentsOf: additionalStorageDevices)
configuration.storageDevices = devices
// Entropy // Entropy
if !suspendable { if !suspendable {
@@ -347,7 +356,7 @@ class VM: NSObject, VZVirtualMachineDelegate, ObservableObject {
// //
// A dummy console device useful for implementing // A dummy console device useful for implementing
// host feature checks in the guest agent software. // host feature checks in the guest agent software.
if #available(macOS 13, *) { if !suspendable {
let consolePort = VZVirtioConsolePortConfiguration() let consolePort = VZVirtioConsolePortConfiguration()
consolePort.name = "tart-version-\(CI.version)" consolePort.name = "tart-version-\(CI.version)"
+1 -5
View File
@@ -97,11 +97,7 @@ struct VMConfig: Codable {
case .darwin: case .darwin:
platform = try Darwin(from: decoder) platform = try Darwin(from: decoder)
case .linux: case .linux:
if #available(macOS 13, *) { platform = try Linux(from: decoder)
platform = try Linux(from: decoder)
} else {
throw UnsupportedOSError("Linux VMs", "are")
}
} }
cpuCountMin = try container.decode(Int.self, forKey: .cpuCountMin) cpuCountMin = try container.decode(Int.self, forKey: .cpuCountMin)
cpuCount = try container.decode(Int.self, forKey: .cpuCount) cpuCount = try container.decode(Int.self, forKey: .cpuCount)
+35 -62
View File
@@ -1,33 +1,30 @@
import Foundation import Foundation
import Compression
import Sentry import Sentry
enum OCIError: Error { enum OCIError: Error {
case ShouldBeExactlyOneLayer case ShouldBeExactlyOneLayer
case ShouldBeAtLeastOneLayer case ShouldBeAtLeastOneLayer
case FailedToCreateVmFile case FailedToCreateVmFile
case LayerIsMissingUncompressedSizeAnnotation
case LayerIsMissingUncompressedDigestAnnotation
} }
extension VMDirectory { extension VMDirectory {
private static let bufferSizeBytes = 64 * 1024 * 1024 private static let bufferSizeBytes = 64 * 1024 * 1024
private static let layerLimitBytes = 500 * 1000 * 1000 private static let layerLimitBytes = 500 * 1000 * 1000
private static let configMediaType = "application/vnd.cirruslabs.tart.config.v1" func pullFromRegistry(registry: Registry, reference: String, concurrency: UInt) async throws {
private static let diskMediaType = "application/vnd.cirruslabs.tart.disk.v1"
private static let nvramMediaType = "application/vnd.cirruslabs.tart.nvram.v1"
func pullFromRegistry(registry: Registry, reference: String) async throws {
defaultLogger.appendNewLine("pulling manifest...") defaultLogger.appendNewLine("pulling manifest...")
let (manifest, _) = try await registry.pullManifest(reference: reference) let (manifest, _) = try await registry.pullManifest(reference: reference)
return try await pullFromRegistry(registry: registry, manifest: manifest) return try await pullFromRegistry(registry: registry, manifest: manifest, concurrency: concurrency)
} }
func pullFromRegistry(registry: Registry, manifest: OCIManifest) async throws { func pullFromRegistry(registry: Registry, manifest: OCIManifest, concurrency: UInt) async throws {
// Pull VM's config file layer and re-serialize it into a config file // Pull VM's config file layer and re-serialize it into a config file
let configLayers = manifest.layers.filter { let configLayers = manifest.layers.filter {
$0.mediaType == Self.configMediaType $0.mediaType == configMediaType
} }
if configLayers.count != 1 { if configLayers.count != 1 {
throw OCIError.ShouldBeExactlyOneLayer throw OCIError.ShouldBeExactlyOneLayer
@@ -41,50 +38,36 @@ extension VMDirectory {
} }
try configFile.close() try configFile.close()
// Pull VM's disk layers and decompress them sequentially into a disk file // Pull VM's disk layers and decompress them into a disk file
let diskLayers = manifest.layers.filter { let diskImplType: Disk.Type
$0.mediaType == Self.diskMediaType let layers: [OCIManifestLayer]
}
if diskLayers.isEmpty { if manifest.layers.contains(where: { $0.mediaType == diskV1MediaType }) {
diskImplType = DiskV1.self
layers = manifest.layers.filter { $0.mediaType == diskV1MediaType }
} else if manifest.layers.contains(where: { $0.mediaType == diskV2MediaType }) {
diskImplType = DiskV2.self
layers = manifest.layers.filter { $0.mediaType == diskV2MediaType }
} else {
throw OCIError.ShouldBeAtLeastOneLayer throw OCIError.ShouldBeAtLeastOneLayer
} }
if !FileManager.default.createFile(atPath: diskURL.path, contents: nil) {
throw OCIError.FailedToCreateVmFile
}
let disk = try FileHandle(forWritingTo: diskURL)
let filter = try OutputFilter(.decompress, using: .lz4, bufferCapacity: Self.bufferSizeBytes) { data in
if let data = data {
disk.write(data)
}
}
// Progress let diskCompressedSize = layers.map { Int64($0.size) }.reduce(0, +)
let diskCompressedSize: Int64 = Int64(diskLayers.map { SentrySDK.span?.setMeasurement(name: "compressed_disk_size", value: diskCompressedSize as NSNumber, unit: MeasurementUnitInformation.byte)
$0.size
}
.reduce(0) {
$0 + $1
})
let prettyDiskSize = String(format: "%.1f", Double(diskCompressedSize) / 1_000_000_000.0) let prettyDiskSize = String(format: "%.1f", Double(diskCompressedSize) / 1_000_000_000.0)
defaultLogger.appendNewLine("pulling disk (\(prettyDiskSize) GB compressed)...") defaultLogger.appendNewLine("pulling disk (\(prettyDiskSize) GB compressed)...")
let progress = Progress(totalUnitCount: diskCompressedSize) let progress = Progress(totalUnitCount: diskCompressedSize)
ProgressObserver(progress).log(defaultLogger) ProgressObserver(progress).log(defaultLogger)
for diskLayer in diskLayers { try await diskImplType.pull(registry: registry, diskLayers: layers, diskURL: diskURL, concurrency: concurrency, progress: progress)
try await registry.pullBlob(diskLayer.digest) { data in
try filter.write(data)
progress.completedUnitCount += Int64(data.count)
}
}
try filter.finalize()
try disk.close()
SentrySDK.span?.setMeasurement(name: "compressed_disk_size", value: diskCompressedSize as NSNumber, unit: MeasurementUnitInformation.byte);
// Pull VM's NVRAM file layer and store it in an NVRAM file // Pull VM's NVRAM file layer and store it in an NVRAM file
defaultLogger.appendNewLine("pulling NVRAM...") defaultLogger.appendNewLine("pulling NVRAM...")
let nvramLayers = manifest.layers.filter { let nvramLayers = manifest.layers.filter {
$0.mediaType == Self.nvramMediaType $0.mediaType == nvramMediaType
} }
if nvramLayers.count != 1 { if nvramLayers.count != 1 {
throw OCIError.ShouldBeExactlyOneLayer throw OCIError.ShouldBeExactlyOneLayer
@@ -99,7 +82,7 @@ extension VMDirectory {
try nvram.close() try nvram.close()
} }
func pushToRegistry(registry: Registry, references: [String], chunkSizeMb: Int) async throws -> RemoteName { func pushToRegistry(registry: Registry, references: [String], chunkSizeMb: Int, diskFormat: String) async throws -> RemoteName {
var layers = Array<OCIManifestLayer>() var layers = Array<OCIManifestLayer>()
// Read VM's config and push it as blob // Read VM's config and push it as blob
@@ -107,32 +90,22 @@ extension VMDirectory {
let configJSON = try JSONEncoder().encode(config) let configJSON = try JSONEncoder().encode(config)
defaultLogger.appendNewLine("pushing config...") defaultLogger.appendNewLine("pushing config...")
let configDigest = try await registry.pushBlob(fromData: configJSON, chunkSizeMb: chunkSizeMb) let configDigest = try await registry.pushBlob(fromData: configJSON, chunkSizeMb: chunkSizeMb)
layers.append(OCIManifestLayer(mediaType: Self.configMediaType, size: configJSON.count, digest: configDigest)) layers.append(OCIManifestLayer(mediaType: configMediaType, size: configJSON.count, digest: configDigest))
// Progress // Compress the disk file as multiple chunks and push them as disk layers
let diskSize = try FileManager.default.attributesOfItem(atPath: diskURL.path)[.size] as! Int64 let diskSize = try FileManager.default.attributesOfItem(atPath: diskURL.path)[.size] as! Int64
defaultLogger.appendNewLine("pushing disk... this will take a while...") defaultLogger.appendNewLine("pushing disk... this will take a while...")
let progress = Progress(totalUnitCount: diskSize) let progress = Progress(totalUnitCount: diskSize)
ProgressObserver(progress).log(defaultLogger) ProgressObserver(progress).log(defaultLogger)
// Read VM's compressed disk as chunks switch diskFormat {
// and sequentially upload them as blobs case "v1":
let mappedDisk = try Data(contentsOf: diskURL, options: [.alwaysMapped]) layers.append(contentsOf: try await DiskV1.push(diskURL: diskURL, registry: registry, chunkSizeMb: chunkSizeMb, progress: progress))
let mappedDiskSize = mappedDisk.count case "v2":
var mappedDiskReadOffset = 0 layers.append(contentsOf: try await DiskV2.push(diskURL: diskURL, registry: registry, chunkSizeMb: chunkSizeMb, progress: progress))
let compressingFilter = try InputFilter(.compress, using: .lz4, bufferCapacity: Self.bufferSizeBytes) { (length: Int) -> Data? in default:
let bytesRead = min(length, mappedDiskSize - mappedDiskReadOffset) throw RuntimeError.OCIUnsupportedDiskFormat(diskFormat)
let data = mappedDisk.subdata(in: mappedDiskReadOffset ..< mappedDiskReadOffset + bytesRead)
mappedDiskReadOffset += bytesRead
progress.completedUnitCount = Int64(mappedDiskReadOffset)
return data
}
while let compressedLayerData = try compressingFilter.readData(ofLength: Self.layerLimitBytes) {
let layerDigest = try await registry.pushBlob(fromData: compressedLayerData, chunkSizeMb: chunkSizeMb)
layers.append(OCIManifestLayer(mediaType: Self.diskMediaType, size: compressedLayerData.count, digest: layerDigest))
} }
// Read VM's NVRAM and push it as blob // Read VM's NVRAM and push it as blob
@@ -140,7 +113,7 @@ extension VMDirectory {
let nvram = try FileHandle(forReadingFrom: nvramURL).readToEnd()! let nvram = try FileHandle(forReadingFrom: nvramURL).readToEnd()!
let nvramDigest = try await registry.pushBlob(fromData: nvram, chunkSizeMb: chunkSizeMb) let nvramDigest = try await registry.pushBlob(fromData: nvram, chunkSizeMb: chunkSizeMb)
layers.append(OCIManifestLayer(mediaType: Self.nvramMediaType, size: nvram.count, digest: nvramDigest)) layers.append(OCIManifestLayer(mediaType: nvramMediaType, size: nvram.count, digest: nvramDigest))
// Craft a stub OCI config for Docker Hub compatibility // Craft a stub OCI config for Docker Hub compatibility
let ociConfigJSON = try OCIConfig(architecture: config.arch, os: config.os).toJSON() let ociConfigJSON = try OCIConfig(architecture: config.arch, os: config.os).toJSON()
@@ -148,7 +121,7 @@ extension VMDirectory {
let manifest = OCIManifest( let manifest = OCIManifest(
config: OCIManifestConfig(size: ociConfigJSON.count, digest: ociConfigDigest), config: OCIManifestConfig(size: ociConfigJSON.count, digest: ociConfigDigest),
layers: layers, layers: layers,
uncompressedDiskSize: UInt64(mappedDiskReadOffset), uncompressedDiskSize: UInt64(diskSize),
uploadDate: Date() uploadDate: Date()
) )
+13 -1
View File
@@ -30,13 +30,17 @@ struct VMDirectory: Prunable {
baseURL baseURL
} }
func lock() throws -> PIDLock {
try PIDLock(lockURL: configURL)
}
func running() throws -> Bool { func running() throws -> Bool {
// The most common reason why PIDLock() instantiation fails is a race with "tart delete" (ENOENT), // The most common reason why PIDLock() instantiation fails is a race with "tart delete" (ENOENT),
// which is fine to report as "not running". // which is fine to report as "not running".
// //
// The other reasons are unlikely and the cost of getting a false positive is way less than // The other reasons are unlikely and the cost of getting a false positive is way less than
// the cost of crashing with an exception when calling "tart list" on a busy machine, for example. // the cost of crashing with an exception when calling "tart list" on a busy machine, for example.
guard let lock = try? PIDLock(lockURL: configURL) else { guard let lock = try? lock() else {
return false return false
} }
@@ -137,7 +141,15 @@ struct VMDirectory: Prunable {
} }
func delete() throws { func delete() throws {
let lock = try lock()
if try !lock.trylock() {
throw RuntimeError.VMIsRunning(name)
}
try FileManager.default.removeItem(at: baseURL) try FileManager.default.removeItem(at: baseURL)
try lock.unlock()
} }
func accessDate() throws -> Date { func accessDate() throws -> Date {
+18 -4
View File
@@ -34,9 +34,15 @@ class VMStorageHelper {
} }
} }
extension NSError {
func isFileNotFound() -> Bool {
return self.code == NSFileNoSuchFileError || self.code == NSFileReadNoSuchFileError
}
}
extension Error { extension Error {
func isFileNotFound() -> Bool { func isFileNotFound() -> Bool {
(self as NSError).code == NSFileReadNoSuchFileError (self as NSError).isFileNotFound() || (self as NSError).underlyingErrors.contains(where: { $0.isFileNotFound() })
} }
} }
@@ -44,7 +50,8 @@ enum RuntimeError : Error {
case VMConfigurationError(_ message: String) case VMConfigurationError(_ message: String)
case VMDoesNotExist(name: String) case VMDoesNotExist(name: String)
case VMMissingFiles(_ message: String) case VMMissingFiles(_ message: String)
case VMNotRunning(_ message: String) case VMIsRunning(_ name: String)
case VMNotRunning(_ name: String)
case VMAlreadyRunning(_ message: String) case VMAlreadyRunning(_ message: String)
case NoIPAddressFound(_ message: String) case NoIPAddressFound(_ message: String)
case DiskAlreadyInUse(_ message: String) case DiskAlreadyInUse(_ message: String)
@@ -58,6 +65,7 @@ enum RuntimeError : Error {
case ImportFailed(_ message: String) case ImportFailed(_ message: String)
case SoftnetFailed(_ message: String) case SoftnetFailed(_ message: String)
case OCIStorageError(_ message: String) case OCIStorageError(_ message: String)
case OCIUnsupportedDiskFormat(_ format: String)
case SuspendFailed(_ message: String) case SuspendFailed(_ message: String)
} }
@@ -74,8 +82,10 @@ extension RuntimeError : CustomStringConvertible {
return "the specified VM \"\(name)\" does not exist" return "the specified VM \"\(name)\" does not exist"
case .VMMissingFiles(let message): case .VMMissingFiles(let message):
return message return message
case .VMNotRunning(let message): case .VMIsRunning(let name):
return message return "VM \"\(name)\" is running"
case .VMNotRunning(let name):
return "VM \"\(name)\" is not running"
case .VMAlreadyRunning(let message): case .VMAlreadyRunning(let message):
return message return message
case .NoIPAddressFound(let message): case .NoIPAddressFound(let message):
@@ -102,6 +112,8 @@ extension RuntimeError : CustomStringConvertible {
return "Softnet failed: \(message)" return "Softnet failed: \(message)"
case .OCIStorageError(let message): case .OCIStorageError(let message):
return "OCI storage error: \(message)" return "OCI storage error: \(message)"
case .OCIUnsupportedDiskFormat(let format):
return "OCI disk format \(format) is not supported by this version of Tart"
case .SuspendFailed(let message): case .SuspendFailed(let message):
return "Failed to suspend the VM: \(message)" return "Failed to suspend the VM: \(message)"
} }
@@ -111,6 +123,8 @@ extension RuntimeError : CustomStringConvertible {
extension RuntimeError : HasExitCode { extension RuntimeError : HasExitCode {
var exitCode: Int32 { var exitCode: Int32 {
switch self { switch self {
case .VMDoesNotExist:
return 2
case .VMNotRunning: case .VMNotRunning:
return 2 return 2
case .VMAlreadyRunning: case .VMAlreadyRunning:
+1 -1
View File
@@ -39,7 +39,7 @@ class VMStorageLocal: PrunableStorage {
} }
func delete(_ name: String) throws { func delete(_ name: String) throws {
try FileManager.default.removeItem(at: vmURL(name)) try VMDirectory(baseURL: vmURL(name)).delete()
} }
func list() throws -> [(String, VMDirectory)] { func list() throws -> [(String, VMDirectory)] {
+3 -5
View File
@@ -132,7 +132,7 @@ class VMStorageOCI: PrunableStorage {
try list().filter { (_, _, isSymlink) in !isSymlink }.map { (_, vmDir, _) in vmDir } try list().filter { (_, _, isSymlink) in !isSymlink }.map { (_, vmDir, _) in vmDir }
} }
func pull(_ name: RemoteName, registry: Registry) async throws { func pull(_ name: RemoteName, registry: Registry, concurrency: UInt) async throws {
SentrySDK.configureScope { scope in SentrySDK.configureScope { scope in
scope.setContext(value: ["imageName": name], key: "OCI") scope.setContext(value: ["imageName": name], key: "OCI")
} }
@@ -188,7 +188,7 @@ class VMStorageOCI: PrunableStorage {
} }
try await withTaskCancellationHandler(operation: { try await withTaskCancellationHandler(operation: {
try await tmpVMDir.pullFromRegistry(registry: registry, manifest: manifest) try await tmpVMDir.pullFromRegistry(registry: registry, manifest: manifest, concurrency: concurrency)
try move(digestName, from: tmpVMDir) try move(digestName, from: tmpVMDir)
transaction.finish() transaction.finish()
}, onCancel: { }, onCancel: {
@@ -219,9 +219,7 @@ class VMStorageOCI: PrunableStorage {
} }
func link(from: RemoteName, to: RemoteName) throws { func link(from: RemoteName, to: RemoteName) throws {
if FileManager.default.fileExists(atPath: vmURL(from).path) { try? FileManager.default.removeItem(at: vmURL(from))
try FileManager.default.removeItem(at: vmURL(from))
}
try FileManager.default.createSymbolicLink(at: vmURL(from), withDestinationURL: vmURL(to)) try FileManager.default.createSymbolicLink(at: vmURL(from), withDestinationURL: vmURL(to))
+16
View File
@@ -0,0 +1,16 @@
import XCTest
@testable import tart
final class DockerConfigTests: XCTestCase {
func testHelpers() throws {
let config = DockerConfig(credHelpers: [
"(.*).dkr.ecr.(.*).amazonaws.com": "ecr-login",
"gcr.io": "gcloud"
])
XCTAssertEqual(try config.findCredHelper(host: "gcr.io"), "gcloud")
XCTAssertEqual(try config.findCredHelper(host: "123.dkr.ecr.eu-west-1.amazonaws.com"), "ecr-login")
XCTAssertEqual(try config.findCredHelper(host: "456.dkr.ecr.us-east-1.amazonaws.com"), "ecr-login")
XCTAssertNil(try config.findCredHelper(host: "ghcr.io"))
}
}
+90
View File
@@ -0,0 +1,90 @@
import XCTest
@testable import tart
final class LayerizerTests: XCTestCase {
var registryRunner: RegistryRunner?
var registry: Registry {
registryRunner!.registry
}
override func setUp() async throws {
try await super.setUp()
do {
registryRunner = try await RegistryRunner()
} catch {
try XCTSkipIf(ProcessInfo.processInfo.environment["CI"] == nil)
}
}
override func tearDown() async throws {
try await super.tearDown()
registryRunner = nil
}
func testDiskV1() async throws {
// Original disk file to be pushed to the registry
let originalDiskFileURL = try fileWithRandomData(sizeBytes: 5 * 1024 * 1024 * 1024)
addTeardownBlock {
try FileManager.default.removeItem(at: originalDiskFileURL)
}
// Disk file to be pulled from the registry
// and compared against the original disk file
let pulledDiskFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
print("pushing disk...")
let diskLayers = try await DiskV1.push(diskURL: originalDiskFileURL, registry: registry, chunkSizeMb: 0, progress: Progress())
print("pulling disk...")
try await DiskV1.pull(registry: registry, diskLayers: diskLayers, diskURL: pulledDiskFileURL, concurrency: 16, progress: Progress())
print("comparing disks...")
try XCTAssertEqual(Digest.hash(originalDiskFileURL), Digest.hash(pulledDiskFileURL))
}
func testDiskV2() async throws {
// Original disk file to be pushed to the registry
let originalDiskFileURL = try fileWithRandomData(sizeBytes: 5 * 1024 * 1024 * 1024)
addTeardownBlock {
try FileManager.default.removeItem(at: originalDiskFileURL)
}
// Disk file to be pulled from the registry
// and compared against the original disk file
let pulledDiskFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
print("pushing disk...")
let diskLayers = try await DiskV2.push(diskURL: originalDiskFileURL, registry: registry, chunkSizeMb: 0, progress: Progress())
print("pulling disk...")
try await DiskV2.pull(registry: registry, diskLayers: diskLayers, diskURL: pulledDiskFileURL, concurrency: 16, progress: Progress())
print("comparing disks...")
try XCTAssertEqual(Digest.hash(originalDiskFileURL), Digest.hash(pulledDiskFileURL))
}
private func fileWithRandomData(sizeBytes: Int) throws -> URL {
let devUrandom = try FileHandle(forReadingFrom: URL(filePath: "/dev/urandom"))
let temporaryFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
FileManager.default.createFile(atPath: temporaryFileURL.path, contents: nil)
let temporaryFile = try FileHandle(forWritingTo: temporaryFileURL)
var remainingBytes = sizeBytes
while remainingBytes > 0 {
let randomData = try devUrandom.read(upToCount: min(64 * 1024 * 1024, remainingBytes))!
remainingBytes -= randomData.count
try temporaryFile.write(contentsOf: randomData)
}
try devUrandom.close()
try temporaryFile.close()
return temporaryFileURL
}
}
+18
View File
@@ -0,0 +1,18 @@
import XCTest
@testable import tart
import Network
import SwiftRadix
final class LeaseTests: XCTestCase {
func testCorrectTimezone() throws {
let lease = Lease(fromRawLease: [
"hw_address": "1,11:22:33:44:55:66",
"ip_address": "1.2.3.4",
"lease": "0x6565da9e",
])
XCTAssertNotNil(lease)
XCTAssertEqual(lease!.expiresAt.toISO(), "2023-11-28T12:18:38Z")
}
}
+38
View File
@@ -0,0 +1,38 @@
import XCTest
@testable import tart
import Network
import SwiftDate
final class LeasesTests: XCTestCase {
func testNoExpired() throws {
let macAddress = MACAddress(fromString: "11:22:33:44:55:66")!
let leases = try Leases("""
{
name=whatever
ip_address=66.66.66.66
hw_address=1,\(macAddress)
identifier=1,\(macAddress)
lease=\(Int((Date() - 1.seconds).timeIntervalSince1970).hex)
}
{
name=whatever
ip_address=1.2.3.4
hw_address=1,\(macAddress)
identifier=1,\(macAddress)
lease=\(Int((Date() + 10.minutes).timeIntervalSince1970).hex)
}
{
name=whatever
ip_address=66.66.66.66
hw_address=1,\(macAddress)
identifier=1,\(macAddress)
lease=\(Int((Date() - 1.seconds).timeIntervalSince1970).hex)
}
""")
XCTAssertEqual(IPv4Address("1.2.3.4"), leases.ResolveMACAddress(macAddress: macAddress))
}
}
@@ -8,11 +8,12 @@ final class MACAddressResolverTests: XCTestCase {
{ {
ip_address=1.2.3.4 ip_address=1.2.3.4
hw_address=1,00:11:22:33:44:55 hw_address=1,00:11:22:33:44:55
lease=0x7fffffff
} }
""") """)
XCTAssertEqual(IPv4Address("1.2.3.4"), XCTAssertEqual(IPv4Address("1.2.3.4"),
try leases.ResolveMACAddress(macAddress: MACAddress(fromString: "00:11:22:33:44:55")!)) leases.ResolveMACAddress(macAddress: MACAddress(fromString: "00:11:22:33:44:55")!))
} }
func testMultipleEntries() throws { func testMultipleEntries() throws {
@@ -20,16 +21,18 @@ final class MACAddressResolverTests: XCTestCase {
{ {
ip_address=1.2.3.4 ip_address=1.2.3.4
hw_address=1,00:11:22:33:44:55 hw_address=1,00:11:22:33:44:55
lease=0x7fffffff
} }
{ {
ip_address=5.6.7.8 ip_address=5.6.7.8
hw_address=1,AA:BB:CC:DD:EE:FF hw_address=1,AA:BB:CC:DD:EE:FF
lease=0x7fffffff
} }
""") """)
XCTAssertEqual(IPv4Address("1.2.3.4"), XCTAssertEqual(IPv4Address("1.2.3.4"),
try leases.ResolveMACAddress(macAddress: MACAddress(fromString: "00:11:22:33:44:55")!)) leases.ResolveMACAddress(macAddress: MACAddress(fromString: "00:11:22:33:44:55")!))
XCTAssertEqual(IPv4Address("5.6.7.8"), XCTAssertEqual(IPv4Address("5.6.7.8"),
try leases.ResolveMACAddress(macAddress: MACAddress(fromString: "AA:BB:CC:DD:EE:FF")!)) leases.ResolveMACAddress(macAddress: MACAddress(fromString: "AA:BB:CC:DD:EE:FF")!))
} }
} }
+12
View File
@@ -0,0 +1,12 @@
"default": true
"MD002": false # First heading should be a top level heading
"MD007": # Unordered list indentation
indent: 4
"MD009": false # Trailing spaces
"MD013": false # Line length
"MD025": false # Multiple top level headings in the same document
"MD026": false # Trailing punctuation in heading
"MD033": false # Inline HTML
"MD041": false # First line in file should be a top level heading
"MD045": false # OK not to have a description for an image
"MD046": false # Code block style [Expected: fenced; Actual: indented]
Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 602 KiB

+9 -8
View File
@@ -1,8 +1,9 @@
edigaryev: authors:
name: Nikolay Edigaryev edigaryev:
description: Creator name: Nikolay Edigaryev
avatar: https://github.com/edigaryev.png description: Creator
fkorotkov: avatar: https://github.com/edigaryev.png
name: Fedor Korotkov fkorotkov:
description: Creator name: Fedor Korotkov
avatar: https://github.com/fkorotkov.png description: Creator
avatar: https://github.com/fkorotkov.png
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 602 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 538 KiB

@@ -56,7 +56,7 @@ On bootstrap, each Orchard worker establishes a `Watch()` RPC stream and waits f
Once `PortForward` instruction is received, the worker connects to the specified VM and port locally and opens a new `PortForward()` RPC stream with the controller, carrying the unique `session` identifier in the gRPC metadata to help distinguish several port forwarding requests. Once `PortForward` instruction is received, the worker connects to the specified VM and port locally and opens a new `PortForward()` RPC stream with the controller, carrying the unique `session` identifier in the gRPC metadata to help distinguish several port forwarding requests.
We’re using a pretty ingenious Golang package that turns any gRPC stream into a `net.Conn`: https://github.com/mitchellh/go-grpc-net-conn. This allows us to abstract from the gRPC details and simply proxy two `net.Conns`, thus providing the port forwarding functionality. We’re using a pretty ingenious [Golang package that turns any gRPC stream into a `net.Conn`](https://github.com/mitchellh/go-grpc-net-conn). This allows us to abstract from the gRPC details and simply proxy two `net.Conns`, thus providing the port forwarding functionality.
We’ve also initially considered using [Yamux](https://github.com/hashicorp/yamux) to only keep a single connection with each worker, however, that involves the burden of dealing with flow control and potential implementation bugs associated with it, so we’ve decided to simply open an additional connection for each port forwarding session and let the OS deal with it. We’ve also initially considered using [Yamux](https://github.com/hashicorp/yamux) to only keep a single connection with each worker, however, that involves the burden of dealing with flow control and potential implementation bugs associated with it, so we’ve decided to simply open an additional connection for each port forwarding session and let the OS deal with it.
@@ -74,25 +74,25 @@ Secondly, we’ve exposed three commands in the Orchard CLI that all use this en
Opens a TCP port locally and forwards everything sent to it to the specified VM (and vice versa). Opens a TCP port locally and forwards everything sent to it to the specified VM (and vice versa).
For example, `orchard port-forward vm ventura-builder 2222:22` will forward traffic from the local TCP port `2222` to the `ventura-builder` VM’s TCP port `22`. For example, `orchard port-forward vm sonoma-builder 2222:22` will forward traffic from the local TCP port `2222` to the `ventura-builder` VM’s TCP port `22`.
### `orchard ssh` ### `orchard ssh`
Connects to the specified VM on the default SSH port `22`, optionally only launching a command (if specified), similarly to what the official OpenSSH client does. Connects to the specified VM on the default SSH port `22`, optionally only launching a command (if specified), similarly to what the official OpenSSH client does.
For example, `orchard ssh vm ventura-builder` will open an interactive session with the `ventura-builder` VM. For example, `orchard ssh vm sonoma-builder` will open an interactive session with the `ventura-builder` VM.
You can also send local scripts for execution by utilizing redirection: You can also send local scripts for execution by utilizing redirection:
```shell ```shell
orchard ssh vm ventura-builder 'sh -s' < script.sh orchard ssh vm sonoma-builder 'sh -s' < script.sh
``` ```
### `orchard vnc` ### `orchard vnc`
Establishes a port forwarding to the specified VM’s default VNC port `5900` and opens the default macOS Screen Sharing app. Establishes a port forwarding to the specified VM’s default VNC port `5900` and opens the default macOS Screen Sharing app.
For example, `orchard vnc vm ventura-builder` will establish a port-forwarding to the `ventura-builder` VM's port `5900` under the hood and launch macOS Screen Sharing app. For example, `orchard vnc vm sonoma-builder` will establish a port-forwarding to the `ventura-builder` VM's port `5900` under the hood and launch macOS Screen Sharing app.
Note that the SSH and VNC commands expect the VM resource to specify credentials in it’s definition (can be done via `orchard create vm`), and will otherwise fall back to the credentials specified by `--username` and `--password`, or if none specified — to de-facto standard of `admin:admin` credentials. Note that the SSH and VNC commands expect the VM resource to specify credentials in it’s definition (can be done via `orchard create vm`), and will otherwise fall back to the credentials specified by `--username` and `--password`, or if none specified — to de-facto standard of `admin:admin` credentials.
+104
View File
@@ -0,0 +1,104 @@
---
draft: false
date: 2023-09-20
search:
exclude: true
authors:
- fkorotkov
categories:
- announcement
---
# Tart 2.0.0 and community updates
Today we'd like to share some news and updates around the Tart ecosystem since the Tart 1.0.0 release back in February.
<!-- more -->
## Community Growth
In the last 7 months Tart community almost tripled and growth is continuing to accelerate. Tart just crossed 25,000 installations,
dozens of companies that we know of are using Tart in their daily workflows. If your company is not in the list please consider
[joining](https://github.com/cirruslabs/tart/blob/main/Resources/Users/HowToAddYourself.md)!
<div class="grid cards" markdown>
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Krisp.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Mullvad.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/ahrefs.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Suran.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Symflower.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Transloadit.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/PITSGlobalDataRecoveryServices.png){ height="65" }
- ![](https://github.com/cirruslabs/tart/raw/main/Resources/Users/Uphold.png){ height="65" }
</div>
We are also very pleased by how the community responded to [the license change](2023-02-11-changing-tart-license.md).
We now have a number of companies running Tart at scale under the new license. Revenue from the licensing allowed us to
allocate time to continue improving Tart which brings us to the section below.
## Recent updates and what's changing in Tart 2.0.0
In the last 7 months we've had 12 feature releases that brought a lot of features requested by the community. Here are just
a few of them to highlight:
-[Custom GitLab Runner Executor](/integrations/gitlab-runner/).
-[Cluster Management via Orchard](2023-04-25-orchard-ga.md).
-Numerous compatibility improvements for all kinds of OCI-registries.
-Sonoma Support (see details [below](#macos-sonoma-updates)).
But one of the most requested features/complaints was around pulling huge Tart images from remote OCI-compatible registries.
With an ideal network conditions `tart pull` worked pretty good but in case of any network issues it was required to
restart the pull from scratch. Additionally, some registries are notably slow streaming a single blob but can stream
multiple blobs in parallel. Finally, the initial format of storing Tart VMs was very naive: disk image is compressed
via a single stream which is chunked up into blobs that are serially uploaded to a registry. A single compression stream
means that Tart can also only decompress blobs serially.
Given these three observations above we came up with an improved format of storing Tart VM disk images. In Tart 2.0.0
disk images are chunked up first and compressed independently into blobs, when pushed, each blob has attached annotations
of expected uncompressed size and a checksum. This way when Tart 2.0.0 is pulling an image pushed by Tart 2.0.0 each blob can
be pulled, uncompressed and written at the right offset independently. Having checksums along expected uncompressed blob size
also allowed to support resumable pulls. Upon a failure Tart 2.0.0 will compare checksums of chunks and will continue pulling
only missing blobs.
Overall in our experiments we saw a 10% improvement in compressed size of the images and **4 times faster pulls**.
In order to try the new image format please upgrade Tart and try to pull any of [the Sonoma images](https://github.com/orgs/cirruslabs/packages?tab=packages&q=macos-sonoma):
```bash
brew upgrade cirruslabs/cli/tart
tart pull ghcr.io/cirruslabs/macos-sonoma-base:latest
```
## macOS Sonoma Updates
Tart VMs now can be run in a "suspendable" mode which will enable VM snapshotting instead of the standard shutdown.
VMs with an existing snapshot will `run` from the same state as they got snapshotted. Please check demo down below:
<div>
<blockquote class="twitter-tweet" data-theme="dark">
<p lang="en" dir="ltr">
Tart 1.8.0 brings macOS Sonoma updates! 🍏 Now you can suspend and resume your virtual machines for even faster startup times. Check out the demo below 👇 <a href="https://t.co/RoRFT8Nwst">pic.twitter.com/RoRFT8Nwst</a>
</p>&mdash; Cirrus Labs (@cirrus_labs) <a href="https://twitter.com/cirrus_labs/status/1677308360385765382?ref_src=twsrc%5Etfw">July 7, 2023</a>
</blockquote>
<script src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
</div>
There are two caveats to the "suspendable" mode support:
1. Both host and guest should be running macOS Sonoma.
2. Snapshots are locally encrypted and can't be shared between physical hosts. Therefore `tart push` won't push the corresponding snapshotted state of the VM.
Try the "suspendable" mode for yourself by passing `--suspendable` flag to a `tart run` command:
```bash
tart clone ghcr.io/cirruslabs/macos-sonoma-base:latest sonoma-base
tart run --suspendable sonoma-base
```
## Conclusion
We are very excited about this major release of Tart. Please give it a try and let us know how it went!
Stay tuned for new updates and announcements! There are a few coming up very shortly...
+71
View File
@@ -0,0 +1,71 @@
---
draft: false
date: 2023-10-06
search:
exclude: true
authors:
- fkorotkov
categories:
- announcement
---
# Tart is now available on AWS Marketplace
Announcing [official AMIs for EC2 Mac Instances](https://aws.amazon.com/marketplace/pp/prodview-qczco34wlkdws)
with preconfigured Tart installation that is optimized to work within AWS infrastructure.
EC2 Mac Instances is a gem of engineering powered by AWS Nitro devices. Just imagine there is a physical Mac Mini with
a plugged in Nitro device that can push the physical power button!
![EC2 M2 Pro](/blog/images/ec2-mac2-m2pro.png)
This clever synergy between Apple Hardware and Nitro System allows seamless integration with VPC networking and booting macOS from an EBS volume.
In this blog post we’ll see how a virtualization solution like Tart can compliment and elevate experience with EC2 Mac Instances.
<!-- more -->
Let’s start from the basics, what EC2 Mac Instances allow to do compared to physical Mac Minis seating in offices of
many companies around the world?
First and foremost, EC2 Mac Instances sit inside AWS data centers and can leverage all the goodies of VPC networking
within your company's existing infrastructure. No need to connect your Macs in the office through a VPN and deal
with networking and security.
Additionally, EC2 Mac Instances are booting from EBS volumes which means it is possible to always have reproducible instances
and apply all the best practices of Infrastructure-as-Code. Managing a fleet of physical Macs is a pain and it's very hard
to make them configured in a reproducible and stable way. With booting from identical EBS volumes your team is always sure
about the identical initial state of the fleet.
## Compromises of EC2 Mac Instances
The flexibility of EBS volumes for macOS comes with some compromises that virtualization solutions like Tart can help with.
The initial boot from an EBS volume takes some time and not instant. macOS itself is pretty heavy and a Nitro device needs
to download tens of gigabytes that macOS requires in order to boot. This means that **resetting a EC2 Mac Instance to a clean state
is not instant and usually takes a couple of minutes** when you can’t utilize the precious resources for your workloads.
It is much easier to tailor such EBS volumes with tools like Packer but there is still a **friction to test newly created EBS volumes**
since one needs to start and run a EC2 Mac Instance and it’s not possible to test things locally. Similarly it is even harder
to test beta versions of macOS that require manual interaction with a running instance.
## Solution
Tart can help with all the compromises! Tart virtual machines (VMs) have nearly native performance thanks to utilizing
native `Virtualization.Framework` that was developed along the first Apple Silicon chip. **Tart VMs can be copied/disposed
instantly and booting a fresh Tart VM takes only several seconds**. It is also possible to run two different Tart VMs in parallel
that can have completely different versions of macOS and packages. For example, it is possible to have the latest stable macOS
with the release version of Xcode along with the next version of macOS with the latest beta of Xcode.
Creation of Tart VMs can be automated with [a Packer plugin](https://github.com/cirruslabs/packer-plugin-tart) the same way as
creation of EC2 AMIs with one caveat that **Tart Packer Plugin works locally so you can test the same virtual machine locally
as you would run it in the cloud**.
Lightweight nature of Tart VMs with a focus on an easy-to-integrate Tart CLI compliments any macOS automation and helps to reduce
the feedback cycle and improves reproducibility of macOS environments even further.
## Conclusion
We are excited to bring [official AMIs that include Tart installation optimized to work within AWS](https://aws.amazon.com/marketplace/pp/prodview-qczco34wlkdws).
In the coming weeks when macOS Sonoma will become available on AWS we’ll release another update specifically targeting EC2 Mac Instances.
This update will simplify access to local SSDs of Mac Instances that are slightly faster than EBS volumes. Stay tuned and don’t hesitate
to ask any [questions](https://tart.run/licensing/).
@@ -0,0 +1,59 @@
---
draft: false
date: 2023-11-03
search:
exclude: true
authors:
- fkorotkov
categories:
- announcement
---
# New dashboard with insights into performance of Cirrus Runners
This month we are celebrating one year since launching Cirrus Runners — managed Apple Silicon infrastructure for your
GitHub Actions. During the last 12 months we ran millions of workflows for our customers and now ready to share some insights
into price performance of them for our customers.
One of the key difference with Cirrus Runners is how they are getting billed for. Customers purchase Cirrus Runners via monthly subscription
that costs $150 per each Cirrus Runner. Each runner can be used 24 hours a day 7 days a week to run GitHub Actions workflows
for an organization. If there are more outstanding jobs than available runners then they are queued and executed as soon as
there is a free runner. This is different from how GitHub-managed GitHub Actions are billed for — you pay for each minute of execution time.
The benefit of a fixed price is that you can run as many jobs as you want without worrying about the cost. The downside is that
you need to make sure that you are using your runners efficiently. This is where the new dashboard comes in handy.
<!-- more -->
But first, **let's see theoretically the lowest price per minute** of a Cirrus Runners. If you run 24 hours a day 7 days a week
then you will get 43,200 minutes of execution time per month. This means that the price per minute is $0.0035 if your runners
utilization is 100%. But even if your engineering teams is located in a single time zone and works 8 hours a day 5 days a week
then you will get 9,600 minutes of execution time per month which comes down to $0.015 per-minute. This is still more than 10 times cheaper
than recently announced Apple Silicon GitHub-manged runners that cost $0.16 per minute.
Now lets take a look at the new Cirrus Runners dashboard of a real customers that run their workflows on Cirrus Runners
and **practically pushing the price performance pretty close to the theoretical minimum**.
![Cirrus Runners Dashboard](/blog/images/runners-price-performance-2.png)
As you can see above Cirrus Runners Dashboard focuses on 4 core metrics:
1. **Minutes Used** — overall amount of minutes that Cirrus Runners were executing jobs.
2. **Workflow Runs** — absolute number of workflow runs that were executed on Cirrus Runners.
3. **Queue Size** — number of jobs that were queued and waiting for a free Cirrus Runner.
4. **Queue Time** — average time that jobs were waiting in the queue.
In this particular example price performance of Cirrus Runners is $0.006 per minute which is 2 times more than the theoretical minimum
and **26 times better than GitHub-managed Apple Silicon runners**. But this is a extreme example, looking at queue time and queue size
we can see that the downside of such great price performance is that jobs are waiting in the queue on average around 5 minutes.
Here is another example of Cirrus Runners Dashboard for a different customer that has a slightly higher price performance of $0.017 per minute
but at the same time doesn't experience queue time at all. **Note that $0.017 is still 10 times cheaper than GitHub-managed Apple Silicon runners**.
![Cirrus Runners Dashboard](/blog/images/runners-price-performance-3.png)
## Conclusion
Having a fixed price for Cirrus Runners is a great way to save money on your CI/CD infrastructure and just in general have predictable budged.
But it requires keeping the balance between price per minute and queue time. Cirrus Runners Dashboard helps you to keep an eye on this balance
and make sure that you are getting the most out of your Cirrus Runners.
+21
View File
@@ -0,0 +1,21 @@
# Buildkite
It is possible to run [Buildkite](https://buildkite.com/) pipeline steps in isolated ephemeral Tart Virtual Machines with the help of [Tart Buildkite Plugin](https://github.com/cirruslabs/tart-buildkite-plugin):
![](/assets/images/BuildkiteTartPlugin.png)
## Configuration
The most basic configuration looks like this:
```yaml
steps:
- command: uname -a
plugins:
- cirruslabs/tart#main:
image: ghcr.io/cirruslabs/macos-sonoma-base:latest
```
This will run `uname -r` in a macOS Tart VM cloned from `ghcr.io/cirruslabs/macos-sonoma-base:latest`.
See plugin's [Configuration section](https://github.com/cirruslabs/tart-buildkite-plugin#configuration) for the full list of available options.
+2 -2
View File
@@ -13,7 +13,7 @@ task:
name: hello name: hello
macos_instance: macos_instance:
# can be a remote or a local virtual machine # can be a remote or a local virtual machine
image: ghcr.io/cirruslabs/macos-monterey-base:latest image: ghcr.io/cirruslabs/macos-sonoma-base:latest
hello_script: hello_script:
- echo "Hello from within a Tart VM!" - echo "Hello from within a Tart VM!"
- echo "Here is my CPU info:" - echo "Here is my CPU info:"
@@ -45,7 +45,7 @@ exposes it via [`artifacts` instruction](https://cirrus-ci.org/guide/writing-tas
task: task:
name: Build name: Build
macos_instance: macos_instance:
image: ghcr.io/cirruslabs/macos-monterey-xcode:latest image: ghcr.io/cirruslabs/macos-sonoma-xcode:latest
build_script: swift build --product tart build_script: swift build --product tart
binary_artifacts: binary_artifacts:
path: .build/debug/tart path: .build/debug/tart
+109 -18
View File
@@ -1,33 +1,124 @@
# GitHub Actions # Cirrus Runners for GitHub Actions
Tart already powers several CI services mentioned above including our own [Cirrus CI](https://cirrus-ci.org/guide/macOS/) which offers unlimited concurrency with per-second billing. *Cirrus Runners* is the fastest and most cost-efficient way to get your current CI workflows to benefit from Apple Silicon hardware. No need to manage infrastructure or migrate to another CI provider.
For services that haven't leveraged Tart yet, we offer fully managed runners via a monthly subscription. Your actions will be executed in clean macOS virtual machines with 4 Apple M2 cores.
*Cirrus Runners* is the fastest way to get your current CI workflows to benefit from Apple Silicon hardware. No need to manage infrastructure or migrate to another CI provider.
## Testimonials from customers ## Testimonials from customers
Sebastian Jachec, Mobile Engineer at [Daybridge](https://www.daybridge.com/). Max Lapides, Senior Mobile Engineer at [Tonal](https://www.tonal.com/):
> It’s been plain-sailing with the Cirrus Runners — they’ve been great! They’re consistently 60+% faster on workflows that we previously used Github Actions’ macOS runners for.
Max Lapides, Senior Mobile Engineer at [Tonal](https://www.tonal.com/).
> Previously, we were using the GitHub‑hosted macOS runners and our iOS build took ~30 minutes. Now with Cirrus Runners, the iOS build only takes ~12 minutes. That’s a huge boost to our productivity, and for only $150/month per runner it is much less expensive too. > Previously, we were using the GitHub‑hosted macOS runners and our iOS build took ~30 minutes. Now with Cirrus Runners, the iOS build only takes ~12 minutes. That’s a huge boost to our productivity, and for only $150/month per runner it is much less expensive too.
John A., Software Engineer at [GitKraken](https://www.gitkraken.com/):
> GitHub Actions MacOS-x86 runners have become increasingly unreliable, so we're moving our Mac builds over to arm64 because Cirrus Labs' M1 runners are not only ~3 times faster, they've also been far more stable.
Sebastian Jachec, Mobile Engineer at [Daybridge](https://www.daybridge.com/):
> It’s been plain-sailing with the Cirrus Runners — they’ve been great! They’re consistently 60+% faster on workflows that we previously used Github Actions’ macOS runners for.
## Pricing
Each Cirrus Runner costs $150 a month and there is no limit on the amount of minutes for your actions.
We recommend to purchase several Cirrus Runners depending on your team size, so you can run actions in
parallel. Note that you can change your subscription at any time via [this page](https://billing.stripe.com/p/login/3cs7vNbzo92p7fy3cc)
or by emailing [support@cirruslabs.org](mailto:support@cirruslabs.org).
### Discounts
We offer two mutually exclusive discounts:
- 10% "Volume Discount" for subscriptions of 10 or more Cirrus Runners.
- 15% "Annual Discount" for 12 months subscription commitment of any amount of Cirrus Runners.
Please contact [support@cirruslabs.org](mailto:support@cirruslabs.org) after activating the subscription in order to get the discount applied.
### Priority Support
Subscriptions of 20 or more Cirrus Runners include access to [Priority Support](../licensing.md#priority-support).
Please contact [sales@cirruslabs.org](mailto:sales@cirruslabs.org) in order to get all the details.
### CPU and Memory resources of Cirrus Runners
By default, a single Cirrus Runner is allocated with 4 M2 cores and 12 GB of unified memory which is enough for most of the workloads.
For workloads that require more resources it is possible to use XL Cirrus Runners which have twice the resources: a full M2 chip with 8 cores
and 24 GB of unified memory. Note that a single XL Cirrus Runner also uses twice the concurrency.
In order to use an XL Cirrus Runner for a job please append `-xl` suffix to your `runs-on` property. More on that down below.
## Installation
Once you configure [Cirrus Runners App](https://github.com/apps/cirrus-runners) for your organization, you'll be redirected
to a checkout page powered by Stripe. During the checkout process you'll be able to configure a subscription for
a desired amount of parallel Cirrus Runners and try it for free for 10 days.
Once configured, please follow instruction below. If you have any questions please contact [support@cirruslabs.org](mailto:support@cirruslabs.org).
Subscriptions with more than 10 runners also include Priority Support
## Configuring Cirrus Runners ## Configuring Cirrus Runners
Configuring Cirrus Runners for GitHub Actions is as simple as installing [Cirrus Runners App](https://github.com/apps/cirrus-runners). In order for Cirrus Runners to be used by your GitHub Actions workflow jobs, specify a desired image in the `runs-on` property.
After successful installation and subscription configuration, use any of [Ventura images managed by us](https://github.com/cirruslabs/macos-image-templates) in `runs-on`:
```yaml === "Default Cirrus Runner"
name: Test Suite
jobs: ```yaml
test: name: Tests
runs-on: ghcr.io/cirruslabs/macos-ventura-xcode:latest jobs:
``` test:
runs-on: ghcr.io/cirruslabs/macos-sonoma-xcode:latest
```
=== "XL Cirrus Runner"
```yaml
name: Integration Tests
jobs:
test:
runs-on: ghcr.io/cirruslabs/macos-sonoma-xcode:latest-xl
```
List of all available images can be found in [this repository](https://github.com/cirruslabs/macos-image-templates).
Note that Tart VM images don't have the same set of pre-installed packages as the official Intel GitHub runners.
If something is missing please [create an issue within this repository](https://github.com/cirruslabs/macos-image-templates/issues/new).
When workflows are executing you'll see Cirrus on-demand runners on your organization's settings page at `https://github.com/organizations/<ORGANIZATION>/settings/actions/runners`. When workflows are executing you'll see Cirrus on-demand runners on your organization's settings page at `https://github.com/organizations/<ORGANIZATION>/settings/actions/runners`.
Note that Cirrus Runners will get added to the default runner group. By default, only private repositories can access runners in a default runner group, but you can override this in your organization's settings. Note that Cirrus Runners will get added to the default runner group.
!!! tip "Using Cirrus Runners with public repositories"
By default, only private repositories can access runners in a default runner group, but you can override this in your organization's settings:
```https://github.com/organizations/<YOUR ORGANIZATION NAME>/settings/actions/runner-groups/1```
![](/assets/images/TartGHARunners.png) ![](/assets/images/TartGHARunners.png)
### Dashboard
You can also see the status of your runners on the [Cirrus Runners Dashboard](https://cirrus-runners.app/). This dashboard
also provides insights into price performance of your Cirrus Runners. Please check out [this blog post](/blog/2023/11/03/new-dashboard-with-insights-into-performance-of-cirrus-runners/)
to learn more about what this dashboard can do for you.
![](/assets/images/RunnersDashboard.png)
## Data handling flow
By design Cirrus Runners service never sees any of your secrets or source code and acts as compute platform with the lastest
Apple Silicon hardware that can quickly allocate CPU/Memory resources for your jobs.
Here is a high-level overview of how Cirrus Runners service manages runners for your organization:
- Cirrus Runner GitHub App is subscribed to [`workflow_job`](https://docs.github.com/en/webhooks/webhook-events-and-payloads#workflow_job).
- Upon receiving a new event targeting Cirrus Runners via `runs-on` property the following steps take place:
- Non-personal information about your job is saved to perform health checking of Cirrus Runners execution.
- Cirrus Runners GitHub App has only one permission that allows generating temporary registration tokens for
self-hosted GitHub Actions Runners. Note that Cirrus Runners GitHub App itself doesn't have access to contents of
repositories in your organization.
- Cirrus Runners Service creates a new single use Tart VM, generates a temporary registration tokens for self-hosted runners
and passes it without storing inside the VM for the GitHub Actions Runner service to [start a ephemeral runner](https://github.blog/changelog/2021-09-20-github-actions-ephemeral-self-hosted-runners-new-webhooks-for-auto-scaling/).
- Cirrus Runners service continuously monitors health of the Tart VM executing your job to make sure it runs to completion.
- After the job finishes the ephemeral Tart VM is getting destroyed with all the information of the job run.
If you have any questions or concerns please feel free to reach out to [support@cirruslabs.org](mailto:support@cirruslabs.org).
+2 -2
View File
@@ -19,7 +19,7 @@ concurrent = 2
[[runners]] [[runners]]
# ... # ...
executor = "custom" executor = "custom"
builds_dir = "/Users/admin/builds" # directory inside the builds_dir = "/Users/admin/builds" # directory inside the VM
cache_dir = "/Users/admin/cache" cache_dir = "/Users/admin/cache"
[runners.feature_flags] [runners.feature_flags]
FF_RESOLVE_FULL_TLS_CHAIN = false FF_RESOLVE_FULL_TLS_CHAIN = false
@@ -37,7 +37,7 @@ Now you can use Tart Images in your `.gitlab-ci.yml`:
```yaml ```yaml
# You can use any remote Tart Image. # You can use any remote Tart Image.
# Tart Executor will pull it from the registry and use it for creating ephemeral VMs. # Tart Executor will pull it from the registry and use it for creating ephemeral VMs.
image: ghcr.io/cirruslabs/macos-ventura-base:latest image: ghcr.io/cirruslabs/macos-sonoma-base:latest
test: test:
tags: tags:
+7 -5
View File
@@ -11,8 +11,8 @@ Tart can create VMs from `*.ipsw` files. You can download a specific `*.ipsw` fi
use `latest` instead of a path to `*.ipsw` to download the latest available version: use `latest` instead of a path to `*.ipsw` to download the latest available version:
```bash ```bash
tart create --from-ipsw=latest monterey-vanilla tart create --from-ipsw=latest sonoma-vanilla
tart run monterey-vanilla tart run sonoma-vanilla
``` ```
After the initial booting of the VM you'll need to manually go through the macOS installation process. As a convention we recommend creating an `admin` user with an `admin` password. After the regular installation please do some additional modifications in the VM: After the initial booting of the VM you'll need to manually go through the macOS installation process. As a convention we recommend creating an `admin` user with an `admin` password. After the regular installation please do some additional modifications in the VM:
@@ -54,7 +54,7 @@ Please refer to `tart set --help` for additional details.
## Building with Packer ## Building with Packer
Please refer to [Tart Packer Plugin repository](https://github.com/cirruslabs/packer-plugin-tart) for setup instructions. Please refer to [Tart Packer Plugin repository](https://github.com/cirruslabs/packer-plugin-tart) for setup instructions.
Here is an example of a template to build `monterey-base` local image based of a remote image: Here is an example of a template to build a local image based of a remote image:
```hcl ```hcl
packer { packer {
@@ -67,8 +67,8 @@ packer {
} }
source "tart-cli" "tart" { source "tart-cli" "tart" {
vm_base_name = "ghcr.io/cirruslabs/macos-ventura-base:latest" vm_base_name = "ghcr.io/cirruslabs/macos-sonoma-base:latest"
vm_name = "my-custom-ventura" vm_name = "my-custom-sonoma"
cpu_count = 4 cpu_count = 4
memory_gb = 8 memory_gb = 8
disk_size_gb = 70 disk_size_gb = 70
@@ -92,7 +92,9 @@ Here is a [repository with Packer templates](https://github.com/cirruslabs/macos
## Working with a Remote OCI Container Registry ## Working with a Remote OCI Container Registry
<!-- markdownlint-disable MD034 -->
For example, let's say you want to push/pull images to a registry hosted at https://acme.io/. For example, let's say you want to push/pull images to a registry hosted at https://acme.io/.
<!-- markdownlint-enable MD034 -->
### Registry Authorization ### Registry Authorization
+8 -1
View File
@@ -13,7 +13,6 @@ will be required to obtain a paid license.
Tart VMs will automatically try to balance compute between all available cores of the host CPU. As a result, Tart VMs will automatically try to balance compute between all available cores of the host CPU. As a result,
all performance and energy-efficient cores of the host CPU are always counted towards the license usage. all performance and energy-efficient cores of the host CPU are always counted towards the license usage.
# License Tiers # License Tiers
## Free Tier ## Free Tier
@@ -57,6 +56,14 @@ If your organization is interested in purchasing one of the license tiers, pleas
You can see a template of a license subscription agreement [here](assets/TartLicenseSubscription.pdf). You can see a template of a license subscription agreement [here](assets/TartLicenseSubscription.pdf).
!!! info "Running on AWS?"
There are [official AMIs for EC2 Mac Instances](https://aws.amazon.com/marketplace/pp/prodview-qczco34wlkdws)
with preconfigured Tart installation that is optimized to work within AWS infrastructure.
Additionally, there is a [ECR Pulic Gallery mirror](https://gallery.ecr.aws/cirruslabs/macos) of all the
[Tart VM images managed by us](https://github.com/cirruslabs/macos-image-templates).
# General Support # General Support
The best way to ask general questions about particular use cases is to email our support team at [support@cirruslabs.org](mailto:support@cirruslabs.org). The best way to ask general questions about particular use cases is to email our support team at [support@cirruslabs.org](mailto:support@cirruslabs.org).
+41 -10
View File
@@ -3,12 +3,12 @@ hide:
- navigation - navigation
--- ---
Try running a Tart VM on your Apple Silicon device running macOS 12.0 (Monterey) or later (will download a 25 GB image): Try running a Tart VM on your Apple Silicon device running macOS 13.0 (Ventura) or later (will download a 25 GB image):
```bash ```bash
brew install cirruslabs/cli/tart brew install cirruslabs/cli/tart
tart clone ghcr.io/cirruslabs/macos-ventura-base:latest ventura-base tart clone ghcr.io/cirruslabs/macos-sonoma-base:latest sonoma-base
tart run ventura-base tart run sonoma-base
``` ```
??? info "Manual installation from a release archive" ??? info "Manual installation from a release archive"
@@ -17,8 +17,8 @@ tart run ventura-base
```bash ```bash
curl -LO https://github.com/cirruslabs/tart/releases/latest/download/tart.tar.gz curl -LO https://github.com/cirruslabs/tart/releases/latest/download/tart.tar.gz
tar -xzvf tart.tar.gz tar -xzvf tart.tar.gz
./tart.app/Contents/MacOS/tart clone ghcr.io/cirruslabs/macos-ventura-base:latest ventura-base ./tart.app/Contents/MacOS/tart clone ghcr.io/cirruslabs/macos-sonoma-base:latest sonoma-base
./tart.app/Contents/MacOS/tart run ventura-base ./tart.app/Contents/MacOS/tart run sonoma-base
``` ```
Please note that `./tart.app/Contents/MacOS/tart` binary is required to be used in order to trick macOS Please note that `./tart.app/Contents/MacOS/tart` binary is required to be used in order to trick macOS
@@ -28,12 +28,44 @@ tart run ventura-base
<img src="https://github.com/cirruslabs/tart/raw/main/Resources/TartScreenshot.png"/> <img src="https://github.com/cirruslabs/tart/raw/main/Resources/TartScreenshot.png"/>
</p> </p>
## VM images
The following macOS images are currently available:
* macOS 14 (Sonoma)
* `ghcr.io/cirruslabs/macos-sonoma-vanilla:latest`
* `ghcr.io/cirruslabs/macos-sonoma-base:latest`
* `ghcr.io/cirruslabs/macos-sonoma-xcode:latest`
* macOS 13 (Ventura)
* `ghcr.io/cirruslabs/macos-ventura-vanilla:latest`
* `ghcr.io/cirruslabs/macos-ventura-base:latest`
* `ghcr.io/cirruslabs/macos-ventura-xcode:latest`
* macOS 12 (Monterey)
* `ghcr.io/cirruslabs/macos-monterey-vanilla:latest`
* `ghcr.io/cirruslabs/macos-monterey-base:latest`
* `ghcr.io/cirruslabs/macos-monterey-xcode:latest`
There's also a [full list of images](https://github.com/orgs/cirruslabs/packages?tab=packages&q=macos-) in which you can discovery specific tags (e.g. `ghcr.io/cirruslabs/macos-monterey-xcode:15`) and [macOS-specific Packer templates](https://github.com/cirruslabs/macos-image-templates) that were used to generate these images.
For, Linux the options are as follows:
* Ubuntu
* `ghcr.io/cirruslabs/ubuntu:latest`
* Debian
* `ghcr.io/cirruslabs/debian:latest`
* Fedora
* `ghcr.io/cirruslabs/fedora:latest`
These Linux images can be ran natively on [Vetu](https://github.com/cirruslabs/vetu), our virtualization solution for Linux, assuming that Vetu itself is running on an `arm64` machine.
Similarly to macOS, there's also a [full list of images](https://github.com/orgs/cirruslabs/packages?repo_name=linux-image-templates) in which you can discovery specific tags (e.g. `ghcr.io/cirruslabs/ubuntu:22.04`) and [Linux-specific Packer templates](https://github.com/cirruslabs/linux-image-templates) that were used to generate these images.
## SSH access ## SSH access
If the guest VM is running and configured to accept incoming SSH connections you can conveniently connect to it like so: If the guest VM is running and configured to accept incoming SSH connections you can conveniently connect to it like so:
```bash ```bash
ssh admin@$(tart ip ventura-base) ssh admin@$(tart ip sonoma-base)
``` ```
!!! tip "Running scripts inside Tart virtual machines" !!! tip "Running scripts inside Tart virtual machines"
@@ -41,9 +73,9 @@ ssh admin@$(tart ip ventura-base)
from within Tart virtual machines. Alternatively, you can use plain ssh connection and `tart ip` command: from within Tart virtual machines. Alternatively, you can use plain ssh connection and `tart ip` command:
```bash ```bash
brew install sshpass brew install cirruslabs/cli/sshpass
sshpass -p admin ssh -o "StrictHostKeyChecking no" admin@$(tart ip ventura-base) "uname -a" sshpass -p admin ssh -o "StrictHostKeyChecking no" admin@$(tart ip sonoma-base) "uname -a"
sshpass -p admin ssh -o "StrictHostKeyChecking no" admin@$(tart ip ventura-base) < script.sh sshpass -p admin ssh -o "StrictHostKeyChecking no" admin@$(tart ip sonoma-base) < script.sh
``` ```
## Mounting directories ## Mounting directories
@@ -100,4 +132,3 @@ mount -t virtiofs com.apple.virtio-fs.automount /mnt/shared
``` ```
The directory we've mounted above will be accessible from the `/mnt/shared/project` path inside a guest VM. The directory we've mounted above will be accessible from the `/mnt/shared/project` path inside a guest VM.
+5 -8
View File
@@ -1,11 +1,5 @@
{% extends "base.html" %} {% extends "base.html" %}
{% block announce %}
<a href="/blog/2023/04/25/announcing-orchard-orchestration-for-managing-macos-virtual-machines-at-scale/">
🚀🚀🚀&nbsp&nbspAnnouncing <strong>Orchard</strong> orchestration for managing macOS virtual machines at scale&nbsp;&nbsp;🚀🚀🚀
</a>
{% endblock %}
<!-- Render landing page under tabs --> <!-- Render landing page under tabs -->
{% block tabs %} {{ super() }} {% block tabs %} {{ super() }}
@@ -242,12 +236,15 @@
} }
let counterElement = document.getElementById('installation-counter'); let counterElement = document.getElementById('installation-counter');
if (counterElement) { if (counterElement) {
counterElement.textContent = Math.round(allDownloads / 1000) + ",000" // Live installation count is available starting version 1.0.0
// Prior Tart was installed a little over 14,000 times, let's count them too
let installationPriorV1 = 14
counterElement.textContent = (installationPriorV1 + Math.round(allDownloads / 1000)) + ",000"
} }
}) })
</script> </script>
<h2> <h2>
With more than <strong id="installation-counter">10,000</strong> installations to date, Tart has been adopted for various scenarios. With more than <strong id="installation-counter">25,000</strong> installations to date, Tart has been adopted for various scenarios.
Its applications range from powering CI/CD pipelines and reproducible local development environments, Its applications range from powering CI/CD pipelines and reproducible local development environments,
to helping in the testing of device management systems without actual physical devices. to helping in the testing of device management systems without actual physical devices.
</h2> </h2>
+1 -1
View File
@@ -7,7 +7,7 @@ def test_run(tart):
vm_name = f"integration-test-run-{uuid.uuid4()}" vm_name = f"integration-test-run-{uuid.uuid4()}"
# Instantiate a VM with admin:admin SSH access # Instantiate a VM with admin:admin SSH access
tart.run(["clone", "ghcr.io/cirruslabs/macos-ventura-base:latest", vm_name]) tart.run(["clone", "ghcr.io/cirruslabs/macos-sonoma-base:latest", vm_name])
# Run the VM asynchronously # Run the VM asynchronously
tart_run_process = tart.run_async(["run", vm_name]) tart_run_process = tart.run_async(["run", vm_name])
+3
View File
@@ -82,6 +82,8 @@ markdown_extensions:
- pymdownx.tasklist: - pymdownx.tasklist:
custom_checkbox: true custom_checkbox: true
- pymdownx.tilde - pymdownx.tilde
- attr_list
- md_in_html
nav: nav:
- "Home": index.md - "Home": index.md
@@ -89,6 +91,7 @@ nav:
- "Integrations": - "Integrations":
- "GitHub Actions": integrations/github-actions.md - "GitHub Actions": integrations/github-actions.md
- "GitLab Runner": integrations/gitlab-runner.md - "GitLab Runner": integrations/gitlab-runner.md
- "Buildkite": integrations/buildkite.md
- "Self-hosted CI": integrations/cirrus-cli.md - "Self-hosted CI": integrations/cirrus-cli.md
- "Managing VMs": integrations/vm-management.md - "Managing VMs": integrations/vm-management.md
- "Support & Licensing": licensing.md - "Support & Licensing": licensing.md
+6 -2
View File
@@ -1,11 +1,15 @@
#!/bin/sh #!/bin/sh
# helper script to build and run a signed tart binary # helper script to build and run a signed tart binary
# usage: ./scripts/run-signed.sh run ventura-base # usage: ./scripts/run-signed.sh run sonoma-base
set -e set -e
swift build --product tart swift build --product tart
codesign --sign - --entitlements Resources/tart-dev.entitlements --force .build/debug/tart codesign --sign - --entitlements Resources/tart-dev.entitlements --force .build/debug/tart
.build/debug/tart "$@" mkdir -p .build/tart.app/Contents/MacOS
cp -c .build/debug/tart .build/tart.app/Contents/MacOS/tart
cp -c Resources/embedded.provisionprofile .build/tart.app/Contents/embedded.provisionprofile
.build/tart.app/Contents/MacOS/tart "$@"