diff options
Diffstat
88 files changed, 1183 insertions, 8212 deletions
diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 --- a/.dockerignore +++ /dev/null @@ -1,9 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -.git -.github -.recluse-state -dist -target -*.lcov diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 --- a/.editorconfig +++ /dev/null @@ -1,26 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -root = true - -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true -indent_style = space -indent_size = 4 - -[*.md] -# double whitespace at end of line -# denotes a line break in Markdown -trim_trailing_whitespace = false - -[*.rs] -max_line_length = 100 - -[*.yml] -indent_size = 2 - -[{Makefile,*.mk}] -indent_style = tab diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml deleted file mode 100644 --- a/.github/workflows/build.yml +++ /dev/null @@ -1,83 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -name: Build - -on: - push: - branches: [main] - tags: ["v*"] - pull_request: - branches: [main] - -permissions: - contents: read - -concurrency: - group: hule-build-${{ github.ref }} - cancel-in-progress: true - -env: - CARGO_TERM_COLOR: always - RELEASE_TAG: nightly - -jobs: - lint: - name: Static checks - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - - - uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3 - with: - version: 2026.7.5 - experimental: true - install: false - - name: Install dependencies - run: mise bootstrap --locked --yes --update - - uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2 - - - name: formatting - run: cargo fmt --all --check - - - name: shellcheck - run: shellcheck images/*/genimg - - - name: clippy - run: cargo clippy --workspace --all-targets --all-features --release --locked -- -D warnings - - build: - name: Build (${{ matrix.arch }}) - runs-on: ${{ matrix.runner }} - needs: [lint] - strategy: - fail-fast: false - matrix: - include: - - runner: ubuntu-24.04 - arch: amd64 - - runner: ubuntu-24.04-arm - arch: arm64 - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - - - uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3 - with: - version: 2026.7.5 - experimental: true - install: false - - name: Install dependencies - run: mise bootstrap --locked --yes - - uses: Swatinem/rust-cache@779680da715d629ac1d338a641029a2f4372abb5 # v2.8.2 - - - name: Build - run: cargo build --workspace --all-features --release --locked - - - name: Run tests - run: cargo test --workspace --all-features --release --locked - - - name: Upload binary - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0 - with: - name: hule-${{ matrix.arch }} - path: target/release/hule diff --git a/.github/workflows/legal.yml b/.github/workflows/legal.yml deleted file mode 100644 --- a/.github/workflows/legal.yml +++ /dev/null @@ -1,35 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -name: Legal - -on: - push: - branches: [main] - tags: ["v*"] - pull_request: - branches: [main] - -permissions: - contents: read - -jobs: - legal: - name: Legal checks - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - with: - fetch-depth: 0 - - - uses: jdx/mise-action@5228313ee0372e111a38da051671ca30fc5a96db # v3 - with: - version: 2026.7.5 - experimental: true - install: false - - - name: Check contribution sign-off - run: mise run signoff - - - name: Check licensing policy - run: mise run licenses diff --git a/.gitignore b/.gitignore index ea96d7d..d70a18d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,8 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# Copyright (c) 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 -/dist /target -mise.local.toml -mise.*.local.toml +/dist __pycache__ *.qcow2 - -# Built machine images and manifests -*.hmi -*.hmm -/images/*/*/*/config.json diff --git a/.mailmap b/.mailmap deleted file mode 100644 --- a/.mailmap +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 -# -# Add new entries in alphabetical order - -Nikolay Govorov <me@govorov.online> -Nikolay Govorov <mr@dimidiumlabs.io> diff --git a/CLA.md b/CLA.md deleted file mode 100644 --- a/CLA.md +++ /dev/null @@ -1,170 +0,0 @@ -# Hule Individual Contributor License Agreement - -Version 1.0 - -> This agreement is based on the Harmony Individual Contributor License -> Agreement Version 1.0 licensed under a -> [Creative Commons Attribution 3.0 Unported License](https://creativecommons.org/licenses/by/3.0/). - -Thank you for your interest in contributing to Hule (the "Project"). In this -Agreement, "We" and "Us" mean Nikolay Govorov. - -This contributor agreement ("Agreement") documents the rights granted by -contributors to Us. To make this document effective, You must personally add -the following trailers to every commit You Submit: - -```text -CLA-Version: 1.0 -Signed-off-by: Your Name <your.email@example.com> -``` - -The name and email address in `Signed-off-by` must identify You and match the -commit author. By Submitting a commit containing these trailers, You -electronically sign and accept this Agreement. No other person or automated -system may add the `Signed-off-by` trailer on Your behalf. This is a legally -binding document, so please read it carefully before agreeing to it. - -## 1. Definitions - -"You" means the individual who Submits a Contribution to Us. - -"Contribution" means any work of authorship that is Submitted by You to Us in -which You own or assert ownership of the Copyright. If You do not own the -Copyright in the entire work of authorship, please follow the instructions in -Section 3(d). - -"Copyright" means all rights protecting works of authorship owned or controlled -by You, including copyright, moral and neighboring rights, as appropriate, for -the full term of their existence including any extensions by You. - -"Material" means the work of authorship which is made available by Us to third -parties as part of the Project. After You Submit the Contribution, it may be -included in the Material. - -"Submit" means any form of electronic, verbal, or written communication sent to -Us or our representatives, including but not limited to electronic mailing -lists, source code control systems, and issue tracking systems that are managed -by, or on behalf of, Us for the purpose of discussing and improving the -Material, but excluding communication that is conspicuously marked or otherwise -designated in writing by You as "Not a Contribution." - -"Submission Date" means the date on which You Submit a Contribution to Us. - -"Effective Date" means the date You execute this Agreement or the date You first -Submit a Contribution to Us, whichever is earlier. - -"Media" means any portion of a Contribution which is not software. - -## 2. Grant of Rights - -### 2.1 Copyright License - -(a) You retain ownership of the Copyright in Your Contribution and have the same -rights to use or license the Contribution which You would have had without -entering into the Agreement. - -(b) To the maximum extent permitted by the relevant law, You grant to Us a -perpetual, worldwide, non-exclusive, transferable, royalty-free, irrevocable -license under the Copyright covering the Contribution, with the right to -sublicense such rights through multiple tiers of sublicensees, to reproduce, -modify, display, perform and distribute the Contribution as part of the -Material; provided that this license is conditioned upon compliance with Section -2.3. - -### 2.2 Patent License - -For patent claims including, without limitation, method, process, and apparatus -claims which You own, control or have the right to grant, -now or in the future, You grant to Us a perpetual, worldwide, non-exclusive, -transferable, royalty-free, irrevocable patent license, with the right to -sublicense these rights to multiple tiers of sublicensees, to make, have made, -use, sell, offer for sale, import and otherwise transfer the Contribution and -the Contribution in combination with the Material (and portions of such -combination). This license is granted only to the extent that the exercise of -the licensed rights infringes such patent claims; and provided that this license -is conditioned upon compliance with Section 2.3. - -### 2.3 Outbound License - -Based on the grant of rights in Sections 2.1 and 2.2, if We include Your -Contribution in a Material, We may license the Contribution under any license, -including copyleft, permissive, commercial, or proprietary licenses. As a -condition on the exercise of this right, We agree to also license the -Contribution under the terms of the license or licenses which We are using for -the Material on the Submission Date. - -### 2.4 Moral Rights - -If moral rights apply to the Contribution, to the maximum extent permitted by -law, You waive and agree not to assert such moral rights against Us or our -successors in interest, or any of our licensees, either direct or indirect. - -### 2.5 Our Rights - -You acknowledge that We are not obligated to use Your Contribution as part of -the Material and may decide to include any Contribution We consider appropriate. - -### 2.6 Reservation of Rights - -Any rights not expressly licensed under this section are expressly -reserved by You. - -## 3. Agreement - -You confirm that: - -(a) You have the legal authority to enter into this Agreement. - -(b) You own the Copyright and patent claims covering the -Contribution which are required to grant the rights under Section 2. - -(c) The grant of rights under Section 2 does not violate any grant -of rights which You have made to third parties, including Your employer. If You -are an employee, You have had Your employer approve this Agreement or sign the -Entity version of this document. If You are less than eighteen years old, please -have Your parents or guardian sign the Agreement. - -(d) If You do not own the Copyright in the entire work of authorship Submitted, -You have clearly identified the third-party work, its source, and its license in -the Submission. - -## 4. Disclaimer - -EXCEPT FOR THE EXPRESS WARRANTIES IN SECTION 3, THE CONTRIBUTION IS PROVIDED "AS -IS". MORE PARTICULARLY, ALL EXPRESS OR IMPLIED WARRANTIES INCLUDING, WITHOUT -LIMITATION, ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR -PURPOSE AND NON-INFRINGEMENT ARE EXPRESSLY DISCLAIMED BY YOU TO US. -TO THE EXTENT THAT ANY SUCH WARRANTIES CANNOT BE DISCLAIMED, SUCH WARRANTY -IS LIMITED IN DURATION TO THE MINIMUM PERIOD PERMITTED BY LAW. - -## 5. Consequential Damage Waiver - -TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT WILL YOU BE -LIABLE FOR ANY LOSS OF PROFITS, LOSS OF ANTICIPATED SAVINGS, LOSS OF DATA, -INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL AND EXEMPLARY DAMAGES ARISING OUT -OF THIS AGREEMENT REGARDLESS OF THE LEGAL OR EQUITABLE THEORY (CONTRACT, TORT OR -OTHERWISE) UPON WHICH THE CLAIM IS BASED. - -## 6. Miscellaneous - -6.1 This Agreement sets out the entire agreement between You and Us for Your -Contributions to Us and overrides all other agreements or understandings. - -6.2 If You or We assign the rights or obligations received through this -Agreement to a third party, as a condition of the assignment, that third party -must agree in writing to abide by all the rights and obligations in the -Agreement. - -6.3 The failure of either party to require performance by the other party of any -provision of this Agreement in one situation shall not affect the right of a -party to require such performance at any time in the future. A waiver of -performance under a provision in one situation shall not be considered a waiver -of the performance of the provision in the future or a waiver of the provision -in its entirety. - -6.4 If any provision of this Agreement is found void and unenforceable, such -provision will be replaced to the extent possible with a provision that comes -closest to the meaning of the original provision and which is enforceable. The -terms and conditions set forth in this Agreement shall apply notwithstanding any -failure of essential purpose of this Agreement or any limited remedy to the -maximum extent possible under law. diff --git a/CODEOWNERS b/CODEOWNERS deleted file mode 100644 --- a/CODEOWNERS +++ /dev/null @@ -1,4 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -* @mrdimidium diff --git a/Cargo.lock b/Cargo.lock index d2d38d6..6e0705b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3,2410 +3,17 @@ version = 4 [[package]] -name = "aho-corasick" -version = "1.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" -dependencies = [ - "memchr", -] - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - -[[package]] -name = "anstream" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] - -[[package]] -name = "anstyle" -version = "1.0.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" - -[[package]] -name = "anstyle-parse" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" -dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" -dependencies = [ - "anstyle", - "once_cell_polyfill", - "windows-sys 0.61.2", -] - -[[package]] -name = "async-trait" -version = "0.1.89" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "atomic-waker" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" - -[[package]] -name = "autocfg" -version = "1.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" - -[[package]] -name = "aws-lc-rs" -version = "1.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4342d8937fc7e5dd9b1c60292261c0670c882a2cd1719cfc11b1af41731e32ad" -dependencies = [ - "aws-lc-sys", - "untrusted 0.7.1", - "zeroize", -] - -[[package]] -name = "aws-lc-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d9ceb1da931507a12f4fccea479dccd00da1943e1b4ae72d8e502d707361444" -dependencies = [ - "cc", - "cmake", - "dunce", - "fs_extra", - "pkg-config", -] - -[[package]] -name = "base64" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" - -[[package]] -name = "bitflags" -version = "2.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" - -[[package]] -name = "block-buffer" -version = "0.10.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" -dependencies = [ - "generic-array", -] - -[[package]] -name = "block-buffer" -version = "0.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "bumpalo" -version = "3.20.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" - -[[package]] -name = "bytes" -version = "1.12.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" - -[[package]] -name = "cc" -version = "1.2.67" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" -dependencies = [ - "find-msvc-tools", - "jobserver", - "libc", - "shlex", -] - -[[package]] -name = "cfg-if" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" - -[[package]] -name = "cfg_aliases" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" - -[[package]] -name = "chacha20" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "rand_core 0.10.1", -] - -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - -[[package]] -name = "clap" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" -dependencies = [ - "clap_builder", - "clap_derive", -] - -[[package]] -name = "clap_builder" -version = "4.6.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" -dependencies = [ - "anstream", - "anstyle", - "clap_lex", - "strsim", -] - -[[package]] -name = "clap_derive" -version = "4.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "clap_lex" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" - -[[package]] -name = "cmake" -version = "0.1.58" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" -dependencies = [ - "cc", -] - -[[package]] -name = "colorchoice" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" - -[[package]] -name = "combine" -version = "4.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" -dependencies = [ - "bytes", - "memchr", -] - -[[package]] -name = "const-oid" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" - -[[package]] -name = "const_format" -version = "0.2.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4481a617ad9a412be3b97c5d403fef8ed023103368908b9c50af598ff467cc1e" -dependencies = [ - "const_format_proc_macros", - "konst", -] - -[[package]] -name = "const_format_proc_macros" -version = "0.2.34" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d57c2eccfb16dbac1f4e61e206105db5820c9d26c3c472bc17c774259ef7744" -dependencies = [ - "proc-macro2", - "quote", - "unicode-xid", -] - -[[package]] -name = "core-foundation" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "core-foundation-sys" -version = "0.8.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" - -[[package]] -name = "cpufeatures" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" -dependencies = [ - "libc", -] - -[[package]] -name = "cpufeatures" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" -dependencies = [ - "libc", -] - -[[package]] -name = "crypto-common" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" -dependencies = [ - "generic-array", - "typenum", -] - -[[package]] -name = "crypto-common" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" -dependencies = [ - "hybrid-array", -] - -[[package]] -name = "darling" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" -dependencies = [ - "darling_core", - "darling_macro", -] - -[[package]] -name = "darling_core" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim", - "syn", -] - -[[package]] -name = "darling_macro" -version = "0.20.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" -dependencies = [ - "darling_core", - "quote", - "syn", -] - -[[package]] -name = "derive_builder" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" -dependencies = [ - "derive_builder_macro", -] - -[[package]] -name = "derive_builder_core" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" -dependencies = [ - "darling", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "derive_builder_macro" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" -dependencies = [ - "derive_builder_core", - "syn", -] - -[[package]] -name = "digest" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" -dependencies = [ - "block-buffer 0.10.4", - "crypto-common 0.1.7", -] - -[[package]] -name = "digest" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" -dependencies = [ - "block-buffer 0.12.1", - "const-oid", - "crypto-common 0.2.2", -] - -[[package]] -name = "displaydoc" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "dunce" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" - -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "find-msvc-tools" -version = "0.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" - -[[package]] -name = "fnv" -version = "1.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" - -[[package]] -name = "form_urlencoded" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" -dependencies = [ - "percent-encoding", -] - -[[package]] -name = "fs_extra" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" - -[[package]] -name = "futures-channel" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" -dependencies = [ - "futures-core", -] - -[[package]] -name = "futures-core" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" - -[[package]] -name = "futures-io" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" - -[[package]] -name = "futures-macro" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "futures-sink" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" - -[[package]] -name = "futures-task" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" - -[[package]] -name = "futures-util" -version = "0.3.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" -dependencies = [ - "futures-core", - "futures-io", - "futures-macro", - "futures-sink", - "futures-task", - "memchr", - "pin-project-lite", - "slab", -] - -[[package]] -name = "generic-array" -version = "0.14.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" -dependencies = [ - "typenum", - "version_check", -] - -[[package]] -name = "getrandom" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "wasi", - "wasm-bindgen", -] - -[[package]] -name = "getrandom" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" -dependencies = [ - "cfg-if", - "js-sys", - "libc", - "r-efi", - "rand_core 0.10.1", - "wasm-bindgen", -] - -[[package]] -name = "getset" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6cf442baaabe4213ce7d1239afc26c039180b6456da2cededa316ae2c8a77a77" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "heck" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" - -[[package]] -name = "hex" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" - -[[package]] -name = "http" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" -dependencies = [ - "bytes", - "itoa", -] - -[[package]] -name = "http-auth" -version = "0.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150fa4a9462ef926824cf4519c84ed652ca8f4fbae34cb8af045b5cbcaf98822" -dependencies = [ - "memchr", -] - -[[package]] -name = "http-body" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" -dependencies = [ - "bytes", - "http", -] - -[[package]] -name = "http-body-util" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" -dependencies = [ - "bytes", - "futures-core", - "http", - "http-body", - "pin-project-lite", -] - -[[package]] -name = "httparse" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" - -[[package]] name = "hule" version = "0.1.0" dependencies = [ - "clap", - "hule-hmi", "hule-oci", "hule-vmm", - "tokio", - "uuid", -] - -[[package]] -name = "hule-hmi" -version = "0.1.0" -dependencies = [ - "serde", - "serde_json", ] [[package]] name = "hule-oci" version = "0.1.0" -dependencies = [ - "hule-hmi", - "oci-client", - "serde_json", - "sha2 0.10.9", - "tokio", - "zstd", -] [[package]] name = "hule-vmm" version = "0.1.0" -dependencies = [ - "async-trait", - "base64", - "hule-hmi", - "serde", - "serde_json", - "tokio", - "uuid", -] - -[[package]] -name = "hybrid-array" -version = "0.4.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" -dependencies = [ - "typenum", -] - -[[package]] -name = "hyper" -version = "1.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" -dependencies = [ - "atomic-waker", - "bytes", - "futures-channel", - "futures-core", - "http", - "http-body", - "httparse", - "itoa", - "pin-project-lite", - "smallvec", - "tokio", - "want", -] - -[[package]] -name = "hyper-rustls" -version = "0.27.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" -dependencies = [ - "http", - "hyper", - "hyper-util", - "rustls", - "tokio", - "tokio-rustls", - "tower-service", -] - -[[package]] -name = "hyper-util" -version = "0.1.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" -dependencies = [ - "base64", - "bytes", - "futures-channel", - "futures-util", - "http", - "http-body", - "hyper", - "ipnet", - "libc", - "percent-encoding", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", -] - -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - -[[package]] -name = "icu_collections" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" -dependencies = [ - "displaydoc", - "potential_utf", - "utf8_iter", - "yoke", - "zerofrom", - "zerovec", -] - -[[package]] -name = "icu_locale_core" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" -dependencies = [ - "displaydoc", - "litemap", - "tinystr", - "writeable", - "zerovec", -] - -[[package]] -name = "icu_normalizer" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" -dependencies = [ - "icu_collections", - "icu_normalizer_data", - "icu_properties", - "icu_provider", - "smallvec", - "zerovec", -] - -[[package]] -name = "icu_normalizer_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" - -[[package]] -name = "icu_properties" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" -dependencies = [ - "icu_collections", - "icu_locale_core", - "icu_properties_data", - "icu_provider", - "zerotrie", - "zerovec", -] - -[[package]] -name = "icu_properties_data" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" - -[[package]] -name = "icu_provider" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" -dependencies = [ - "displaydoc", - "icu_locale_core", - "writeable", - "yoke", - "zerofrom", - "zerotrie", - "zerovec", -] - -[[package]] -name = "ident_case" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" - -[[package]] -name = "idna" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" -dependencies = [ - "idna_adapter", - "smallvec", - "utf8_iter", -] - -[[package]] -name = "idna_adapter" -version = "1.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" -dependencies = [ - "icu_normalizer", - "icu_properties", -] - -[[package]] -name = "ipnet" -version = "2.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" - -[[package]] -name = "is_terminal_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" - -[[package]] -name = "itoa" -version = "1.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" - -[[package]] -name = "jni" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" -dependencies = [ - "cfg-if", - "combine", - "jni-macros", - "jni-sys", - "log", - "simd_cesu8", - "thiserror", - "walkdir", - "windows-link", -] - -[[package]] -name = "jni-macros" -version = "0.22.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" -dependencies = [ - "proc-macro2", - "quote", - "rustc_version", - "simd_cesu8", - "syn", -] - -[[package]] -name = "jni-sys" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" -dependencies = [ - "jni-sys-macros", -] - -[[package]] -name = "jni-sys-macros" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" -dependencies = [ - "quote", - "syn", -] - -[[package]] -name = "jobserver" -version = "0.1.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" -dependencies = [ - "getrandom 0.4.3", - "libc", -] - -[[package]] -name = "js-sys" -version = "0.3.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102" -dependencies = [ - "cfg-if", - "futures-util", - "wasm-bindgen", -] - -[[package]] -name = "jsonwebtoken" -version = "10.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eba32bfb4ffdeaca3e34431072faf01745c9b26d25504aa7a6cf5684334fc4fc" -dependencies = [ - "aws-lc-rs", - "base64", - "getrandom 0.2.17", - "js-sys", - "serde", - "serde_json", - "signature", - "zeroize", -] - -[[package]] -name = "konst" -version = "0.2.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" -dependencies = [ - "konst_macro_rules", -] - -[[package]] -name = "konst_macro_rules" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" - -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - -[[package]] -name = "libc" -version = "0.2.186" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" - -[[package]] -name = "litemap" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" - -[[package]] -name = "log" -version = "0.4.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" - -[[package]] -name = "lru-slab" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" - -[[package]] -name = "memchr" -version = "2.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" - -[[package]] -name = "mio" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" -dependencies = [ - "libc", - "wasi", - "windows-sys 0.61.2", -] - -[[package]] -name = "num-traits" -version = "0.2.19" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" -dependencies = [ - "autocfg", -] - -[[package]] -name = "oci-client" -version = "0.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5261a7fb43d9c53b8e63e6d5e86860719dad253d015d022066c72d585125aed8" -dependencies = [ - "bytes", - "chrono", - "futures-util", - "hex", - "http", - "http-auth", - "jsonwebtoken", - "lazy_static", - "oci-spec", - "olpc-cjson", - "regex", - "reqwest", - "serde", - "serde_json", - "sha2 0.11.0", - "thiserror", - "tokio", - "tracing", - "unicase", -] - -[[package]] -name = "oci-spec" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8445a2631507cec628a15fdd6154b54a3ab3f20ed4fe9d73a3b8b7a4e1ba03a" -dependencies = [ - "const_format", - "derive_builder", - "getset", - "regex", - "serde", - "serde_json", - "strum", - "strum_macros", - "thiserror", -] - -[[package]] -name = "olpc-cjson" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "696183c9b5fe81a7715d074fd632e8bd46f4ccc0231a3ed7fc580a80de5f7083" -dependencies = [ - "serde", - "serde_json", - "unicode-normalization", -] - -[[package]] -name = "once_cell" -version = "1.21.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" - -[[package]] -name = "once_cell_polyfill" -version = "1.70.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" - -[[package]] -name = "openssl-probe" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" - -[[package]] -name = "percent-encoding" -version = "2.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" - -[[package]] -name = "pin-project-lite" -version = "0.2.17" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" - -[[package]] -name = "pkg-config" -version = "0.3.33" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" - -[[package]] -name = "potential_utf" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" -dependencies = [ - "zerovec", -] - -[[package]] -name = "proc-macro2" -version = "1.0.106" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "quinn" -version = "0.11.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8" -dependencies = [ - "bytes", - "cfg_aliases", - "pin-project-lite", - "quinn-proto", - "quinn-udp", - "rustc-hash", - "rustls", - "socket2", - "thiserror", - "tokio", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-proto" -version = "0.11.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560" -dependencies = [ - "aws-lc-rs", - "bytes", - "getrandom 0.4.3", - "lru-slab", - "rand", - "rand_pcg", - "ring", - "rustc-hash", - "rustls", - "rustls-pki-types", - "slab", - "thiserror", - "tinyvec", - "tracing", - "web-time", -] - -[[package]] -name = "quinn-udp" -version = "0.5.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694" -dependencies = [ - "cfg_aliases", - "libc", - "once_cell", - "socket2", - "tracing", - "windows-sys 0.61.2", -] - -[[package]] -name = "quote" -version = "1.0.46" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368" -dependencies = [ - "proc-macro2", -] - -[[package]] -name = "r-efi" -version = "6.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" - -[[package]] -name = "rand" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80" -dependencies = [ - "chacha20", - "getrandom 0.4.3", - "rand_core 0.10.1", -] - -[[package]] -name = "rand_core" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" -dependencies = [ - "getrandom 0.2.17", -] - -[[package]] -name = "rand_core" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" - -[[package]] -name = "rand_pcg" -version = "0.10.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" -dependencies = [ - "rand_core 0.10.1", -] - -[[package]] -name = "regex" -version = "1.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2" -dependencies = [ - "aho-corasick", - "memchr", - "regex-automata", - "regex-syntax", -] - -[[package]] -name = "regex-automata" -version = "0.4.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db" -dependencies = [ - "aho-corasick", - "memchr", - "regex-syntax", -] - -[[package]] -name = "regex-syntax" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" - -[[package]] -name = "reqwest" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3" -dependencies = [ - "base64", - "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-body-util", - "hyper", - "hyper-rustls", - "hyper-util", - "js-sys", - "log", - "percent-encoding", - "pin-project-lite", - "quinn", - "rustls", - "rustls-pki-types", - "rustls-platform-verifier", - "serde", - "serde_json", - "serde_urlencoded", - "sync_wrapper", - "tokio", - "tokio-rustls", - "tokio-util", - "tower", - "tower-http", - "tower-service", - "url", - "wasm-bindgen", - "wasm-bindgen-futures", - "wasm-streams", - "web-sys", -] - -[[package]] -name = "ring" -version = "0.17.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" -dependencies = [ - "cc", - "cfg-if", - "getrandom 0.2.17", - "libc", - "untrusted 0.9.0", - "windows-sys 0.52.0", -] - -[[package]] -name = "rustc-hash" -version = "2.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" - -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - -[[package]] -name = "rustls" -version = "0.23.41" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" -dependencies = [ - "aws-lc-rs", - "once_cell", - "rustls-pki-types", - "rustls-webpki", - "subtle", - "zeroize", -] - -[[package]] -name = "rustls-native-certs" -version = "0.8.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" -dependencies = [ - "openssl-probe", - "rustls-pki-types", - "schannel", - "security-framework", -] - -[[package]] -name = "rustls-pki-types" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046" -dependencies = [ - "web-time", - "zeroize", -] - -[[package]] -name = "rustls-platform-verifier" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0" -dependencies = [ - "core-foundation", - "core-foundation-sys", - "jni", - "log", - "once_cell", - "rustls", - "rustls-native-certs", - "rustls-platform-verifier-android", - "rustls-webpki", - "security-framework", - "security-framework-sys", - "webpki-root-certs", - "windows-sys 0.61.2", -] - -[[package]] -name = "rustls-platform-verifier-android" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" - -[[package]] -name = "rustls-webpki" -version = "0.103.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" -dependencies = [ - "aws-lc-rs", - "ring", - "rustls-pki-types", - "untrusted 0.9.0", -] - -[[package]] -name = "rustversion" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" - -[[package]] -name = "ryu" -version = "1.0.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" - -[[package]] -name = "same-file" -version = "1.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" -dependencies = [ - "winapi-util", -] - -[[package]] -name = "schannel" -version = "0.1.29" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "security-framework" -version = "3.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" -dependencies = [ - "bitflags", - "core-foundation", - "core-foundation-sys", - "libc", - "security-framework-sys", -] - -[[package]] -name = "security-framework-sys" -version = "2.17.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" -dependencies = [ - "core-foundation-sys", - "libc", -] - -[[package]] -name = "semver" -version = "1.0.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" - -[[package]] -name = "serde" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" -dependencies = [ - "serde_core", - "serde_derive", -] - -[[package]] -name = "serde_core" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" -dependencies = [ - "serde_derive", -] - -[[package]] -name = "serde_derive" -version = "1.0.228" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "serde_json" -version = "1.0.150" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" -dependencies = [ - "itoa", - "memchr", - "serde", - "serde_core", - "zmij", -] - -[[package]] -name = "serde_urlencoded" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" -dependencies = [ - "form_urlencoded", - "itoa", - "ryu", - "serde", -] - -[[package]] -name = "sha2" -version = "0.10.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - -[[package]] -name = "sha2" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" -dependencies = [ - "cfg-if", - "cpufeatures 0.3.0", - "digest 0.11.3", -] - -[[package]] -name = "shlex" -version = "2.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - -[[package]] -name = "signature" -version = "2.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" -dependencies = [ - "rand_core 0.6.4", -] - -[[package]] -name = "simd_cesu8" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33" -dependencies = [ - "rustc_version", - "simdutf8", -] - -[[package]] -name = "simdutf8" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" - -[[package]] -name = "slab" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" - -[[package]] -name = "smallvec" -version = "1.15.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" - -[[package]] -name = "socket2" -version = "0.6.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - -[[package]] -name = "stable_deref_trait" -version = "1.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" - -[[package]] -name = "strsim" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" - -[[package]] -name = "strum" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" - -[[package]] -name = "strum_macros" -version = "0.27.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "subtle" -version = "2.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" - -[[package]] -name = "syn" -version = "2.0.118" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", -] - -[[package]] -name = "sync_wrapper" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" -dependencies = [ - "futures-core", -] - -[[package]] -name = "synstructure" -version = "0.13.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "thiserror" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tinystr" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" -dependencies = [ - "displaydoc", - "zerovec", -] - -[[package]] -name = "tinyvec" -version = "1.12.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" -dependencies = [ - "tinyvec_macros", -] - -[[package]] -name = "tinyvec_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" - -[[package]] -name = "tokio" -version = "1.52.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" -dependencies = [ - "bytes", - "libc", - "mio", - "pin-project-lite", - "signal-hook-registry", - "socket2", - "tokio-macros", - "windows-sys 0.61.2", -] - -[[package]] -name = "tokio-macros" -version = "2.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tokio-rustls" -version = "0.26.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" -dependencies = [ - "rustls", - "tokio", -] - -[[package]] -name = "tokio-util" -version = "0.7.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" -dependencies = [ - "bytes", - "futures-core", - "futures-sink", - "pin-project-lite", - "tokio", -] - -[[package]] -name = "tower" -version = "0.5.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" -dependencies = [ - "futures-core", - "futures-util", - "pin-project-lite", - "sync_wrapper", - "tokio", - "tower-layer", - "tower-service", -] - -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags", - "bytes", - "futures-util", - "http", - "http-body", - "pin-project-lite", - "tower", - "tower-layer", - "tower-service", - "url", -] - -[[package]] -name = "tower-layer" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" - -[[package]] -name = "tower-service" -version = "0.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" - -[[package]] -name = "tracing" -version = "0.1.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" -dependencies = [ - "log", - "pin-project-lite", - "tracing-attributes", - "tracing-core", -] - -[[package]] -name = "tracing-attributes" -version = "0.1.31" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "tracing-core" -version = "0.1.36" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" -dependencies = [ - "once_cell", -] - -[[package]] -name = "try-lock" -version = "0.2.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" - -[[package]] -name = "typenum" -version = "1.20.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" - -[[package]] -name = "unicase" -version = "2.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" - -[[package]] -name = "unicode-ident" -version = "1.0.24" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" - -[[package]] -name = "unicode-normalization" -version = "0.1.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" -dependencies = [ - "tinyvec", -] - -[[package]] -name = "unicode-xid" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" - -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - -[[package]] -name = "untrusted" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" - -[[package]] -name = "url" -version = "2.5.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" -dependencies = [ - "form_urlencoded", - "idna", - "percent-encoding", - "serde", -] - -[[package]] -name = "utf8_iter" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" - -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" -dependencies = [ - "getrandom 0.4.3", - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "version_check" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" - -[[package]] -name = "walkdir" -version = "2.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" -dependencies = [ - "same-file", - "winapi-util", -] - -[[package]] -name = "want" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" -dependencies = [ - "try-lock", -] - -[[package]] -name = "wasi" -version = "0.11.1+wasi-snapshot-preview1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" - -[[package]] -name = "wasm-bindgen" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4" -dependencies = [ - "cfg-if", - "once_cell", - "rustversion", - "wasm-bindgen-macro", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-futures" -version = "0.4.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e" -dependencies = [ - "bumpalo", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.126" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24" -dependencies = [ - "unicode-ident", -] - -[[package]] -name = "wasm-streams" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" -dependencies = [ - "futures-util", - "js-sys", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", -] - -[[package]] -name = "web-sys" -version = "0.3.103" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki-root-certs" -version = "1.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0d46a5a140e6f7afeccd8eae97eff335163939eac8b929834875168b29b3d267" -dependencies = [ - "rustls-pki-types", -] - -[[package]] -name = "winapi-util" -version = "0.1.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" -dependencies = [ - "windows-sys 0.61.2", -] - -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "windows-link" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" - -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-sys" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" -dependencies = [ - "windows-targets", -] - -[[package]] -name = "windows-sys" -version = "0.61.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-targets" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" -dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", -] - -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" - -[[package]] -name = "windows_aarch64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" - -[[package]] -name = "windows_i686_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" - -[[package]] -name = "windows_i686_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" - -[[package]] -name = "windows_i686_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" - -[[package]] -name = "windows_x86_64_gnu" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" - -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" - -[[package]] -name = "windows_x86_64_msvc" -version = "0.52.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" - -[[package]] -name = "writeable" -version = "0.6.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" - -[[package]] -name = "yoke" -version = "0.8.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" -dependencies = [ - "stable_deref_trait", - "yoke-derive", - "zerofrom", -] - -[[package]] -name = "yoke-derive" -version = "0.8.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zerofrom" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" -dependencies = [ - "zerofrom-derive", -] - -[[package]] -name = "zerofrom-derive" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "synstructure", -] - -[[package]] -name = "zeroize" -version = "1.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" -dependencies = [ - "zeroize_derive", -] - -[[package]] -name = "zeroize_derive" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zerotrie" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" -dependencies = [ - "displaydoc", - "yoke", - "zerofrom", -] - -[[package]] -name = "zerovec" -version = "0.11.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" -dependencies = [ - "yoke", - "zerofrom", - "zerovec-derive", -] - -[[package]] -name = "zerovec-derive" -version = "0.11.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "zmij" -version = "1.0.21" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" - -[[package]] -name = "zstd" -version = "0.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a" -dependencies = [ - "zstd-safe", -] - -[[package]] -name = "zstd-safe" -version = "7.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d" -dependencies = [ - "zstd-sys", -] - -[[package]] -name = "zstd-sys" -version = "2.0.16+zstd.1.5.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748" -dependencies = [ - "cc", - "pkg-config", -] diff --git a/Cargo.toml b/Cargo.toml index 825ad03..1eb1be9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 [workspace] @@ -11,15 +11,9 @@ edition = "2024" version = "0.1.0" license = "Apache-2.0" authors = ["Nikolay Govorov <me@govorov.online>"] -repository = "https://git.dimidiumlabs.io/hule" +repository = "https://github.com/dimidiumlabs/hule" [workspace.dependencies] # local dependencies -hule-hmi = { path = "crates/hule-hmi" } hule-oci = { path = "crates/hule-oci" } hule-vmm = { path = "crates/hule-vmm" } - -# external dependencies -serde = { version = "1", features = ["derive"] } -serde_json = "1" -tokio = "1" diff --git a/LICENSES/CC-BY-3.0.txt b/LICENSES/CC-BY-3.0.txt deleted file mode 100644 --- a/LICENSES/CC-BY-3.0.txt +++ /dev/null @@ -1,319 +0,0 @@ -Creative Commons Legal Code - -Attribution 3.0 Unported - - CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE - LEGAL SERVICES. DISTRIBUTION OF THIS LICENSE DOES NOT CREATE AN - ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS - INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES - REGARDING THE INFORMATION PROVIDED, AND DISCLAIMS LIABILITY FOR - DAMAGES RESULTING FROM ITS USE. - -License - -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE -COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY -COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS -AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE -TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY -BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS -CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND -CONDITIONS. - -1. Definitions - - a. "Adaptation" means a work based upon the Work, or upon the Work and - other pre-existing works, such as a translation, adaptation, - derivative work, arrangement of music or other alterations of a - literary or artistic work, or phonogram or performance and includes - cinematographic adaptations or any other form in which the Work may be - recast, transformed, or adapted including in any form recognizably - derived from the original, except that a work that constitutes a - Collection will not be considered an Adaptation for the purpose of - this License. For the avoidance of doubt, where the Work is a musical - work, performance or phonogram, the synchronization of the Work in - timed-relation with a moving image ("synching") will be considered an - Adaptation for the purpose of this License. - b. "Collection" means a collection of literary or artistic works, such as - encyclopedias and anthologies, or performances, phonograms or - broadcasts, or other works or subject matter other than works listed - in Section 1(f) below, which, by reason of the selection and - arrangement of their contents, constitute intellectual creations, in - which the Work is included in its entirety in unmodified form along - with one or more other contributions, each constituting separate and - independent works in themselves, which together are assembled into a - collective whole. A work that constitutes a Collection will not be - considered an Adaptation (as defined above) for the purposes of this - License. - c. "Distribute" means to make available to the public the original and - copies of the Work or Adaptation, as appropriate, through sale or - other transfer of ownership. - d. "Licensor" means the individual, individuals, entity or entities that - offer(s) the Work under the terms of this License. - e. "Original Author" means, in the case of a literary or artistic work, - the individual, individuals, entity or entities who created the Work - or if no individual or entity can be identified, the publisher; and in - addition (i) in the case of a performance the actors, singers, - musicians, dancers, and other persons who act, sing, deliver, declaim, - play in, interpret or otherwise perform literary or artistic works or - expressions of folklore; (ii) in the case of a phonogram the producer - being the person or legal entity who first fixes the sounds of a - performance or other sounds; and, (iii) in the case of broadcasts, the - organization that transmits the broadcast. - f. "Work" means the literary and/or artistic work offered under the terms - of this License including without limitation any production in the - literary, scientific and artistic domain, whatever may be the mode or - form of its expression including digital form, such as a book, - pamphlet and other writing; a lecture, address, sermon or other work - of the same nature; a dramatic or dramatico-musical work; a - choreographic work or entertainment in dumb show; a musical - composition with or without words; a cinematographic work to which are - assimilated works expressed by a process analogous to cinematography; - a work of drawing, painting, architecture, sculpture, engraving or - lithography; a photographic work to which are assimilated works - expressed by a process analogous to photography; a work of applied - art; an illustration, map, plan, sketch or three-dimensional work - relative to geography, topography, architecture or science; a - performance; a broadcast; a phonogram; a compilation of data to the - extent it is protected as a copyrightable work; or a work performed by - a variety or circus performer to the extent it is not otherwise - considered a literary or artistic work. - g. "You" means an individual or entity exercising rights under this - License who has not previously violated the terms of this License with - respect to the Work, or who has received express permission from the - Licensor to exercise rights under this License despite a previous - violation. - h. "Publicly Perform" means to perform public recitations of the Work and - to communicate to the public those public recitations, by any means or - process, including by wire or wireless means or public digital - performances; to make available to the public Works in such a way that - members of the public may access these Works from a place and at a - place individually chosen by them; to perform the Work to the public - by any means or process and the communication to the public of the - performances of the Work, including by public digital performance; to - broadcast and rebroadcast the Work by any means including signs, - sounds or images. - i. "Reproduce" means to make copies of the Work by any means including - without limitation by sound or visual recordings and the right of - fixation and reproducing fixations of the Work, including storage of a - protected performance or phonogram in digital form or other electronic - medium. - -2. Fair Dealing Rights. Nothing in this License is intended to reduce, -limit, or restrict any uses free from copyright or rights arising from -limitations or exceptions that are provided for in connection with the -copyright protection under copyright law or other applicable laws. - -3. License Grant. Subject to the terms and conditions of this License, -Licensor hereby grants You a worldwide, royalty-free, non-exclusive, -perpetual (for the duration of the applicable copyright) license to -exercise the rights in the Work as stated below: - - a. to Reproduce the Work, to incorporate the Work into one or more - Collections, and to Reproduce the Work as incorporated in the - Collections; - b. to create and Reproduce Adaptations provided that any such Adaptation, - including any translation in any medium, takes reasonable steps to - clearly label, demarcate or otherwise identify that changes were made - to the original Work. For example, a translation could be marked "The - original work was translated from English to Spanish," or a - modification could indicate "The original work has been modified."; - c. to Distribute and Publicly Perform the Work including as incorporated - in Collections; and, - d. to Distribute and Publicly Perform Adaptations. - e. For the avoidance of doubt: - - i. Non-waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme cannot be waived, the Licensor - reserves the exclusive right to collect such royalties for any - exercise by You of the rights granted under this License; - ii. Waivable Compulsory License Schemes. In those jurisdictions in - which the right to collect royalties through any statutory or - compulsory licensing scheme can be waived, the Licensor waives the - exclusive right to collect such royalties for any exercise by You - of the rights granted under this License; and, - iii. Voluntary License Schemes. The Licensor waives the right to - collect royalties, whether individually or, in the event that the - Licensor is a member of a collecting society that administers - voluntary licensing schemes, via that society, from any exercise - by You of the rights granted under this License. - -The above rights may be exercised in all media and formats whether now -known or hereafter devised. The above rights include the right to make -such modifications as are technically necessary to exercise the rights in -other media and formats. Subject to Section 8(f), all rights not expressly -granted by Licensor are hereby reserved. - -4. Restrictions. The license granted in Section 3 above is expressly made -subject to and limited by the following restrictions: - - a. You may Distribute or Publicly Perform the Work only under the terms - of this License. You must include a copy of, or the Uniform Resource - Identifier (URI) for, this License with every copy of the Work You - Distribute or Publicly Perform. You may not offer or impose any terms - on the Work that restrict the terms of this License or the ability of - the recipient of the Work to exercise the rights granted to that - recipient under the terms of the License. You may not sublicense the - Work. You must keep intact all notices that refer to this License and - to the disclaimer of warranties with every copy of the Work You - Distribute or Publicly Perform. When You Distribute or Publicly - Perform the Work, You may not impose any effective technological - measures on the Work that restrict the ability of a recipient of the - Work from You to exercise the rights granted to that recipient under - the terms of the License. This Section 4(a) applies to the Work as - incorporated in a Collection, but this does not require the Collection - apart from the Work itself to be made subject to the terms of this - License. If You create a Collection, upon notice from any Licensor You - must, to the extent practicable, remove from the Collection any credit - as required by Section 4(b), as requested. If You create an - Adaptation, upon notice from any Licensor You must, to the extent - practicable, remove from the Adaptation any credit as required by - Section 4(b), as requested. - b. If You Distribute, or Publicly Perform the Work or any Adaptations or - Collections, You must, unless a request has been made pursuant to - Section 4(a), keep intact all copyright notices for the Work and - provide, reasonable to the medium or means You are utilizing: (i) the - name of the Original Author (or pseudonym, if applicable) if supplied, - and/or if the Original Author and/or Licensor designate another party - or parties (e.g., a sponsor institute, publishing entity, journal) for - attribution ("Attribution Parties") in Licensor's copyright notice, - terms of service or by other reasonable means, the name of such party - or parties; (ii) the title of the Work if supplied; (iii) to the - extent reasonably practicable, the URI, if any, that Licensor - specifies to be associated with the Work, unless such URI does not - refer to the copyright notice or licensing information for the Work; - and (iv) , consistent with Section 3(b), in the case of an Adaptation, - a credit identifying the use of the Work in the Adaptation (e.g., - "French translation of the Work by Original Author," or "Screenplay - based on original Work by Original Author"). The credit required by - this Section 4 (b) may be implemented in any reasonable manner; - provided, however, that in the case of a Adaptation or Collection, at - a minimum such credit will appear, if a credit for all contributing - authors of the Adaptation or Collection appears, then as part of these - credits and in a manner at least as prominent as the credits for the - other contributing authors. For the avoidance of doubt, You may only - use the credit required by this Section for the purpose of attribution - in the manner set out above and, by exercising Your rights under this - License, You may not implicitly or explicitly assert or imply any - connection with, sponsorship or endorsement by the Original Author, - Licensor and/or Attribution Parties, as appropriate, of You or Your - use of the Work, without the separate, express prior written - permission of the Original Author, Licensor and/or Attribution - Parties. - c. Except as otherwise agreed in writing by the Licensor or as may be - otherwise permitted by applicable law, if You Reproduce, Distribute or - Publicly Perform the Work either by itself or as part of any - Adaptations or Collections, You must not distort, mutilate, modify or - take other derogatory action in relation to the Work which would be - prejudicial to the Original Author's honor or reputation. Licensor - agrees that in those jurisdictions (e.g. Japan), in which any exercise - of the right granted in Section 3(b) of this License (the right to - make Adaptations) would be deemed to be a distortion, mutilation, - modification or other derogatory action prejudicial to the Original - Author's honor and reputation, the Licensor will waive or not assert, - as appropriate, this Section, to the fullest extent permitted by the - applicable national law, to enable You to reasonably exercise Your - right under Section 3(b) of this License (right to make Adaptations) - but not otherwise. - -5. Representations, Warranties and Disclaimer - -UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR -OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY -KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, -INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, -FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF -LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, -WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION -OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE -LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR -ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES -ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS -BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - a. This License and the rights granted hereunder will terminate - automatically upon any breach by You of the terms of this License. - Individuals or entities who have received Adaptations or Collections - from You under this License, however, will not have their licenses - terminated provided such individuals or entities remain in full - compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will - survive any termination of this License. - b. Subject to the above terms and conditions, the license granted here is - perpetual (for the duration of the applicable copyright in the Work). - Notwithstanding the above, Licensor reserves the right to release the - Work under different license terms or to stop distributing the Work at - any time; provided, however that any such election will not serve to - withdraw this License (or any other license that has been, or is - required to be, granted under the terms of this License), and this - License will continue in full force and effect unless terminated as - stated above. - -8. Miscellaneous - - a. Each time You Distribute or Publicly Perform the Work or a Collection, - the Licensor offers to the recipient a license to the Work on the same - terms and conditions as the license granted to You under this License. - b. Each time You Distribute or Publicly Perform an Adaptation, Licensor - offers to the recipient a license to the original Work on the same - terms and conditions as the license granted to You under this License. - c. If any provision of this License is invalid or unenforceable under - applicable law, it shall not affect the validity or enforceability of - the remainder of the terms of this License, and without further action - by the parties to this agreement, such provision shall be reformed to - the minimum extent necessary to make such provision valid and - enforceable. - d. No term or provision of this License shall be deemed waived and no - breach consented to unless such waiver or consent shall be in writing - and signed by the party to be charged with such waiver or consent. - e. This License constitutes the entire agreement between the parties with - respect to the Work licensed here. There are no understandings, - agreements or representations with respect to the Work not specified - here. Licensor shall not be bound by any additional provisions that - may appear in any communication from You. This License may not be - modified without the mutual written agreement of the Licensor and You. - f. The rights granted under, and the subject matter referenced, in this - License were drafted utilizing the terminology of the Berne Convention - for the Protection of Literary and Artistic Works (as amended on - September 28, 1979), the Rome Convention of 1961, the WIPO Copyright - Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 - and the Universal Copyright Convention (as revised on July 24, 1971). - These rights and subject matter take effect in the relevant - jurisdiction in which the License terms are sought to be enforced - according to the corresponding provisions of the implementation of - those treaty provisions in the applicable national law. If the - standard suite of rights granted under applicable copyright law - includes additional rights not granted under this License, such - additional rights are deemed to be included in the License; this - License is not intended to restrict the license of any rights under - applicable law. - - -Creative Commons Notice - - Creative Commons is not a party to this License, and makes no warranty - whatsoever in connection with the Work. Creative Commons will not be - liable to You or any party on any legal theory for any damages - whatsoever, including without limitation any general, special, - incidental or consequential damages arising in connection to this - license. Notwithstanding the foregoing two (2) sentences, if Creative - Commons has expressly identified itself as the Licensor hereunder, it - shall have all rights and obligations of Licensor. - - Except for the limited purpose of indicating to the public that the - Work is licensed under the CCPL, Creative Commons does not authorize - the use by either party of the trademark "Creative Commons" or any - related trademark or logo of Creative Commons without the prior - written consent of Creative Commons. Any permitted use will be in - compliance with Creative Commons' then-current trademark usage - guidelines, as may be published on its website or otherwise made - available upon request from time to time. For the avoidance of doubt, - this trademark restriction does not form part of this License. - - Creative Commons may be contacted at https://creativecommons.org/. diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt deleted file mode 100644 --- a/LICENSES/CC-BY-4.0.txt +++ /dev/null @@ -1,156 +0,0 @@ -Creative Commons Attribution 4.0 International - - Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. - -Using Creative Commons Public Licenses - -Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. - -Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. - -Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. - -Creative Commons Attribution 4.0 International Public License - -By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. - -Section 1 – Definitions. - - a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. - - b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. - - c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. - - d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. - - e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. - - f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. - - g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. - - h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. - - i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. - - j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. - - k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. - -Section 2 – Scope. - - a. License grant. - - 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: - - A. reproduce and Share the Licensed Material, in whole or in part; and - - B. produce, reproduce, and Share Adapted Material. - - 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. - - 3. Term. The term of this Public License is specified in Section 6(a). - - 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. - - 5. Downstream recipients. - - A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. - - B. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. - - 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). - -b. Other rights. - - 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. - - 2. Patent and trademark rights are not licensed under this Public License. - - 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. - -Section 3 – License Conditions. - -Your exercise of the Licensed Rights is expressly made subject to the following conditions. - - a. Attribution. - - 1. If You Share the Licensed Material (including in modified form), You must: - - A. retain the following if it is supplied by the Licensor with the Licensed Material: - - i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); - - ii. a copyright notice; - - iii. a notice that refers to this Public License; - - iv. a notice that refers to the disclaimer of warranties; - - v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; - - B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and - - C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. - - 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. - - 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. - - 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. - -Section 4 – Sui Generis Database Rights. - -Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: - - a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; - - b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and - - c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. -For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. - -Section 5 – Disclaimer of Warranties and Limitation of Liability. - - a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. - - b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. - - c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. - -Section 6 – Term and Termination. - - a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. - - b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: - - 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or - - 2. upon express reinstatement by the Licensor. - - c. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. - - d. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. - - e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. - -Section 7 – Other Terms and Conditions. - - a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. - - b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. - -Section 8 – Interpretation. - - a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. - - b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. - - c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. - - d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. - -Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. - -Creative Commons may be contacted at creativecommons.org. diff --git a/README.md b/README.md index f335062..c91eb08 100644 --- a/README.md +++ b/README.md @@ -1,49 +1,3 @@ # Hule OCI-compliant layer for virtual machines. - -## Contributing - -We welcome your contributions, including code, bug reports, ideas, and success -stories. - -If you are making a contribution for the first time or from a new email, please -add yourself to the `.mailmap`. - -### Signoff - -To include your code, we ask that you read and agree to the [CLA](./CLA.md). To -sign, add a `CLA-Version: 1.0` and a `Signed-off-by` trailer to every commit -(`git commit -s --trailer "CLA-Version: 1.0"`). Each commit in a pull request -must carry a valid `Signed-off-by` line matching the commit author. Please use -your real name. We cannot include code from anonymous contributors. - -AI agents MUST NOT add Signed-off-by tags. Only humans can legally certify the -Contributor License Agreement. - -### AI policy - -You may use AI agents when writing code and documentation. AI is not allowed for -media including images, videos, fonts at all. You must fully read, understand, -and cleanup any code generated by the agent. We ask that you disclose the -agent's use and indicate the tool, model, and extent of contribution. - -Contributions should include an Assisted-by tag in the following format: -`Assisted-by: AGENT_NAME:MODEL_VERSION [TOOL1] [TOOL2]`, for example: -`Assisted-by: Claude:claude-4.6-opus coccinelle sparse` - -Remember, AI agents should make software better, not worse. - -## Licensing - -Hule source code is licensed under Apache-2.0. Documentation is licensed under -CC-BY-4.0. - -The image-generation scripts in `images/*/genimg` are derived from code -originally published by Drew DeVault as part of [SourceHut](https://sr.ht) and -remain licensed under AGPL-3.0-only. They are not linked into or included in -Hule binaries or release artifacts. Other source code and scripts developed for -Hule are licensed under Apache-2.0. - -Machine images remain subject to the licenses of their operating systems and -included software. diff --git a/REUSE.toml b/REUSE.toml index 9ad56a8..b140299 100644 --- a/REUSE.toml +++ b/REUSE.toml @@ -1,35 +1,13 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 version = 1 [[annotations]] path = [ + "README.md", "Cargo.toml", "Cargo.lock", - "mise.lock", ] SPDX-FileCopyrightText = "2026 Nikolay Govorov" SPDX-License-Identifier = "Apache-2.0" - -[[annotations]] -path = [ - ".mailmap", -] -SPDX-FileCopyrightText = "2026 Nikolay Govorov" -SPDX-License-Identifier = "Apache-2.0" - -[[annotations]] -path = [ - "CLA.md", -] -SPDX-FileCopyrightText = "2026 Nikolay Govorov" -SPDX-License-Identifier = "CC-BY-3.0" - -[[annotations]] -path = [ - "README.md", - "docs/*.md", -] -SPDX-FileCopyrightText = "2026 Nikolay Govorov" -SPDX-License-Identifier = "CC-BY-4.0" diff --git a/crates/hule-hmi/Cargo.toml b/crates/hule-hmi/Cargo.toml deleted file mode 100644 --- a/crates/hule-hmi/Cargo.toml +++ /dev/null @@ -1,17 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -[package] -name = "hule-hmi" -description = "Types and validation for Hule machine images" - -publish.workspace = true -edition.workspace = true -version.workspace = true -license.workspace = true -authors.workspace = true -repository.workspace = true - -[dependencies] -serde.workspace = true -serde_json.workspace = true diff --git a/crates/hule-hmi/src/lib.rs b/crates/hule-hmi/src/lib.rs deleted file mode 100644 --- a/crates/hule-hmi/src/lib.rs +++ /dev/null @@ -1,843 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! Types and validation for a Hule machine image `config.json`. -//! -//! This crate deliberately has no filesystem, registry, or VMM concerns. It -//! validates the declared image contract; callers decide how referenced files -//! are stored and executed. -//! -//! # Schema evolution -//! -//! Bump [`SCHEMA_VERSION`] only for breaking changes. Within a version: -//! [`Boot`]/[`Access`] are menus, so they tolerate unrecognized entries via -//! `Unknown`; [`Architecture`]/[`DiskFormat`] are single mandatory values -//! with no fallback, so they stay closed enums; `system.os` and digest -//! algorithms stay plain strings. No `deny_unknown_fields`; `rename_all = -//! "camelCase"` on every struct. - -use std::collections::HashSet; -use std::fmt; -use std::path::{Component, Path}; - -use serde::{Deserialize, Serialize}; - -pub const SCHEMA_VERSION: u8 = 1; -pub const KIND: &str = "MachineImage"; - -pub const BOOT_LINUX_DIRECT: &str = "linux/direct"; -pub const BOOT_FIRMWARE_DISK_BIOS: &str = "firmware-disk/bios"; -pub const BOOT_FIRMWARE_DISK_UEFI: &str = "firmware-disk/uefi"; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum DiskFormat { - Qcow2, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(transparent)] -pub struct Digest(pub String); - -impl fmt::Display for Digest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(&self.0) - } -} - -impl Digest { - fn validate_into(&self, field: &str, validation: &mut Validation) { - let Some(hex) = self.0.strip_prefix("sha256:") else { - validation.error(format!("{field} must use sha256")); - return; - }; - if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { - validation.error(format!("{field} must contain 64 hexadecimal digits")); - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ResourceRange { - pub minimum: u64, - pub default: u64, -} - -impl ResourceRange { - fn validate_into(self, field: &str, validation: &mut Validation) { - if self.minimum == 0 { - validation.error(format!("{field}.minimum must be greater than zero")); - } - if self.default < self.minimum { - validation.error(format!("{field}.default must be at least minimum")); - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct FileRef { - pub path: String, - pub digest: Digest, -} - -impl FileRef { - fn validate_into(&self, field: &str, validation: &mut Validation) { - validation.path(&self.path, &format!("{field}.path")); - self.digest - .validate_into(&format!("{field}.digest"), validation); - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BootBios { - pub protocol: String, - pub disk: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BootUefi { - pub protocol: String, - pub disk: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct BootLinux { - pub protocol: String, - pub disk: String, - pub kernel: FileRef, - pub initrd: FileRef, - pub cmdline: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(untagged)] -pub enum Boot { - Bios(BootBios), - Uefi(BootUefi), - Linux(BootLinux), - Unknown(serde_json::Value), -} - -impl<'de> Deserialize<'de> for Boot { - fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { - use serde::de::Error; - - let value = serde_json::Value::deserialize(deserializer)?; - let protocol = value.get("protocol").and_then(|p| p.as_str()).unwrap_or(""); - - #[derive(Deserialize)] - struct Raw { - disk: String, - #[serde(default)] - kernel: Option<FileRef>, - #[serde(default)] - initrd: Option<FileRef>, - #[serde(default)] - cmdline: Option<String>, - } - - match protocol { - BOOT_FIRMWARE_DISK_BIOS => { - let raw: Raw = serde_json::from_value(value).map_err(Error::custom)?; - if raw.kernel.is_some() || raw.initrd.is_some() || raw.cmdline.is_some() { - return Err(Error::custom( - "firmware-disk boot must not contain kernel, initrd, or cmdline", - )); - } - Ok(Self::Bios(BootBios { - protocol: BOOT_FIRMWARE_DISK_BIOS.into(), - disk: raw.disk, - })) - } - BOOT_FIRMWARE_DISK_UEFI => { - let raw: Raw = serde_json::from_value(value).map_err(Error::custom)?; - if raw.kernel.is_some() || raw.initrd.is_some() || raw.cmdline.is_some() { - return Err(Error::custom( - "firmware-disk boot must not contain kernel, initrd, or cmdline", - )); - } - Ok(Self::Uefi(BootUefi { - protocol: BOOT_FIRMWARE_DISK_UEFI.into(), - disk: raw.disk, - })) - } - BOOT_LINUX_DIRECT => { - let raw: Raw = serde_json::from_value(value).map_err(Error::custom)?; - Ok(Self::Linux(BootLinux { - protocol: BOOT_LINUX_DIRECT.into(), - disk: raw.disk, - kernel: raw.kernel.ok_or_else(|| Error::missing_field("kernel"))?, - initrd: raw.initrd.ok_or_else(|| Error::missing_field("initrd"))?, - cmdline: raw.cmdline.ok_or_else(|| Error::missing_field("cmdline"))?, - })) - } - _ => Ok(Self::Unknown(value)), - } - } -} - -impl Boot { - pub fn protocol(&self) -> &str { - match self { - Self::Bios(v) => &v.protocol, - Self::Uefi(v) => &v.protocol, - Self::Linux(v) => &v.protocol, - Self::Unknown(v) => v.get("protocol").and_then(|p| p.as_str()).unwrap_or(""), - } - } - - pub fn disk(&self) -> &str { - match self { - Self::Bios(v) => &v.disk, - Self::Uefi(v) => &v.disk, - Self::Linux(v) => &v.disk, - Self::Unknown(_) => "", - } - } - - /// False only for `Unknown`. - pub fn is_recognized(&self) -> bool { - !matches!(self, Self::Unknown(_)) - } - - fn validate_into(&self, field: &str, validation: &mut Validation) { - match self { - Self::Bios(value) => { - if value.protocol != BOOT_FIRMWARE_DISK_BIOS { - validation.error(format!( - "{field} BIOS protocol must be '{BOOT_FIRMWARE_DISK_BIOS}'" - )); - } - validation.required(&value.disk, &format!("{field}.disk")); - } - Self::Uefi(value) => { - if value.protocol != BOOT_FIRMWARE_DISK_UEFI { - validation.error(format!( - "{field} UEFI protocol must be '{BOOT_FIRMWARE_DISK_UEFI}'" - )); - } - validation.required(&value.disk, &format!("{field}.disk")); - } - Self::Linux(value) => { - if value.protocol != BOOT_LINUX_DIRECT { - validation.error(format!( - "{field} direct Linux protocol must be '{BOOT_LINUX_DIRECT}'" - )); - } - validation.required(&value.disk, &format!("{field}.disk")); - value - .kernel - .validate_into(&format!("{field}.kernel"), validation); - value - .initrd - .validate_into(&format!("{field}.initrd"), validation); - validation.required(&value.cmdline, &format!("{field}.cmdline")); - } - // Nothing to check: unrecognized entries are tolerated, not inspected. - Self::Unknown(_) => {} - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum Architecture { - Amd64, - Arm64, - Loong64, - Ppc64le, - Riscv64, - S390x, -} - -impl Architecture { - /// The architecture this process is running on, if it's one we know. - pub fn host() -> Option<Self> { - match std::env::consts::ARCH { - "x86_64" => Some(Self::Amd64), - "aarch64" => Some(Self::Arm64), - "loongarch64" => Some(Self::Loong64), - "riscv64" => Some(Self::Riscv64), - "s390x" => Some(Self::S390x), - "powerpc64" if cfg!(target_endian = "little") => Some(Self::Ppc64le), - _ => None, - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct System { - pub os: String, - #[serde(skip_serializing_if = "Option::is_none")] - pub name: Option<String>, - pub version: String, - pub architecture: Architecture, -} - -impl System { - fn validate_into(&self, field: &str, validation: &mut Validation) { - validation.required(&self.os, &format!("{field}.os")); - if let Some(name) = &self.name { - validation.required(name, &format!("{field}.name")); - } - validation.required(&self.version, &format!("{field}.version")); - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Disk { - pub id: String, - pub format: DiskFormat, - pub path: String, - pub digest: Digest, - pub virt_size: u64, - pub disk_size: u64, -} - -impl Disk { - fn validate_into(&self, field: &str, validation: &mut Validation) { - validation.required(&self.id, &format!("{field}.id")); - validation.path(&self.path, &format!("{field}.path")); - self.digest - .validate_into(&format!("{field}.digest"), validation); - if self.virt_size == 0 { - validation.error(format!("{field}.virtSize must be greater than zero")); - } - if self.disk_size == 0 { - validation.error(format!("{field}.diskSize must be greater than zero")); - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize)] -#[serde(untagged, rename_all = "camelCase")] -pub enum Access { - Ssh { - #[serde(rename = "type")] - kind: String, - port: u16, - user: String, - auth: String, - }, - /// qemu-guest-agent. The hypervisor backend chooses and configures a - /// compatible transport; the image only promises that the agent runs. - Qga { - #[serde(rename = "type")] - kind: String, - }, - /// Unrecognized access surface, preserved verbatim. - Unknown(serde_json::Value), -} - -impl<'de> Deserialize<'de> for Access { - fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { - use serde::de::Error; - - let value = serde_json::Value::deserialize(deserializer)?; - let kind = value.get("type").and_then(|t| t.as_str()).unwrap_or(""); - - match kind { - "ssh" => { - #[derive(Deserialize)] - struct Raw { - port: u16, - user: String, - auth: String, - } - let raw: Raw = serde_json::from_value(value).map_err(Error::custom)?; - Ok(Self::Ssh { - kind: "ssh".into(), - port: raw.port, - user: raw.user, - auth: raw.auth, - }) - } - "qga" => Ok(Self::Qga { kind: "qga".into() }), - _ => Ok(Self::Unknown(value)), - } - } -} - -impl Access { - /// False only for `Unknown`. - pub fn is_recognized(&self) -> bool { - !matches!(self, Self::Unknown(_)) - } - - fn validate_into(&self, field: &str, validation: &mut Validation) { - match self { - Self::Ssh { - port, user, auth, .. - } => { - if *port == 0 { - validation.error(format!("{field}.port must be greater than zero")); - } - validation.required(user, &format!("{field}.user")); - validation.required(auth, &format!("{field}.auth")); - } - Self::Qga { .. } | Self::Unknown(_) => {} - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct NetworkDhcp {} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct NetworkStatic { - pub address: String, - pub gateway: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(tag = "mode", rename_all = "lowercase")] -pub enum Network { - Dhcp(NetworkDhcp), - Static(NetworkStatic), -} - -impl Network { - fn validate_into(&self, field: &str, validation: &mut Validation) { - if let Self::Static(network) = self { - validation.required(&network.address, &format!("{field}.address")); - validation.required(&network.gateway, &format!("{field}.gateway")); - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Machine { - pub cpu: ResourceRange, - pub ram: ResourceRange, - pub boot: Vec<Boot>, - #[serde(default, skip_serializing_if = "Vec::is_empty")] - pub access: Vec<Access>, - pub network: Network, -} - -impl Machine { - fn validate_into(&self, field: &str, validation: &mut Validation) { - self.cpu.validate_into(&format!("{field}.cpu"), validation); - self.ram.validate_into(&format!("{field}.ram"), validation); - if !self.boot.iter().any(Boot::is_recognized) { - validation.error(format!( - "{field}.boot must contain at least one supported boot protocol" - )); - } - for (index, boot) in self.boot.iter().enumerate() { - boot.validate_into(&format!("{field}.boot[{index}]"), validation); - } - if !self.access.is_empty() && !self.access.iter().any(Access::is_recognized) { - validation.error(format!( - "{field}.access must contain at least one supported access method" - )); - } - for (index, access) in self.access.iter().enumerate() { - access.validate_into(&format!("{field}.access[{index}]"), validation); - } - self.network - .validate_into(&format!("{field}.network"), validation); - } -} - -#[derive(Default)] -struct Validation { - issues: Vec<String>, -} - -impl Validation { - fn error(&mut self, message: impl Into<String>) { - self.issues.push(message.into()); - } - - fn required(&mut self, value: &str, field: &str) { - if value.trim().is_empty() { - self.error(format!("{field} must not be empty")); - } - } - - fn path(&mut self, value: &str, field: &str) { - let path = Path::new(value); - if value.is_empty() - || path.is_absolute() - || path - .components() - .any(|component| !matches!(component, Component::Normal(_))) - { - self.error(format!("{field} must be a relative normalized path")); - } - } - - fn finish(self) -> Result<(), ValidationError> { - if self.issues.is_empty() { - Ok(()) - } else { - Err(ValidationError { - issues: self.issues, - }) - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ValidationError { - issues: Vec<String>, -} - -impl ValidationError { - fn single(message: impl Into<String>) -> Self { - Self { - issues: vec![message.into()], - } - } - - pub fn issues(&self) -> &[String] { - &self.issues - } -} - -impl fmt::Display for ValidationError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "invalid Hule image configuration: {}", - self.issues.join("; ") - ) - } -} - -impl std::error::Error for ValidationError {} - -#[derive(Debug)] -pub enum ParseError { - Json(serde_json::Error), - Validation(ValidationError), -} - -impl fmt::Display for ParseError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Json(error) => write!(f, "invalid JSON: {error}"), - Self::Validation(error) => error.fmt(f), - } - } -} - -impl std::error::Error for ParseError {} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MachineImage { - pub schema_version: u8, - pub kind: String, - pub system: System, - pub machine: Machine, - pub disks: Vec<Disk>, -} - -impl MachineImage { - pub fn from_json(data: &[u8]) -> Result<Self, ParseError> { - #[derive(Deserialize)] - #[serde(rename_all = "camelCase")] - struct Header { - schema_version: u8, - #[serde(default)] - kind: Option<String>, - } - - let header: Header = serde_json::from_slice(data).map_err(ParseError::Json)?; - if header.schema_version != SCHEMA_VERSION { - return Err(ParseError::Validation(ValidationError::single(format!( - "unsupported schemaVersion {}", - header.schema_version - )))); - } - if header.kind.as_deref() != Some(KIND) { - return Err(ParseError::Validation(ValidationError::single(format!( - "kind must be '{KIND}'" - )))); - } - - let image: Self = serde_json::from_slice(data).map_err(ParseError::Json)?; - image.validate().map_err(ParseError::Validation)?; - Ok(image) - } - - pub fn validate(&self) -> Result<(), ValidationError> { - if self.schema_version != SCHEMA_VERSION { - return Err(ValidationError::single(format!( - "unsupported schemaVersion {}", - self.schema_version - ))); - } - if self.kind != KIND { - return Err(ValidationError::single(format!("kind must be '{KIND}'"))); - } - - let mut validation = Validation::default(); - self.system.validate_into("system", &mut validation); - self.machine.validate_into("machine", &mut validation); - - if self.disks.is_empty() { - validation.error("disks must not be empty"); - } - let mut disk_ids = HashSet::new(); - let mut paths = HashSet::new(); - for (index, disk) in self.disks.iter().enumerate() { - let at = format!("disks[{index}]"); - disk.validate_into(&at, &mut validation); - if !disk_ids.insert(disk.id.as_str()) { - validation.error(format!("duplicate disk id '{}'", disk.id)); - } - if !paths.insert(disk.path.as_str()) { - validation.error(format!("duplicate image path '{}'", disk.path)); - } - } - - let mut boot_protocols = HashSet::new(); - for (index, boot) in self.machine.boot.iter().enumerate() { - if !boot.is_recognized() { - // Tolerated, not cross-referenced: we don't know what its - // fields (e.g. "disk") even mean. - continue; - } - if !boot_protocols.insert(boot.protocol()) { - validation.error(format!("duplicate boot protocol '{}'", boot.protocol())); - } - if !disk_ids.contains(boot.disk()) { - validation.error(format!( - "machine.boot[{index}] references unknown disk '{}'", - boot.disk() - )); - } - if let Boot::Linux(linux) = boot { - if self.system.os != "linux" { - validation.error(format!( - "machine.boot[{index}] protocol '{BOOT_LINUX_DIRECT}' requires system.os 'linux'" - )); - } - for path in [&linux.kernel.path, &linux.initrd.path] { - if !paths.insert(path) { - validation.error(format!("duplicate image path '{path}'")); - } - } - } - } - - validation.finish() - } - - pub fn referenced_paths(&self) -> impl Iterator<Item = &str> { - self.disks.iter().map(|d| d.path.as_str()).chain( - self.machine - .boot - .iter() - .flat_map(|boot| match boot { - Boot::Bios(_) | Boot::Uefi(_) | Boot::Unknown(_) => [None, None], - Boot::Linux(v) => [Some(v.kernel.path.as_str()), Some(v.initrd.path.as_str())], - }) - .flatten(), - ) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn valid_json() -> Vec<u8> { - br#"{"schemaVersion":1,"kind":"MachineImage","system":{"os":"linux","name":"alpine","version":"3.24","architecture":"amd64"},"machine":{"cpu":{"minimum":1,"default":2},"ram":{"minimum":268435456,"default":1073741824},"boot":[{"protocol":"firmware-disk/bios","disk":"root"}],"access":[{"type":"ssh","port":22,"user":"build","auth":"empty-password"}],"network":{"mode":"static","address":"10.0.2.15/24","gateway":"10.0.2.2"}},"disks":[{"id":"root","format":"qcow2","path":"root.hmi","digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","virtSize":1024,"diskSize":512}]}"#.to_vec() - } - - #[test] - fn parses_and_round_trips_valid_config() { - let image = MachineImage::from_json(&valid_json()).unwrap(); - let encoded = serde_json::to_vec(&image).unwrap(); - assert_eq!(MachineImage::from_json(&encoded).unwrap(), image); - } - - #[test] - fn rejects_unknown_disk_and_unsafe_path() { - let mut image = MachineImage::from_json(&valid_json()).unwrap(); - image.disks[0].path = "../root.hmi".into(); - match &mut image.machine.boot[0] { - Boot::Bios(v) => v.disk = "missing".into(), - Boot::Uefi(_) | Boot::Linux(_) | Boot::Unknown(_) => unreachable!(), - } - let error = image.validate().unwrap_err(); - assert!( - error - .issues() - .iter() - .any(|v| v.contains("relative normalized path")) - ); - assert!(error.issues().iter().any(|v| v.contains("unknown disk"))); - } - - #[test] - fn rejects_invalid_digest_and_resource_range() { - let mut image = MachineImage::from_json(&valid_json()).unwrap(); - image.disks[0].digest = Digest("md5:no".into()); - image.machine.cpu.default = 0; - let error = image.validate().unwrap_err(); - assert_eq!(error.issues().len(), 2); - } - - #[test] - fn system_name_is_optional_but_not_empty() { - let mut image = MachineImage::from_json(&valid_json()).unwrap(); - image.system.name = None; - let encoded = serde_json::to_value(&image).unwrap(); - assert!(encoded["system"].get("name").is_none()); - image.validate().unwrap(); - - image.system.name = Some(String::new()); - assert!(image.validate().is_err()); - } - - #[test] - fn parses_uefi_firmware_disk_boot() { - let mut image = MachineImage::from_json(&valid_json()).unwrap(); - image.machine.boot[0] = Boot::Uefi(BootUefi { - protocol: BOOT_FIRMWARE_DISK_UEFI.into(), - disk: "root".into(), - }); - - let encoded = serde_json::to_vec(&image).unwrap(); - let decoded = MachineImage::from_json(&encoded).unwrap(); - assert_eq!(decoded.machine.boot[0].protocol(), BOOT_FIRMWARE_DISK_UEFI); - } - - #[test] - fn rejects_config_whose_only_boot_entry_is_unrecognized() { - // An unrecognized boot protocol must not fail *parsing* -- see - // `mixed_boot_list_tolerates_unrecognized_entries` below for why -- - // but a config with *no* recognized entry at all is unusable and - // must fail *validation*. - let json = String::from_utf8(valid_json()) - .unwrap() - .replace(BOOT_FIRMWARE_DISK_BIOS, "firmware-disk/unknown"); - let error = MachineImage::from_json(json.as_bytes()).unwrap_err(); - assert!( - error - .to_string() - .contains("must contain at least one supported boot protocol") - ); - } - - #[test] - fn mixed_boot_list_tolerates_unrecognized_entries() { - // A newer image may list a protocol this version doesn't know about - // alongside one it does; parsing and validation must both succeed, - // and the unrecognized entry must round-trip losslessly. - let json = String::from_utf8(valid_json()).unwrap().replace( - r#"[{"protocol":"firmware-disk/bios","disk":"root"}]"#, - r#"[{"protocol":"firmware-disk/bios","disk":"root"},{"protocol":"vsock/direct","disk":"root","futureField":42}]"#, - ); - let image = MachineImage::from_json(json.as_bytes()).unwrap(); - assert_eq!(image.machine.boot.len(), 2); - assert!(image.machine.boot[0].is_recognized()); - assert!(!image.machine.boot[1].is_recognized()); - - let encoded = serde_json::to_vec(&image).unwrap(); - assert_eq!(MachineImage::from_json(&encoded).unwrap(), image); - } - - #[test] - fn rejects_config_whose_only_access_entry_is_unrecognized() { - let json = String::from_utf8(valid_json()).unwrap().replace( - r#"{"type":"ssh","port":22,"user":"build","auth":"empty-password"}"#, - r#"{"type":"vsock-agent","channel":9000}"#, - ); - let error = MachineImage::from_json(json.as_bytes()).unwrap_err(); - assert!( - error - .to_string() - .contains("must contain at least one supported access method") - ); - } - - #[test] - fn parses_qga_access() { - let json = String::from_utf8(valid_json()).unwrap().replace( - r#"[{"type":"ssh","port":22,"user":"build","auth":"empty-password"}]"#, - r#"[{"type":"ssh","port":22,"user":"build","auth":"empty-password"},{"type":"qga"}]"#, - ); - let image = MachineImage::from_json(json.as_bytes()).unwrap(); - assert_eq!(image.machine.access.len(), 2); - assert!(matches!(image.machine.access[1], Access::Qga { .. })); - } - - #[test] - fn access_may_be_omitted_for_a_black_box_image() { - let json = String::from_utf8(valid_json()).unwrap().replace( - r#","access":[{"type":"ssh","port":22,"user":"build","auth":"empty-password"}]"#, - "", - ); - let image = MachineImage::from_json(json.as_bytes()).unwrap(); - assert!(image.machine.access.is_empty()); - assert!( - serde_json::to_value(image).unwrap()["machine"] - .get("access") - .is_none() - ); - } - - #[test] - fn parses_dhcp_network_without_static_parameters() { - let json = String::from_utf8(valid_json()).unwrap().replace( - r#"{"mode":"static","address":"10.0.2.15/24","gateway":"10.0.2.2"}"#, - r#"{"mode":"dhcp"}"#, - ); - let image = MachineImage::from_json(json.as_bytes()).unwrap(); - assert!(matches!(image.machine.network, Network::Dhcp(_))); - } - - #[test] - fn rejects_unknown_schema_before_parsing_schema_fields() { - let error = MachineImage::from_json(br#"{"schemaVersion":2}"#).unwrap_err(); - let ParseError::Validation(error) = error else { - panic!("expected validation error") - }; - assert_eq!(error.issues(), ["unsupported schemaVersion 2"]); - } - - #[test] - fn rejects_unknown_kind_before_parsing_kind_fields() { - let error = MachineImage::from_json(br#"{"schemaVersion":1,"kind":"Other"}"#).unwrap_err(); - let ParseError::Validation(error) = error else { - panic!("expected validation error") - }; - assert_eq!(error.issues(), ["kind must be 'MachineImage'"]); - } - - #[test] - fn rejects_unknown_architecture() { - let json = String::from_utf8(valid_json()) - .unwrap() - .replace("\"architecture\":\"amd64\"", "\"architecture\":\"mips\""); - let error = MachineImage::from_json(json.as_bytes()).unwrap_err(); - assert!(error.to_string().contains("unknown variant `mips`")); - } - - #[test] - fn parses_additional_oci_architectures() { - for architecture in ["loong64", "riscv64", "s390x"] { - let json = String::from_utf8(valid_json()).unwrap().replace( - "\"architecture\":\"amd64\"", - &format!("\"architecture\":\"{architecture}\""), - ); - MachineImage::from_json(json.as_bytes()).unwrap(); - } - } -} diff --git a/crates/hule-oci/Cargo.toml b/crates/hule-oci/Cargo.toml index 6b05ea5..071f9c5 100644 --- a/crates/hule-oci/Cargo.toml +++ b/crates/hule-oci/Cargo.toml @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 [package] @@ -13,9 +13,3 @@ authors.workspace = true repository.workspace = true [dependencies] -hule-hmi.workspace = true -serde_json.workspace = true -tokio = { workspace = true, features = ["fs", "io-util", "rt"] } -oci-client = "0.17" -zstd = "0.13" -sha2 = "0.10" diff --git a/crates/hule-oci/src/error.rs b/crates/hule-oci/src/error.rs deleted file mode 100644 --- a/crates/hule-oci/src/error.rs +++ /dev/null @@ -1,119 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -use oci_client::errors::OciDistributionError; -use std::fmt; -use std::path::PathBuf; - -#[derive(Debug)] -pub enum Error { - Io(std::io::Error), - Json(serde_json::Error), - InvalidImage(hule_hmi::ParseError), - InvalidReference { - reference: String, - source: oci_client::ParseError, - }, - Registry(OciDistributionError), - Task(tokio::task::JoinError), - InvalidImagePath(PathBuf), - MissingConfig(PathBuf), - ImageNotFound(String), - MissingManifest, - InvalidLayer(&'static str), - InvalidAnnotation { - name: &'static str, - value: String, - }, - EmptyImageFile(PathBuf), - InvalidStoragePath { - kind: &'static str, - value: String, - }, -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Io(error) => error.fmt(f), - Self::Json(error) => error.fmt(f), - Self::InvalidImage(error) => error.fmt(f), - Self::InvalidReference { reference, source } => { - write!(f, "invalid reference '{reference}': {source}") - } - Self::Registry(error) => error.fmt(f), - Self::Task(error) => write!(f, "background task failed: {error}"), - Self::InvalidImagePath(path) => { - write!(f, "{} has no file name", path.display()) - } - Self::MissingConfig(path) => { - write!(f, "{} does not contain config.json", path.display()) - } - Self::ImageNotFound(reference) => { - write!(f, "no local image tagged '{reference}'") - } - Self::MissingManifest => f.write_str("registry returned no image manifest"), - Self::InvalidLayer(reason) => write!(f, "invalid chunk layer: {reason}"), - Self::InvalidAnnotation { name, value } => { - write!(f, "invalid chunk {name} annotation '{value}'") - } - Self::EmptyImageFile(path) => write!(f, "{} is empty", path.display()), - Self::InvalidStoragePath { kind, value } => { - write!(f, "invalid {kind} '{value}'") - } - } - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io(error) => Some(error), - Self::Json(error) => Some(error), - Self::InvalidImage(error) => Some(error), - Self::InvalidReference { source, .. } => Some(source), - Self::Registry(error) => Some(error), - Self::Task(error) => Some(error), - Self::InvalidImagePath(_) - | Self::MissingConfig(_) - | Self::ImageNotFound(_) - | Self::MissingManifest - | Self::InvalidLayer(_) - | Self::InvalidAnnotation { .. } - | Self::EmptyImageFile(_) - | Self::InvalidStoragePath { .. } => None, - } - } -} - -impl From<std::io::Error> for Error { - fn from(error: std::io::Error) -> Self { - Self::Io(error) - } -} - -impl From<serde_json::Error> for Error { - fn from(error: serde_json::Error) -> Self { - Self::Json(error) - } -} - -impl From<hule_hmi::ParseError> for Error { - fn from(error: hule_hmi::ParseError) -> Self { - Self::InvalidImage(error) - } -} - -impl From<OciDistributionError> for Error { - fn from(error: OciDistributionError) -> Self { - Self::Registry(error) - } -} - -impl From<tokio::task::JoinError> for Error { - fn from(error: tokio::task::JoinError) -> Self { - Self::Task(error) - } -} - -pub type Result<T> = std::result::Result<T, Error>; diff --git a/crates/hule-oci/src/lib.rs b/crates/hule-oci/src/lib.rs index 819e05b..306f146 100644 --- a/crates/hule-oci/src/lib.rs +++ b/crates/hule-oci/src/lib.rs @@ -1,486 +1,4 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov +// SPDX-FileCopyrightText: 2026 Nikolay Govorov // SPDX-License-Identifier: Apache-2.0 -//! OCI image storage and registry operations for Hule machine images. - -mod error; -mod storage; - -use hule_hmi::MachineImage; -use oci_client::annotations::{ORG_OPENCONTAINERS_IMAGE_REF_NAME, ORG_OPENCONTAINERS_IMAGE_TITLE}; -use oci_client::client::{ClientConfig, ClientProtocol, Config, ImageLayer}; -use oci_client::manifest::{ - ImageIndexEntry, OCI_IMAGE_MEDIA_TYPE, OciDescriptor, OciImageIndex, OciImageManifest, -}; -use oci_client::secrets::RegistryAuth; -use oci_client::{Client, Reference}; -use std::collections::{BTreeMap, BTreeSet}; -use std::path::{Path, PathBuf}; -use tokio::fs::{self, File}; -use tokio::io::AsyncReadExt; -use tokio::task; - -pub use error::{Error, Result}; -pub use storage::Storage; - -type R<T> = Result<T>; - -// ---- local OCI-layout store ------------------------------------------- - -const CHUNK_SIZE: usize = 256 * 1024 * 1024; -const HULE_CHUNK_MEDIA_TYPE: &str = "application/vnd.hule.disk.chunk.v1"; -const HULE_CONFIG_MEDIA_TYPE: &str = "application/vnd.hule.machine.config.v1+json"; -const ANNOTATION_CHUNK_OFFSET: &str = "io.hule.chunk.offset"; -const ANNOTATION_CHUNK_LENGTH: &str = "io.hule.chunk.length"; - -fn index_lookup(index: &OciImageIndex, reference: &str) -> Option<String> { - index - .manifests - .iter() - .find(|m| { - m.annotations - .as_ref() - .and_then(|a| a.get(ORG_OPENCONTAINERS_IMAGE_REF_NAME)) - .map(String::as_str) - == Some(reference) - }) - .map(|m| m.digest.clone()) -} - -fn index_set(index: &mut OciImageIndex, reference: &str, digest: &str, size: u64) { - index.manifests.retain(|m| { - m.annotations - .as_ref() - .and_then(|a| a.get(ORG_OPENCONTAINERS_IMAGE_REF_NAME)) - .map(String::as_str) - != Some(reference) - }); - let mut annotations = BTreeMap::new(); - annotations.insert( - ORG_OPENCONTAINERS_IMAGE_REF_NAME.to_string(), - reference.to_string(), - ); - index.manifests.push(ImageIndexEntry { - media_type: OCI_IMAGE_MEDIA_TYPE.to_string(), - digest: digest.to_string(), - size: size as i64, - platform: None, - annotations: Some(annotations), - artifact_type: None, - }); -} - -/// Manages Hule images backed by a [`Storage`]. -#[derive(Clone, Debug)] -pub struct ImageManager { - storage: Storage, -} - -impl ImageManager { - pub fn new(storage: Storage) -> Self { - Self { storage } - } - - pub fn storage(&self) -> &Storage { - &self.storage - } - - /// Splits `path` into fixed-size chunks, compresses each independently - /// and writes each as its own blob. - async fn write_file_chunks(&self, path: &Path) -> R<Vec<OciDescriptor>> { - let title = path - .file_name() - .ok_or_else(|| Error::InvalidImagePath(path.to_path_buf()))? - .to_string_lossy() - .to_string(); - let mut file = File::open(path).await?; - let mut descriptors = Vec::new(); - let mut offset: u64 = 0; - loop { - let mut buf = Vec::with_capacity(CHUNK_SIZE); - (&mut file) - .take(CHUNK_SIZE as u64) - .read_to_end(&mut buf) - .await?; - if buf.is_empty() { - break; - } - let length = buf.len() as u64; - let compressed = - task::spawn_blocking(move || zstd::stream::encode_all(&buf[..], 0)).await??; - let compressed_len = compressed.len(); - let (digest, _) = self.storage.write_blob(compressed).await?; - - let mut annotations = BTreeMap::new(); - annotations.insert(ORG_OPENCONTAINERS_IMAGE_TITLE.to_string(), title.clone()); - annotations.insert(ANNOTATION_CHUNK_OFFSET.to_string(), offset.to_string()); - annotations.insert(ANNOTATION_CHUNK_LENGTH.to_string(), length.to_string()); - - descriptors.push(OciDescriptor { - media_type: HULE_CHUNK_MEDIA_TYPE.to_string(), - digest, - size: compressed_len as i64, - urls: None, - annotations: Some(annotations), - artifact_type: None, - }); - - offset += length; - if length < CHUNK_SIZE as u64 { - break; - } - } - if descriptors.is_empty() { - return Err(Error::EmptyImageFile(path.to_path_buf())); - } - Ok(descriptors) - } -} - -fn make_client(reference: &Reference) -> Client { - let registry = reference.resolve_registry(); - let host = registry.split(':').next().unwrap_or(registry); - let protocol = if host == "localhost" || host == "127.0.0.1" { - ClientProtocol::Http - } else { - ClientProtocol::Https - }; - Client::new(ClientConfig { - protocol, - ..Default::default() - }) -} - -fn parse_reference(s: &str) -> R<Reference> { - s.parse().map_err(|source| Error::InvalidReference { - reference: s.to_string(), - source, - }) -} - -// ---- image operations ------------------------------------------------- - -impl ImageManager { - /// Loads a prepared HMI image directory and optionally tags it. - pub async fn load(&self, path: &Path, reference: Option<&str>) -> R<String> { - let config_path = path.join("config.json"); - match fs::metadata(&config_path).await { - Ok(metadata) if metadata.is_file() => {} - Ok(_) => return Err(Error::MissingConfig(path.to_path_buf())), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - return Err(Error::MissingConfig(path.to_path_buf())); - } - Err(error) => return Err(error.into()), - } - let config_bytes = fs::read(&config_path).await?; - MachineImage::from_json(&config_bytes)?; - - let mut dir = fs::read_dir(path).await?; - let mut entries = Vec::new(); - while let Some(entry) = dir.next_entry().await? { - entries.push(entry); - } - entries.sort_by_key(|entry| entry.file_name()); - - let mut layers = Vec::new(); - let mut sources: Vec<(String, PathBuf)> = Vec::new(); - for entry in entries { - if !entry.file_type().await?.is_file() { - continue; - } - let name = entry.file_name().to_string_lossy().to_string(); - if name == "config.json" { - continue; - } - let file_path = entry.path(); - layers.extend(self.write_file_chunks(&file_path).await?); - sources.push((name, file_path)); - } - - let config_size = config_bytes.len(); - let (config_digest, _) = self.storage.write_blob(config_bytes).await?; - let config = OciDescriptor { - media_type: HULE_CONFIG_MEDIA_TYPE.to_string(), - digest: config_digest, - size: config_size as i64, - urls: None, - annotations: None, - artifact_type: None, - }; - - let manifest = OciImageManifest { - schema_version: 2, - media_type: Some(OCI_IMAGE_MEDIA_TYPE.to_string()), - config, - layers, - subject: None, - artifact_type: None, - annotations: None, - }; - let manifest_bytes = serde_json::to_vec(&manifest)?; - let manifest_size = manifest_bytes.len(); - let (manifest_digest, _) = self.storage.write_blob(manifest_bytes).await?; - - self.storage.ensure_hmi_image(&manifest_digest).await?; - for (title, source) in &sources { - self.storage - .cache_hmi_file(&manifest_digest, title, source) - .await?; - } - - if let Some(reference) = reference { - let mut index = self.storage.read_index().await?; - index_set( - &mut index, - reference, - &manifest_digest, - manifest_size as u64, - ); - self.storage.write_index(&index).await?; - } - Ok(manifest_digest) - } - - /// Pushes a locally tagged image to its registry reference. - pub async fn push(&self, reference_str: &str) -> R<()> { - let index = self.storage.read_index().await?; - let manifest_digest = index_lookup(&index, reference_str) - .ok_or_else(|| Error::ImageNotFound(reference_str.to_string()))?; - let manifest_bytes = self.storage.read_blob(&manifest_digest).await?; - let manifest: OciImageManifest = serde_json::from_slice(&manifest_bytes)?; - - let reference = parse_reference(reference_str)?; - let client = make_client(&reference); - let auth = RegistryAuth::Anonymous; - - let mut layers = Vec::new(); - for descriptor in &manifest.layers { - let data = self.storage.read_blob(&descriptor.digest).await?; - layers.push(ImageLayer::new( - data, - descriptor.media_type.clone(), - descriptor.annotations.clone(), - )); - } - let config_bytes = self.storage.read_blob(&manifest.config.digest).await?; - let config = Config::new( - config_bytes, - manifest.config.media_type.clone(), - manifest.config.annotations.clone(), - ); - - client - .push(&reference, &layers, config, &auth, Some(manifest)) - .await?; - - Ok(()) - } - - /// Pulls an image into the OCI layout and materializes it in the HMI store. - pub async fn pull(&self, reference_str: &str) -> R<String> { - let reference = parse_reference(reference_str)?; - let client = make_client(&reference); - let auth = RegistryAuth::Anonymous; - - let mut image_data = client - .pull(&reference, &auth, vec![HULE_CHUNK_MEDIA_TYPE]) - .await?; - let manifest = image_data.manifest.ok_or(Error::MissingManifest)?; - - // `client.pull()` fetches layers via `buffer_unordered`, so `image_data.layers` is - // in completion order, not manifest order. Each layer carries its own annotations. - for layer in &mut image_data.layers { - let data = std::mem::take(&mut layer.data); - let (_, data) = self.storage.write_blob(data).await?; - layer.data = data; - } - let config_data = std::mem::take(&mut image_data.config.data); - let (_, config_data) = self.storage.write_blob(config_data).await?; - image_data.config.data = config_data; - - let manifest_bytes = serde_json::to_vec(&manifest)?; - let manifest_size = manifest_bytes.len(); - let (manifest_digest, _) = self.storage.write_blob(manifest_bytes).await?; - self.storage.ensure_hmi_image(&manifest_digest).await?; - - let mut by_title: BTreeMap<String, Vec<(u64, ImageLayer)>> = BTreeMap::new(); - for layer in image_data.layers { - let annotations = layer - .annotations - .as_ref() - .ok_or(Error::InvalidLayer("missing annotations"))?; - let title = annotations - .get(ORG_OPENCONTAINERS_IMAGE_TITLE) - .ok_or(Error::InvalidLayer("missing title annotation"))?; - let offset_value = annotations - .get(ANNOTATION_CHUNK_OFFSET) - .ok_or(Error::InvalidLayer("missing offset annotation"))?; - let offset: u64 = offset_value.parse().map_err(|_| Error::InvalidAnnotation { - name: "offset", - value: offset_value.clone(), - })?; - by_title - .entry(title.clone()) - .or_default() - .push((offset, layer)); - } - - for (title, chunks) in by_title { - let mut decompressed_chunks = Vec::with_capacity(chunks.len()); - for (offset, layer) in chunks { - let data = task::spawn_blocking(move || zstd::stream::decode_all(&layer.data[..])) - .await??; - decompressed_chunks.push((offset, data)); - } - self.storage - .write_hmi_file(&manifest_digest, &title, decompressed_chunks) - .await?; - } - - let mut index = self.storage.read_index().await?; - index_set( - &mut index, - reference_str, - &manifest_digest, - manifest_size as u64, - ); - self.storage.write_index(&index).await?; - - Ok(manifest_digest) - } - - /// Returns whether a reference is present in the local OCI layout. - pub async fn contains(&self, reference_str: &str) -> R<bool> { - Ok(index_lookup(&self.storage.read_index().await?, reference_str).is_some()) - } - - /// Materializes a locally tagged image into `destination` and returns config.json. - pub async fn materialize(&self, reference_str: &str, destination: &Path) -> R<Vec<u8>> { - let manifest_digest = index_lookup(&self.storage.read_index().await?, reference_str) - .ok_or_else(|| Error::ImageNotFound(reference_str.to_string()))?; - - let manifest_bytes = self.storage.read_blob(&manifest_digest).await?; - let manifest: OciImageManifest = serde_json::from_slice(&manifest_bytes)?; - let config_bytes = self.storage.read_blob(&manifest.config.digest).await?; - - fs::create_dir_all(destination).await?; - fs::write(destination.join("config.json"), &config_bytes).await?; - - let mut titles: BTreeSet<String> = BTreeSet::new(); - for descriptor in &manifest.layers { - if let Some(title) = descriptor - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ORG_OPENCONTAINERS_IMAGE_TITLE)) - { - titles.insert(title.clone()); - } - } - for title in titles { - self.storage - .export_hmi_file(&manifest_digest, &title, &destination.join(&title)) - .await?; - } - - Ok(config_bytes) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicU64, Ordering}; - - const TEST_CONFIG: &[u8] = br#"{ - "schemaVersion": 1, - "kind": "MachineImage", - "system": { - "os": "linux", - "name": "test", - "version": "1", - "architecture": "amd64" - }, - "machine": { - "cpu": { "minimum": 1, "default": 1 }, - "ram": { "minimum": 268435456, "default": 268435456 }, - "boot": [{ "protocol": "firmware-disk/bios", "disk": "root" }], - "access": [{ - "type": "ssh", - "port": 22, - "user": "root", - "auth": "empty-password" - }], - "network": { "mode": "dhcp" } - }, - "disks": [{ - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:372409142c91c51316a7ab2b055596e145de56d99aa0f5eb110068876cef0be4", - "virtSize": 14, - "diskSize": 14 - }] - }"#; - - fn temporary_directory() -> PathBuf { - static NEXT_ID: AtomicU64 = AtomicU64::new(0); - std::env::temp_dir().join(format!( - "hule-oci-test-{}-{}", - std::process::id(), - NEXT_ID.fetch_add(1, Ordering::Relaxed) - )) - } - - #[test] - fn manager_uses_separate_oci_and_hmi_roots() { - tokio::runtime::Builder::new_current_thread() - .build() - .unwrap() - .block_on(async { - let root = temporary_directory(); - let source = root.join("source"); - let oci_root = root.join("oci"); - let hmi_root = root.join("hmi"); - let destination = root.join("destination"); - fs::create_dir_all(&source).await.unwrap(); - fs::write(source.join("config.json"), TEST_CONFIG) - .await - .unwrap(); - fs::write(source.join("root.hmi"), b"test hmi image") - .await - .unwrap(); - - let storage = Storage::open(&oci_root, &hmi_root).await.unwrap(); - let images = ImageManager::new(storage); - let reference = "example.test/hule:tokio"; - let digest = images.load(&source, Some(reference)).await.unwrap(); - - assert!(images.contains(reference).await.unwrap()); - assert!(fs::try_exists(oci_root.join("index.json")).await.unwrap()); - assert!( - fs::try_exists( - hmi_root - .join(digest.strip_prefix("sha256:").unwrap_or(&digest)) - .join("root.hmi") - ) - .await - .unwrap() - ); - - let config = images.materialize(reference, &destination).await.unwrap(); - assert!(!config.is_empty()); - assert_eq!( - fs::read(destination.join("root.hmi")).await.unwrap(), - b"test hmi image" - ); - - assert!(matches!(images.contains("missing").await, Ok(false))); - assert!(matches!( - images.materialize("missing", &destination).await, - Err(Error::ImageNotFound(reference)) if reference == "missing" - )); - - fs::remove_dir_all(root).await.unwrap(); - }); - } -} +pub const NAME: &str = "I'm a oci library"; diff --git a/crates/hule-oci/src/storage.rs b/crates/hule-oci/src/storage.rs deleted file mode 100644 --- a/crates/hule-oci/src/storage.rs +++ /dev/null @@ -1,213 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -use crate::{Error, Result}; -use oci_client::manifest::OciImageIndex; -use std::io::SeekFrom; -use std::path::{Component, Path, PathBuf}; -use tokio::fs::{self, File}; -use tokio::io::{AsyncSeekExt, AsyncWriteExt}; -use tokio::task; - -/// Filesystem storage for OCI content and materialized HMI images. -/// -/// The roots are independent so callers can place content-addressed OCI data -/// and large materialized disks on different filesystems. -#[derive(Clone, Debug)] -pub struct Storage { - oci_root: PathBuf, - hmi_root: PathBuf, -} - -impl Storage { - /// Opens the storage and creates its filesystem layout when necessary. - pub async fn open(oci_root: impl Into<PathBuf>, hmi_root: impl Into<PathBuf>) -> Result<Self> { - let storage = Self { - oci_root: oci_root.into(), - hmi_root: hmi_root.into(), - }; - - fs::create_dir_all(&storage.hmi_root).await?; - fs::create_dir_all(storage.blobs_dir()).await?; - - let layout = storage.oci_root.join("oci-layout"); - if !fs::try_exists(&layout).await? { - fs::write(&layout, br#"{"imageLayoutVersion":"1.0.0"}"#).await?; - } - - Ok(storage) - } - - pub fn oci_root(&self) -> &Path { - &self.oci_root - } - - pub fn hmi_root(&self) -> &Path { - &self.hmi_root - } - - fn blobs_dir(&self) -> PathBuf { - self.oci_root.join("blobs").join("sha256") - } - - fn index_path(&self) -> PathBuf { - self.oci_root.join("index.json") - } - - fn hmi_image_dir(&self, manifest_digest: &str) -> Result<PathBuf> { - let digest = safe_component(strip_sha256(manifest_digest), "manifest digest")?; - Ok(self.hmi_root.join(digest)) - } - - fn hmi_file_path(&self, manifest_digest: &str, title: &str) -> Result<PathBuf> { - let title = safe_component(title, "image file name")?; - Ok(self.hmi_image_dir(manifest_digest)?.join(title)) - } - - fn blob_path(&self, digest: &str) -> Result<PathBuf> { - let digest = safe_component(strip_sha256(digest), "blob digest")?; - Ok(self.blobs_dir().join(digest)) - } - - pub(crate) async fn read_blob(&self, digest: &str) -> Result<Vec<u8>> { - Ok(fs::read(self.blob_path(digest)?).await?) - } - - /// Writes raw bytes as a content-addressed blob, no-op if already present. - pub(crate) async fn write_blob<T>(&self, data: T) -> Result<(String, T)> - where - T: AsRef<[u8]> + Send + Sync + 'static, - { - let (digest, data) = - task::spawn_blocking(move || (sha256_hex(data.as_ref()), data)).await?; - let path = self.blob_path(&digest)?; - if !fs::try_exists(&path).await? { - let tmp = path.with_extension("tmp"); - fs::write(&tmp, data.as_ref()).await?; - fs::rename(&tmp, &path).await?; - } - Ok((digest, data)) - } - - pub(crate) async fn read_index(&self) -> Result<OciImageIndex> { - let path = self.index_path(); - if !fs::try_exists(&path).await? { - return Ok(OciImageIndex { - schema_version: 2, - media_type: None, - manifests: vec![], - artifact_type: None, - annotations: None, - }); - } - let data = fs::read(&path).await?; - Ok(serde_json::from_slice(&data)?) - } - - pub(crate) async fn write_index(&self, index: &OciImageIndex) -> Result<()> { - let data = serde_json::to_vec_pretty(index)?; - fs::write(self.index_path(), data).await?; - Ok(()) - } - - pub(crate) async fn ensure_hmi_image(&self, manifest_digest: &str) -> Result<()> { - fs::create_dir_all(self.hmi_image_dir(manifest_digest)?).await?; - Ok(()) - } - - pub(crate) async fn cache_hmi_file( - &self, - manifest_digest: &str, - title: &str, - source: &Path, - ) -> Result<()> { - let destination = self.hmi_file_path(manifest_digest, title)?; - if !fs::try_exists(&destination).await? { - Self::hardlink_or_copy(source, &destination).await?; - } - Ok(()) - } - - pub(crate) async fn write_hmi_file( - &self, - manifest_digest: &str, - title: &str, - mut chunks: Vec<(u64, Vec<u8>)>, - ) -> Result<()> { - chunks.sort_by_key(|(offset, _)| *offset); - let mut file = File::create(self.hmi_file_path(manifest_digest, title)?).await?; - for (offset, data) in chunks { - file.seek(SeekFrom::Start(offset)).await?; - file.write_all(&data).await?; - } - file.flush().await?; - Ok(()) - } - - pub(crate) async fn export_hmi_file( - &self, - manifest_digest: &str, - title: &str, - destination: &Path, - ) -> Result<()> { - let source = self.hmi_file_path(manifest_digest, title)?; - if !fs::try_exists(destination).await? { - Self::hardlink_or_copy(&source, destination).await?; - } - Ok(()) - } - - async fn hardlink_or_copy(source: &Path, destination: &Path) -> Result<()> { - if fs::hard_link(source, destination).await.is_err() { - fs::copy(source, destination).await?; - } - Ok(()) - } -} - -fn safe_component<'a>(value: &'a str, kind: &'static str) -> Result<&'a str> { - let mut components = Path::new(value).components(); - match (components.next(), components.next()) { - (Some(Component::Normal(_)), None) => Ok(value), - _ => Err(Error::InvalidStoragePath { - kind, - value: value.to_string(), - }), - } -} - -fn strip_sha256(digest: &str) -> &str { - digest.strip_prefix("sha256:").unwrap_or(digest) -} - -fn sha256_hex(data: &[u8]) -> String { - use sha2::{Digest, Sha256}; - let mut hasher = Sha256::new(); - hasher.update(data); - format!("sha256:{:x}", hasher.finalize()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn paths_cannot_escape_storage_roots() { - let storage = Storage { - oci_root: "oci".into(), - hmi_root: "hmi".into(), - }; - assert!(matches!( - storage.blob_path("sha256:../../outside"), - Err(Error::InvalidStoragePath { .. }) - )); - assert!(matches!( - storage.hmi_image_dir("sha256:../outside"), - Err(Error::InvalidStoragePath { .. }) - )); - assert!(matches!( - storage.hmi_file_path("sha256:digest", "../outside"), - Err(Error::InvalidStoragePath { .. }) - )); - } -} diff --git a/crates/hule-vmm/Cargo.toml b/crates/hule-vmm/Cargo.toml index 50170c9..42c8561 100644 --- a/crates/hule-vmm/Cargo.toml +++ b/crates/hule-vmm/Cargo.toml @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 [package] @@ -13,13 +13,3 @@ authors.workspace = true repository.workspace = true [dependencies] -hule-hmi.workspace = true -uuid = { version = "1", features = ["v7"] } -tokio = { workspace = true, features = ["process", "fs", "io-util", "sync", "net", "time"] } -async-trait = "0.1" -serde.workspace = true -serde_json.workspace = true -base64 = "0.22" - -[dev-dependencies] -tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } diff --git a/crates/hule-vmm/src/backend/mod.rs b/crates/hule-vmm/src/backend/mod.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/mod.rs +++ /dev/null @@ -1,4 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -pub mod qemu; diff --git a/crates/hule-vmm/src/backend/qemu/cli.rs b/crates/hule-vmm/src/backend/qemu/cli.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/qemu/cli.rs +++ /dev/null @@ -1,388 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! Typed wrapper over the `qemu-system-*` command line. One qemu concept -//! per type/field; knows nothing about Hule's image/machine model. - -use std::path::PathBuf; - -/// One of the architectures qemu ships a `qemu-system-*` binary for. -/// Distinct from `hule_hmi::Architecture`: this is qemu's own set of -/// per-arch conventions (binary name, machine type, TCG cpu model), not -/// Hule's. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Arch { - Amd64, - Arm64, - Loong64, - Ppc64le, - Riscv64, - S390x, -} - -impl Arch { - /// The `qemu-system-*` binary for this target. - pub fn binary(&self) -> String { - let suffix = match self { - Self::Amd64 => "x86_64", - Self::Arm64 => "aarch64", - Self::Loong64 => "loongarch64", - Self::Ppc64le => "ppc64le", - Self::Riscv64 => "riscv64", - Self::S390x => "s390x", - }; - format!("qemu-system-{suffix}") - } - - /// `-machine`/`-M` value this arch needs, if any (the default machine - /// type is fine for the others). - pub fn machine_type(&self) -> Option<&'static str> { - match self { - Self::Arm64 | Self::Riscv64 => Some("virt"), - Self::Ppc64le => Some("pseries"), - _ => None, - } - } - - /// `-cpu` model to emulate when KVM isn't usable. - pub fn tcg_cpu_model(&self) -> &'static str { - match self { - Self::Amd64 => "qemu64", - Self::Arm64 => "cortex-a53", - Self::Loong64 => "la464", - Self::Ppc64le => "power9", - Self::Riscv64 => "rv64", - Self::S390x => "max", - } - } -} - -pub enum Accel { - Tcg, - Kvm, -} - -pub enum NetBackend { - Nic { model: String }, - User { hostfwd: Vec<(u16, u16)> }, -} - -impl NetBackend { - fn to_arg(&self) -> String { - match self { - Self::Nic { model } => format!("nic,model={model}"), - Self::User { hostfwd } => { - let mut s = String::from("user"); - for (host, guest) in hostfwd { - s.push_str(&format!(",hostfwd=tcp:127.0.0.1:{host}-:{guest}")); - } - s - } - } - } -} - -pub enum DriveInterface { - /// `if=virtio`: the disk is a bootable device in its own right. - Virtio, - /// `if=none,id=<id>`: unattached, paired with a `Device::VirtioBlkPci`. - None { id: String }, -} - -pub struct Drive { - pub file: PathBuf, - /// `snapshot=on`: writes go to a throwaway overlay, never to `file`. - pub snapshot: bool, - pub interface: DriveInterface, -} - -impl Drive { - fn to_arg(&self) -> String { - let mut s = format!("file={},media=disk", self.file.display()); - if self.snapshot { - s.push_str(",snapshot=on"); - } - match &self.interface { - DriveInterface::Virtio => s.push_str(",if=virtio"), - DriveInterface::None { id } => s.push_str(&format!(",id={id},if=none")), - } - s - } -} - -pub enum Device { - VirtioBlkPci { drive: String }, - VirtioRngPci, - VirtioBalloon, - VirtioSerialPci, - VirtSerialPort { chardev: String, name: String }, -} - -impl Device { - fn to_arg(&self) -> String { - match self { - Self::VirtioBlkPci { drive } => format!("virtio-blk-pci,drive={drive}"), - Self::VirtioRngPci => "virtio-rng-pci".into(), - Self::VirtioBalloon => "virtio-balloon".into(), - Self::VirtioSerialPci => "virtio-serial-pci".into(), - Self::VirtSerialPort { chardev, name } => { - format!("virtserialport,chardev={chardev},name={name}") - } - } - } -} - -/// One `qemu-system-*` invocation. `to_argv()` is pure -- no process/IO -- -/// so it's testable without spawning anything. -#[derive(Default)] -pub struct Command { - pub binary: String, - /// `-machine`/`-M`; qemu treats them as synonyms, so only one field. - pub machine: Option<String>, - pub cpu: Option<String>, - pub accel: Option<Accel>, - pub memory_mib: u64, - pub smp: u32, - pub display_none: bool, - pub nets: Vec<NetBackend>, - pub drives: Vec<Drive>, - pub devices: Vec<Device>, - pub kernel: Option<PathBuf>, - pub initrd: Option<PathBuf>, - pub append: Option<String>, - /// `-pidfile`: qemu writes its own pid here. The only reliable way to - /// signal/check it later from a process that isn't its parent. - pub pidfile: Option<PathBuf>, - /// `-qmp tcp:127.0.0.1:<port>,server=on,wait=off`: the control channel. - /// TCP loopback, not a unix socket -- the latter doesn't exist on - /// Windows at all (`tokio::net::UnixStream` is unix-only), and this way - /// there's nothing to `#[cfg]` on the transport. - pub qmp_port: Option<u16>, - /// Host side of the qemu-guest-agent virtio-serial channel. - pub qga_port: Option<u16>, - /// Interactive guest serial console and its persistent output log. - pub console: Option<(u16, PathBuf)>, -} - -impl Command { - pub fn to_argv(&self) -> Vec<String> { - let mut argv = vec![self.binary.clone()]; - if let Some(machine) = &self.machine { - argv.extend(["-machine".into(), machine.clone()]); - } - if let Some(cpu) = &self.cpu { - argv.extend(["-cpu".into(), cpu.clone()]); - } - if matches!(self.accel, Some(Accel::Kvm)) { - argv.push("-enable-kvm".into()); - } - argv.extend(["-m".into(), self.memory_mib.to_string()]); - argv.extend(["-smp".into(), format!("cpus={}", self.smp)]); - for net in &self.nets { - argv.extend(["-net".into(), net.to_arg()]); - } - for drive in &self.drives { - argv.extend(["-drive".into(), drive.to_arg()]); - } - for device in &self.devices { - argv.extend(["-device".into(), device.to_arg()]); - } - if self.display_none { - argv.extend(["-display".into(), "none".into()]); - } - if let Some(kernel) = &self.kernel { - argv.extend(["-kernel".into(), kernel.display().to_string()]); - } - if let Some(initrd) = &self.initrd { - argv.extend(["-initrd".into(), initrd.display().to_string()]); - } - if let Some(append) = &self.append { - argv.extend(["-append".into(), append.clone()]); - } - if let Some(pidfile) = &self.pidfile { - argv.extend(["-pidfile".into(), pidfile.display().to_string()]); - } - if let Some(port) = self.qmp_port { - argv.extend([ - "-qmp".into(), - format!("tcp:127.0.0.1:{port},server=on,wait=off"), - ]); - } - if let Some(port) = self.qga_port { - argv.extend([ - "-chardev".into(), - format!("socket,id=qga0,host=127.0.0.1,port={port},server=on,wait=off"), - "-device".into(), - Device::VirtioSerialPci.to_arg(), - "-device".into(), - Device::VirtSerialPort { - chardev: "qga0".into(), - name: "org.qemu.guest_agent.0".into(), - } - .to_arg(), - ]); - } - if let Some((port, logfile)) = &self.console { - argv.extend([ - "-chardev".into(), - format!( - "socket,id=console0,host=127.0.0.1,port={port},server=on,wait=off,logfile={},logappend=off", - logfile.display() - ), - "-serial".into(), - "chardev:console0".into(), - ]); - } - argv - } -} - -/// Whether `/dev/kvm` is actually usable, not just present -- the node can -/// exist but be unopenable (e.g. group `kvm` without membership), which -/// qemu only reports once it's already mid-boot. -pub async fn kvm_available() -> bool { - tokio::fs::OpenOptions::new() - .read(true) - .write(true) - .open("/dev/kvm") - .await - .is_ok() -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn renders_flags_in_a_stable_order() { - let cmd = Command { - binary: "qemu-system-x86_64".into(), - cpu: Some("qemu64".into()), - memory_mib: 1024, - smp: 2, - display_none: true, - nets: vec![ - NetBackend::Nic { - model: "virtio".into(), - }, - NetBackend::User { - hostfwd: vec![(8022, 22)], - }, - ], - drives: vec![Drive { - file: "root.hmi".into(), - snapshot: true, - interface: DriveInterface::Virtio, - }], - devices: vec![Device::VirtioRngPci], - ..Default::default() - }; - assert_eq!( - cmd.to_argv(), - vec![ - "qemu-system-x86_64", - "-cpu", - "qemu64", - "-m", - "1024", - "-smp", - "cpus=2", - "-net", - "nic,model=virtio", - "-net", - "user,hostfwd=tcp:127.0.0.1:8022-:22", - "-drive", - "file=root.hmi,media=disk,snapshot=on,if=virtio", - "-device", - "virtio-rng-pci", - "-display", - "none", - ] - ); - } - - #[test] - fn kvm_accel_adds_enable_kvm_flag() { - let cmd = Command { - binary: "qemu-system-x86_64".into(), - cpu: Some("host".into()), - accel: Some(Accel::Kvm), - ..Default::default() - }; - assert!(cmd.to_argv().contains(&"-enable-kvm".to_string())); - } - - #[test] - fn detached_drive_pairs_with_a_virtio_blk_device() { - let cmd = Command { - binary: "qemu-system-x86_64".into(), - drives: vec![Drive { - file: "root.hmi".into(), - snapshot: true, - interface: DriveInterface::None { id: "root".into() }, - }], - devices: vec![Device::VirtioBlkPci { - drive: "root".into(), - }], - kernel: Some("vmlinuz".into()), - initrd: Some("initrd.img".into()), - append: Some("console=ttyS0".into()), - ..Default::default() - }; - let argv = cmd.to_argv(); - assert!(argv.windows(2).any(|w| w == ["-kernel", "vmlinuz"])); - assert!(argv.windows(2).any(|w| w == ["-initrd", "initrd.img"])); - assert!(argv.windows(2).any(|w| w == ["-append", "console=ttyS0"])); - assert!(argv.windows(2).any(|w| w - == [ - "-drive", - "file=root.hmi,media=disk,snapshot=on,id=root,if=none" - ])); - assert!( - argv.windows(2) - .any(|w| w == ["-device", "virtio-blk-pci,drive=root"]) - ); - } - - #[test] - fn qga_uses_a_dedicated_virtio_serial_channel() { - let argv = Command { - binary: "qemu-system-x86_64".into(), - qga_port: Some(1234), - ..Default::default() - } - .to_argv(); - assert!(argv.windows(2).any(|w| { - w == [ - "-chardev", - "socket,id=qga0,host=127.0.0.1,port=1234,server=on,wait=off", - ] - })); - assert!(argv.windows(2).any(|w| { - w == [ - "-device", - "virtserialport,chardev=qga0,name=org.qemu.guest_agent.0", - ] - })); - } - - #[test] - fn serial_console_has_an_attach_socket_and_log() { - let argv = Command { - binary: "qemu-system-x86_64".into(), - console: Some((4321, "console.log".into())), - ..Default::default() - } - .to_argv(); - assert!(argv.windows(2).any(|w| { - w == [ - "-chardev", - "socket,id=console0,host=127.0.0.1,port=4321,server=on,wait=off,logfile=console.log,logappend=off", - ] - })); - assert!( - argv.windows(2) - .any(|w| w == ["-serial", "chardev:console0"]) - ); - } -} diff --git a/crates/hule-vmm/src/backend/qemu/mod.rs b/crates/hule-vmm/src/backend/qemu/mod.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/qemu/mod.rs +++ /dev/null @@ -1,563 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! QMP is an unconditional implementation detail of this backend. Guest -//! access is independent: an image may be a black box, or may promise QGA; -//! a promised QGA channel must become ready for `start()` to succeed. -//! -//! `logs`/`attach` use a dedicated serial console; `exec` uses QGA. -//! Console resizing and `reattach` are not implemented yet. -//! -//! `cli` is the typed qemu CLI wrapper; `supervise` gets an exit code out of -//! a process even if we stop being its parent; this module only translates -//! Hule's image/machine types into both. - -mod cli; -mod qga; -mod qmp; -mod supervise; - -use std::path::{Path, PathBuf}; -use std::process::{ExitStatus, Output}; -use std::time::Duration; - -use async_trait::async_trait; -use hule_hmi::{Access, Architecture, Boot, BootLinux, Disk, MachineImage}; -use tokio::process::Child; -use tokio::sync::Mutex; - -use crate::{ - Console, Error, Hypervisor, HypervisorId, Machine, MachineId, R, Settings, State, Stats, -}; - -const QEMU_HYPERVISOR_ID: HypervisorId = HypervisorId(1); - -enum QemuBoot { - // No BootBios fields are needed here: `disk` is already resolved into - // `QemuMachine::disk`, and `protocol` isn't used past `supports()`. - Bios, - Linux(BootLinux), -} - -/// The wrapper (`sh`) process, not qemu itself -- once qemu has a pid on -/// disk (see `QemuMachine::pid_path`), that's the source of truth for -/// liveness/signaling, not this. -enum ChildState { - NotStarted, - Running(Child), - Exited(ExitStatus), -} - -pub struct QemuMachine { - id: MachineId, - name: Option<String>, - dir: PathBuf, - arch: Architecture, - settings: Settings, - disk: Disk, - boot: QemuBoot, - qga: bool, - child: Mutex<ChildState>, - qga_lock: Mutex<()>, - qmp_client: Mutex<Option<qmp::Qmp>>, -} - -impl QemuMachine { - /// Where qemu's own `-pidfile` lands. Provisional: once a persisted - /// `run/<id>/` directory exists (separate from `dir`, the materialized - /// image files), this moves there instead of living inside `dir`. - fn pid_path(&self) -> PathBuf { - self.dir.join("qemu.pid") - } - - fn exit_code_path(&self) -> PathBuf { - self.dir.join("qemu.exit-code") - } - - /// Where the port `start()` picked for `-qmp tcp:127.0.0.1:<port>` is - /// recorded -- chosen by us, not qemu, so (unlike `pid_path`) nothing - /// needs to wait for this file; it exists before qemu is spawned. - fn qmp_port_path(&self) -> PathBuf { - self.dir.join("qemu.qmp-port") - } - - fn qga_port_path(&self) -> PathBuf { - self.dir.join("qemu.qga-port") - } - - fn console_port_path(&self) -> PathBuf { - self.dir.join("qemu.console-port") - } - - fn console_log_path(&self) -> PathBuf { - self.dir.join("console.log") - } - - async fn read_port(&self, path: &Path, name: &str) -> R<u16> { - let data = tokio::fs::read_to_string(path).await?; - data.trim() - .parse() - .map_err(|_| Error::InvalidState(format!("invalid {name} port contents"))) - } - - async fn qmp_port(&self) -> R<u16> { - self.read_port(&self.qmp_port_path(), "qmp").await - } - - async fn qga_port(&self) -> R<u16> { - self.read_port(&self.qga_port_path(), "qga").await - } - - async fn console_port(&self) -> R<u16> { - self.read_port(&self.console_port_path(), "console").await - } - - /// Connects on first use (there's a short window after spawn before - /// qemu's TCP listener is actually up, so a couple of retries) and - /// reuses the connection after that. - async fn qmp_client(&self) -> R<tokio::sync::MutexGuard<'_, Option<qmp::Qmp>>> { - let mut client = self.qmp_client.lock().await; - if client.is_none() { - let port = self.qmp_port().await?; - let mut connected = None; - for _ in 0..50 { - match qmp::Qmp::connect(port).await { - Ok(qmp) => { - connected = Some(qmp); - break; - } - Err(_) => tokio::time::sleep(Duration::from_millis(20)).await, - } - } - *client = Some( - connected - .ok_or_else(|| Error::InvalidState("qemu's qmp port never came up".into()))?, - ); - } - Ok(client) - } - - /// Reads qemu's pid, waiting briefly for `-pidfile` to actually appear - /// (there's a short window between spawn and qemu writing it). - async fn qemu_pid(&self) -> R<supervise::Pid> { - for _ in 0..50 { - if let Ok(data) = tokio::fs::read_to_string(self.pid_path()).await - && let Ok(pid) = data.trim().parse() - { - return Ok(supervise::Pid(pid)); - } - tokio::time::sleep(Duration::from_millis(20)).await; - } - Err(Error::InvalidState( - "qemu did not write its pidfile in time".into(), - )) - } - - async fn read_exit_code(&self) -> Option<ExitStatus> { - let data = tokio::fs::read_to_string(self.exit_code_path()) - .await - .ok()?; - let code: i32 = data.trim().parse().ok()?; - #[cfg(unix)] - { - use std::os::unix::process::ExitStatusExt; - // `$?` is already qemu's plain exit code; shift it into the - // wait()-status shape ExitStatus expects (bits 8-15 == exit - // code, low byte 0 == not signaled). Loses signal detail, but - // `.code()` -- all we ever read -- comes back right. - Some(ExitStatus::from_raw(code << 8)) - } - #[cfg(not(unix))] - { - None - } - } -} - -#[async_trait] -impl Machine for QemuMachine { - fn id(&self) -> MachineId { - self.id - } - - fn hid(&self) -> HypervisorId { - QEMU_HYPERVISOR_ID - } - - fn name(&self) -> Option<&str> { - self.name.as_deref() - } - - fn settings(&self) -> Settings { - self.settings.clone() - } - - async fn state(&self) -> State { - if let Some(status) = self.read_exit_code().await { - return State::Exited(status.code().unwrap_or(-1)); - } - let pid = match self.qemu_pid().await { - Ok(pid) => pid, - Err(_) => { - return match &*self.child.lock().await { - ChildState::NotStarted => State::Created, - ChildState::Exited(status) => State::Exited(status.code().unwrap_or(-1)), - ChildState::Running(_) => State::Running, - }; - } - }; - if !supervise::pid_alive(pid).await { - return State::Dead; - } - // A live pid alone can't distinguish running from paused; ask QMP. - if let Ok(mut client) = self.qmp_client().await - && let Ok(qmp::Status::Paused) = client - .as_mut() - .expect("initialized by qmp_client") - .status() - .await - { - return State::Paused; - } - State::Running - } - - async fn stats(&self) -> R<Stats> { - let pid = self.qemu_pid().await?; - let (cpu_time_ns, memory_bytes) = supervise::process_stats(pid).await?; - Ok(Stats { - cpu_time_ns, - memory_bytes, - }) - } - - async fn logs(&self) -> R<Vec<u8>> { - match tokio::fs::read(self.console_log_path()).await { - Ok(logs) => Ok(logs), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()), - Err(error) => Err(error.into()), - } - } - - async fn start(&mut self) -> R<()> { - let mut child = self.child.lock().await; - if matches!(*child, ChildState::Running(_)) { - return Err(Error::InvalidState("already started".into())); - } - let _ = tokio::fs::remove_file(self.pid_path()).await; - let _ = tokio::fs::remove_file(self.exit_code_path()).await; - let _ = tokio::fs::remove_file(self.qmp_port_path()).await; - let _ = tokio::fs::remove_file(self.qga_port_path()).await; - let _ = tokio::fs::remove_file(self.console_port_path()).await; - let _ = tokio::fs::remove_file(self.console_log_path()).await; - *self.qmp_client.lock().await = None; - - let qmp_port = qmp::free_port().await?; - tokio::fs::write(self.qmp_port_path(), qmp_port.to_string()).await?; - let qga_port = if self.qga { - let mut port = qmp::free_port().await?; - while port == qmp_port { - port = qmp::free_port().await?; - } - tokio::fs::write(self.qga_port_path(), port.to_string()).await?; - Some(port) - } else { - None - }; - let mut console_port = qmp::free_port().await?; - while console_port == qmp_port || Some(console_port) == qga_port { - console_port = qmp::free_port().await?; - } - tokio::fs::write(self.console_port_path(), console_port.to_string()).await?; - - let kvm = Architecture::host() == Some(self.arch) && cli::kvm_available().await; - let sys_arch = match self.arch { - Architecture::Amd64 => cli::Arch::Amd64, - Architecture::Arm64 => cli::Arch::Arm64, - Architecture::Loong64 => cli::Arch::Loong64, - Architecture::Ppc64le => cli::Arch::Ppc64le, - Architecture::Riscv64 => cli::Arch::Riscv64, - Architecture::S390x => cli::Arch::S390x, - }; - let mut cmd = cli::Command { - binary: sys_arch.binary(), - machine: sys_arch.machine_type().map(String::from), - memory_mib: self.settings.ram, - smp: self.settings.cpu, - display_none: true, - nets: vec![ - cli::NetBackend::Nic { - model: "virtio".into(), - }, - cli::NetBackend::User { - hostfwd: self.settings.port_forwards.clone(), - }, - ], - devices: vec![cli::Device::VirtioRngPci, cli::Device::VirtioBalloon], - ..Default::default() - }; - - if kvm { - cmd.cpu = Some("host".into()); - cmd.accel = Some(cli::Accel::Kvm); - } else { - cmd.cpu = Some(sys_arch.tcg_cpu_model().into()); - cmd.accel = Some(cli::Accel::Tcg); - } - - let disk_path = self.dir.join(&self.disk.path); - match &self.boot { - QemuBoot::Bios => { - cmd.drives.push(cli::Drive { - file: disk_path, - snapshot: true, - interface: cli::DriveInterface::Virtio, - }); - } - QemuBoot::Linux(linux) => { - cmd.drives.push(cli::Drive { - file: disk_path, - snapshot: true, - interface: cli::DriveInterface::None { id: "root".into() }, - }); - cmd.devices.push(cli::Device::VirtioBlkPci { - drive: "root".into(), - }); - cmd.kernel = Some(self.dir.join(&linux.kernel.path)); - cmd.initrd = Some(self.dir.join(&linux.initrd.path)); - cmd.append = Some(linux.cmdline.clone()); - } - } - cmd.pidfile = Some(self.pid_path()); - cmd.qmp_port = Some(qmp_port); - cmd.qga_port = qga_port; - cmd.console = Some((console_port, self.console_log_path())); - let argv = cmd.to_argv(); - - let wrapper = supervise::spawn(&argv, &self.exit_code_path())?; - *child = ChildState::Running(wrapper); - drop(child); - - if let Some(port) = qga_port - && let Err(error) = qga::wait_until_ready(port, Duration::from_secs(60)).await - { - let _ = self.kill().await; - return Err(error); - } - Ok(()) - } - - async fn stop(&mut self) -> R<()> { - self.qmp_client() - .await? - .as_mut() - .expect("initialized by qmp_client") - .power_down() - .await - } - - async fn kill(&mut self) -> R<()> { - let pid = self.qemu_pid().await?; - supervise::kill(pid).await?; - // Reap the wrapper so its resources are released; its own exit - // status is uninteresting, qemu's (now on disk) is what matters. - let mut child = self.child.lock().await; - if let ChildState::Running(c) = &mut *child { - let _ = c.wait().await; - } - if let Some(status) = self.read_exit_code().await { - *child = ChildState::Exited(status); - } - Ok(()) - } - - async fn restart(&mut self) -> R<()> { - self.qmp_client() - .await? - .as_mut() - .expect("initialized by qmp_client") - .reset() - .await - } - - async fn delete(&mut self) -> R<()> { - if self.state().await == State::Running { - self.kill().await?; - } - let _ = tokio::fs::remove_file(self.pid_path()).await; - let _ = tokio::fs::remove_file(self.exit_code_path()).await; - let _ = tokio::fs::remove_file(self.qmp_port_path()).await; - let _ = tokio::fs::remove_file(self.qga_port_path()).await; - let _ = tokio::fs::remove_file(self.console_port_path()).await; - let _ = tokio::fs::remove_file(self.console_log_path()).await; - Ok(()) - } - - async fn pause(&mut self) -> R<()> { - self.qmp_client() - .await? - .as_mut() - .expect("initialized by qmp_client") - .pause() - .await - } - - async fn unpause(&mut self) -> R<()> { - self.qmp_client() - .await? - .as_mut() - .expect("initialized by qmp_client") - .resume() - .await - } - - async fn update(&mut self, settings: Settings) -> R<()> { - if settings.cpu != self.settings.cpu { - return Err(Error::Unsupported( - "qemu backend can't hot-change cpu count (needs maxcpus reserved at boot)".into(), - )); - } - if settings.port_forwards != self.settings.port_forwards { - return Err(Error::Unsupported( - "qemu backend can't hot-change port forwards (fixed at boot via -net user)".into(), - )); - } - if settings.ram != self.settings.ram { - self.qmp_client() - .await? - .as_mut() - .expect("initialized by qmp_client") - .set_balloon_size(settings.ram * 1024 * 1024) - .await?; - } - self.settings = settings; - Ok(()) - } - - async fn rename(&mut self, name: Option<&str>) -> R<()> { - self.name = name.map(String::from); - Ok(()) - } - - async fn wait(&mut self) -> R<ExitStatus> { - loop { - if let Some(status) = self.read_exit_code().await { - *self.child.lock().await = ChildState::Exited(status); - return Ok(status); - } - let mut child = self.child.lock().await; - match &mut *child { - ChildState::Running(c) => { - // The wrapper only exits after qemu does and the exit - // code is flushed to disk, so looping back re-reads it. - c.wait().await?; - } - ChildState::Exited(status) => return Ok(*status), - ChildState::NotStarted => { - return Err(Error::InvalidState("not started".into())); - } - } - } - } - - async fn exec(&self, cmd: &[String]) -> R<Output> { - if !self.qga { - return Err(Error::Unsupported( - "this image does not declare qga access".into(), - )); - } - let _guard = self.qga_lock.lock().await; - qga::exec(self.qga_port().await?, cmd).await - } - - async fn attach(&self) -> R<Box<dyn Console>> { - let port = self.console_port().await?; - for _ in 0..50 { - match tokio::net::TcpStream::connect(("127.0.0.1", port)).await { - Ok(stream) => return Ok(Box::new(stream)), - Err(_) => tokio::time::sleep(Duration::from_millis(20)).await, - } - } - Err(Error::InvalidState( - "qemu serial console did not become available".into(), - )) - } -} - -pub struct QemuHypervisor; - -#[async_trait] -impl Hypervisor for QemuHypervisor { - fn id(&self) -> HypervisorId { - QEMU_HYPERVISOR_ID - } - - fn name(&self) -> &'static str { - "qemu" - } - - fn supports(&self, boot: &Boot) -> bool { - matches!(boot, Boot::Bios(_) | Boot::Linux(_)) - } - - async fn create( - &self, - id: MachineId, - name: Option<&str>, - image: &MachineImage, - dir: &Path, - boot: &Boot, - settings: &Settings, - ) -> R<Box<dyn Machine>> { - let disk = image - .disks - .iter() - .find(|d| d.id == boot.disk()) - .cloned() - .ok_or_else(|| { - Error::InvalidImage(format!( - "boot entry references unknown disk '{}'", - boot.disk() - )) - })?; - - let qemu_boot = match boot { - Boot::Bios(_) => QemuBoot::Bios, - Boot::Linux(b) => QemuBoot::Linux(b.clone()), - Boot::Uefi(_) | Boot::Unknown(_) => { - return Err(Error::Unsupported(format!( - "qemu backend cannot boot protocol '{}'", - boot.protocol() - ))); - } - }; - - Ok(Box::new(QemuMachine { - id, - name: name.map(String::from), - dir: dir.to_path_buf(), - arch: image.system.architecture, - settings: settings.clone(), - disk, - boot: qemu_boot, - qga: image - .machine - .access - .iter() - .any(|access| matches!(access, Access::Qga { .. })), - child: Mutex::new(ChildState::NotStarted), - qga_lock: Mutex::new(()), - qmp_client: Mutex::new(None), - })) - } - - async fn reattach( - &self, - _id: MachineId, - _name: Option<&str>, - _dir: &Path, - _settings: &Settings, - ) -> R<Box<dyn Machine>> { - todo!("no persisted qemu run-state to reattach to yet") - } -} diff --git a/crates/hule-vmm/src/backend/qemu/qga.rs b/crates/hule-vmm/src/backend/qemu/qga.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/qemu/qga.rs +++ /dev/null @@ -1,233 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! Minimal qemu-guest-agent client over qemu's host-side chardev socket. - -use std::time::{Duration, Instant}; - -use base64::Engine; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; -use tokio::net::TcpStream; - -use crate::{Error, R}; - -async fn execute( - port: u16, - command: &str, - arguments: Option<serde_json::Value>, -) -> R<serde_json::Value> { - tokio::time::timeout( - Duration::from_secs(5), - execute_without_timeout(port, command, arguments), - ) - .await - .map_err(|_| Error::InvalidState(format!("qga {command} timed out")))? -} - -async fn execute_without_timeout( - port: u16, - command: &str, - arguments: Option<serde_json::Value>, -) -> R<serde_json::Value> { - let stream = TcpStream::connect(("127.0.0.1", port)).await?; - let mut stream = BufReader::new(stream); - let mut request = serde_json::json!({ "execute": command }); - if let Some(arguments) = arguments { - request["arguments"] = arguments; - } - stream - .get_mut() - .write_all( - format!( - "{}\n", - serde_json::to_string(&request) - .map_err(|error| Error::InvalidState(error.to_string()))? - ) - .as_bytes(), - ) - .await?; - - let mut response = String::new(); - stream.read_line(&mut response).await?; - if response.is_empty() { - return Err(Error::InvalidState( - "qemu-guest-agent closed its channel without replying".into(), - )); - } - validate_response(command, &response) -} - -fn validate_response(command: &str, response: &str) -> R<serde_json::Value> { - let response: serde_json::Value = serde_json::from_str(response) - .map_err(|error| Error::InvalidState(format!("invalid qga response: {error}")))?; - if let Some(error) = response.get("error") { - return Err(Error::InvalidState(format!( - "qga {command} failed: {error}" - ))); - } - response - .get("return") - .cloned() - .ok_or_else(|| Error::InvalidState(format!("qga {command} response has no return value"))) -} - -async fn ping(port: u16) -> R<()> { - execute(port, "guest-ping", None).await.map(|_| ()) -} - -pub async fn wait_until_ready(port: u16, timeout: Duration) -> R<()> { - let deadline = Instant::now() + timeout; - loop { - let attempt = tokio::time::timeout(Duration::from_secs(1), ping(port)).await; - if matches!(attempt, Ok(Ok(()))) { - return Ok(()); - } - if Instant::now() >= deadline { - return Err(Error::InvalidState(format!( - "declared qga access did not become ready within {} seconds", - timeout.as_secs() - ))); - } - tokio::time::sleep(Duration::from_millis(100)).await; - } -} - -pub async fn exec(port: u16, command: &[String]) -> R<std::process::Output> { - let (path, args) = command - .split_first() - .ok_or_else(|| Error::InvalidState("exec command must not be empty".into()))?; - let started = execute( - port, - "guest-exec", - Some(serde_json::json!({ - "path": path, - "arg": args, - "capture-output": true - })), - ) - .await?; - let pid = started - .get("pid") - .and_then(serde_json::Value::as_u64) - .ok_or_else(|| Error::InvalidState("qga guest-exec returned no pid".into()))?; - - loop { - let status = execute( - port, - "guest-exec-status", - Some(serde_json::json!({ "pid": pid })), - ) - .await?; - if !status - .get("exited") - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { - tokio::time::sleep(Duration::from_millis(20)).await; - continue; - } - - return output(&status); - } -} - -fn output(status: &serde_json::Value) -> R<std::process::Output> { - for field in ["out-truncated", "err-truncated"] { - if status - .get(field) - .and_then(serde_json::Value::as_bool) - .unwrap_or(false) - { - return Err(Error::InvalidState(format!( - "qga exec output was truncated ({field})" - ))); - } - } - let decode = |field: &str| -> R<Vec<u8>> { - let Some(encoded) = status.get(field).and_then(serde_json::Value::as_str) else { - return Ok(Vec::new()); - }; - base64::engine::general_purpose::STANDARD - .decode(encoded) - .map_err(|error| Error::InvalidState(format!("invalid qga {field}: {error}"))) - }; - Ok(std::process::Output { - status: exit_status(status)?, - stdout: decode("out-data")?, - stderr: decode("err-data")?, - }) -} - -fn exit_status(status: &serde_json::Value) -> R<std::process::ExitStatus> { - #[cfg(unix)] - { - use std::os::unix::process::ExitStatusExt; - if let Some(code) = status.get("exitcode").and_then(serde_json::Value::as_i64) { - let code: i32 = code - .try_into() - .map_err(|_| Error::InvalidState("qga returned an invalid exit code".into()))?; - return Ok(std::process::ExitStatus::from_raw(code << 8)); - } - if let Some(signal) = status.get("signal").and_then(serde_json::Value::as_i64) { - let signal: i32 = signal - .try_into() - .map_err(|_| Error::InvalidState("qga returned an invalid signal".into()))?; - return Ok(std::process::ExitStatus::from_raw(signal & 0x7f)); - } - Err(Error::InvalidState( - "qga exec status has neither exitcode nor signal".into(), - )) - } - #[cfg(windows)] - { - use std::os::windows::process::ExitStatusExt; - let code = status - .get("exitcode") - .and_then(serde_json::Value::as_i64) - .ok_or_else(|| Error::InvalidState("qga exec status has no exitcode".into()))?; - let code: u32 = code - .try_into() - .map_err(|_| Error::InvalidState("qga returned an invalid exit code".into()))?; - Ok(std::process::ExitStatus::from_raw(code)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn readiness_requires_a_successful_guest_ping_response() { - validate_response("guest-ping", r#"{"return":{}}"#).unwrap(); - assert!( - validate_response("guest-ping", r#"{"error":{"class":"CommandNotFound"}}"#).is_err() - ); - assert!(validate_response("guest-ping", r#"{"event":"something"}"#).is_err()); - } - - #[test] - fn exec_output_is_decoded_without_losing_exit_status() { - let output = output(&serde_json::json!({ - "exited": true, - "exitcode": 7, - "out-data": "aGVsbG8K", - "err-data": "b29wcwo=" - })) - .unwrap(); - assert_eq!(output.status.code(), Some(7)); - assert_eq!(output.stdout, b"hello\n"); - assert_eq!(output.stderr, b"oops\n"); - } - - #[test] - fn truncated_exec_output_is_an_error() { - assert!( - output(&serde_json::json!({ - "exited": true, - "exitcode": 0, - "out-truncated": true - })) - .is_err() - ); - } -} diff --git a/crates/hule-vmm/src/backend/qemu/qmp.rs b/crates/hule-vmm/src/backend/qemu/qmp.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/qemu/qmp.rs +++ /dev/null @@ -1,165 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! Minimal QMP client: line-delimited JSON commands/responses over the TCP -//! loopback channel qemu exposes via -//! `-qmp tcp:127.0.0.1:<port>,server=on,wait=off`. Events are read and -//! discarded, not surfaced. - -use serde::Deserialize; -use serde_json::{Value, json}; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; -use tokio::net::TcpStream; -use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf}; - -use crate::{Error, R}; - -pub struct Qmp { - reader: BufReader<OwnedReadHalf>, - writer: OwnedWriteHalf, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Status { - Running, - Paused, - Transitional, -} - -impl Status { - fn from_wire(status: &str) -> Self { - match status { - "running" => Self::Running, - "paused" => Self::Paused, - _ => Self::Transitional, - } - } -} - -impl Qmp { - /// Connects and completes the capabilities handshake (greeting -> - /// `qmp_capabilities`), after which arbitrary commands are allowed. - pub async fn connect(port: u16) -> R<Self> { - let (read_half, write_half) = TcpStream::connect(("127.0.0.1", port)).await?.into_split(); - let mut qmp = Self { - reader: BufReader::new(read_half), - writer: write_half, - }; - qmp.read_message().await?; // greeting - qmp.execute("qmp_capabilities", None).await?; - Ok(qmp) - } - - pub async fn status(&mut self) -> R<Status> { - #[derive(Deserialize)] - struct Response { - status: String, - } - - let response: Response = self.execute_typed("query-status", None).await?; - Ok(Status::from_wire(&response.status)) - } - - pub async fn power_down(&mut self) -> R<()> { - self.execute_empty("system_powerdown", None).await - } - - pub async fn reset(&mut self) -> R<()> { - self.execute_empty("system_reset", None).await - } - - pub async fn pause(&mut self) -> R<()> { - self.execute_empty("stop", None).await - } - - pub async fn resume(&mut self) -> R<()> { - self.execute_empty("cont", None).await - } - - pub async fn set_balloon_size(&mut self, bytes: u64) -> R<()> { - self.execute_empty("balloon", Some(json!({ "value": bytes }))) - .await - } - - async fn read_message(&mut self) -> R<Value> { - loop { - let mut line = String::new(); - if self.reader.read_line(&mut line).await? == 0 { - return Err(Error::InvalidState("qmp connection closed".into())); - } - - let line = line.trim(); - if line.is_empty() { - continue; - } - - let value: Value = serde_json::from_str(line) - .map_err(|e| Error::InvalidState(format!("invalid qmp message: {e}")))?; - - // Events arrive unprompted between a command and its response; - // we don't surface them (yet), so skip past them here. - if value.get("event").is_some() { - continue; - } - - return Ok(value); - } - } - - async fn execute(&mut self, command: &str, arguments: Option<Value>) -> R<Value> { - let mut request = json!({ "execute": command }); - if let Some(arguments) = arguments { - request["arguments"] = arguments; - } - let mut bytes = serde_json::to_vec(&request).expect("serializable request"); - bytes.push(b'\n'); - self.writer.write_all(&bytes).await?; - let response = self.read_message().await?; - if let Some(error) = response.get("error") { - return Err(Error::InvalidState(format!( - "qmp '{command}' failed: {error}" - ))); - } - response.get("return").cloned().ok_or_else(|| { - Error::InvalidState(format!("qmp '{command}' response has no return value")) - }) - } - - async fn execute_empty(&mut self, command: &str, arguments: Option<Value>) -> R<()> { - self.execute(command, arguments).await.map(|_| ()) - } - - async fn execute_typed<T: for<'de> Deserialize<'de>>( - &mut self, - command: &str, - arguments: Option<Value>, - ) -> R<T> { - let value = self.execute(command, arguments).await?; - serde_json::from_value(value).map_err(|error| { - Error::InvalidState(format!("invalid qmp '{command}' result: {error}")) - }) - } -} - -/// Picks a free TCP port on 127.0.0.1: binds to port 0 (OS assigns one), -/// reads it back, then drops the listener before qemu binds it for real. -/// Small TOCTOU race in principle; standard practice in the absence of a -/// way to ask qemu what port it actually bound. -pub async fn free_port() -> std::io::Result<u16> { - Ok(tokio::net::TcpListener::bind(("127.0.0.1", 0)) - .await? - .local_addr()? - .port()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn wire_status_does_not_escape_the_qmp_boundary() { - assert_eq!(Status::from_wire("running"), Status::Running); - assert_eq!(Status::from_wire("paused"), Status::Paused); - assert_eq!(Status::from_wire("inmigrate"), Status::Transitional); - } -} diff --git a/crates/hule-vmm/src/backend/qemu/supervise.rs b/crates/hule-vmm/src/backend/qemu/supervise.rs deleted file mode 100644 --- a/crates/hule-vmm/src/backend/qemu/supervise.rs +++ /dev/null @@ -1,190 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -//! Runs a command so its exit code survives even once nobody is left to -//! `wait()` on it as its real OS parent -- podman does this with `conmon`; -//! here the host's own shell does the same job. Host-specific by nature -//! (`sh` on POSIX, PowerShell on Windows), which is fine: unlike guests, -//! the set of hosts we run on is small and known, so a wrapper per host is -//! not a burden. Each function has one signature; the OS split lives inside -//! as `#[cfg]`-gated blocks. - -use std::fmt; -use std::io; -use std::path::Path; - -use tokio::process::{Child, Command}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Pid(pub u32); - -impl fmt::Display for Pid { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -/// Fixed PowerShell wrapper: `$Bin`/`$ExitFile`/`$Rest` all arrive as real -/// process arguments (via `-File`, which binds them like any `param()` -/// block), never spliced into script text. -#[cfg(windows)] -const SUPERVISE_PS1: &str = r#" -param( - [Parameter(Mandatory=$true, Position=0)] [string]$Bin, - [Parameter(Mandatory=$true, Position=1)] [string]$ExitFile, - [Parameter(ValueFromRemainingArguments=$true)] [string[]]$Rest -) -& $Bin @Rest -Set-Content -Path $ExitFile -Value $LASTEXITCODE -NoNewline -"#; - -/// Spawns `argv` (`argv[0]` is the binary) wrapped so that once it exits, -/// its exit code is written to `exit_code_file` -- readable later even by a -/// process that isn't its parent and so can't `wait()` on it directly. -/// -/// All dynamic values travel as separate argv entries to the wrapper, never -/// interpolated into script text, so nothing needs escaping. -pub fn spawn(argv: &[String], exit_code_file: &Path) -> io::Result<Child> { - #[cfg(unix)] - { - Command::new("sh") - .arg("-c") - .arg(r#"bin="$1"; shift; exitfile="$1"; shift; "$bin" "$@"; echo $? > "$exitfile""#) - .arg("sh") // conventional $0 filler, unused - .arg(&argv[0]) - .arg(exit_code_file) - .args(&argv[1..]) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - } - #[cfg(windows)] - { - // Content is constant, only the path is dynamic -- written next to - // the machine's own files, same lifetime as the pidfile/exit-code - // file. - let script = exit_code_file - .parent() - .unwrap_or_else(|| Path::new(".")) - .join("supervise.ps1"); - std::fs::write(&script, SUPERVISE_PS1)?; - - Command::new("powershell") - .args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-File"]) - .arg(&script) - .arg(&argv[0]) - .arg(exit_code_file) - .args(&argv[1..]) - .stdin(std::process::Stdio::null()) - .stdout(std::process::Stdio::null()) - .stderr(std::process::Stdio::null()) - .spawn() - } -} - -/// Whether `pid` is still alive. Works for any pid, not just our own -/// children -- `Child::try_wait` only works on the latter. -pub async fn pid_alive(pid: Pid) -> bool { - #[cfg(target_os = "linux")] - { - tokio::fs::try_exists(format!("/proc/{pid}")) - .await - .unwrap_or(false) - } - #[cfg(all(unix, not(target_os = "linux")))] - { - Command::new("kill") - .arg("-0") - .arg(pid.to_string()) - .status() - .await - .map(|s| s.success()) - .unwrap_or(false) - } - #[cfg(windows)] - { - let Ok(out) = Command::new("tasklist") - .args(["/FI", &format!("PID eq {pid}"), "/NH"]) - .output() - .await - else { - return false; - }; - String::from_utf8_lossy(&out.stdout).contains(&pid.to_string()) - } -} - -/// Force-terminates `pid`. No parent relationship required, unlike -/// `Child::kill()`, which is exactly the point. -pub async fn kill(pid: Pid) -> io::Result<()> { - #[cfg(unix)] - { - let status = Command::new("kill") - .arg("-KILL") - .arg(pid.to_string()) - .status() - .await?; - if status.success() { - Ok(()) - } else { - Err(io::Error::other(format!("kill -KILL {pid} failed"))) - } - } - #[cfg(windows)] - { - let status = Command::new("taskkill") - .args(["/PID", &pid.to_string(), "/F"]) - .status() - .await?; - if status.success() { - Ok(()) - } else { - Err(io::Error::other(format!("taskkill /PID {pid} /F failed"))) - } - } -} - -/// (cpu_time_ns, memory_bytes) for `pid`, read straight from the host -/// process -- no QMP/guest cooperation needed. -pub async fn process_stats(pid: Pid) -> io::Result<(u64, u64)> { - #[cfg(target_os = "linux")] - { - let stat = tokio::fs::read_to_string(format!("/proc/{pid}/stat")).await?; - // `comm` (field 2) can itself contain spaces/parens; splitting after - // the last ')' reliably skips past it regardless. - let after_comm = stat - .rsplit_once(')') - .map(|(_, rest)| rest) - .ok_or_else(|| io::Error::other("unexpected /proc/pid/stat format"))?; - let fields: Vec<&str> = after_comm.split_whitespace().collect(); - let field = |i: usize| -> io::Result<u64> { - fields - .get(i) - .and_then(|s| s.parse().ok()) - .ok_or_else(|| io::Error::other("unexpected /proc/pid/stat format")) - }; - // Fields are 0-indexed from `state` (original field 3); utime/stime - // are original fields 14/15. 100 (USER_HZ) is the practically - // universal Linux clock tick rate. - let cpu_time_ns = (field(11)? + field(12)?) * 10_000_000; - - let status = tokio::fs::read_to_string(format!("/proc/{pid}/status")).await?; - let memory_bytes = status - .lines() - .find_map(|line| line.strip_prefix("VmRSS:")) - .and_then(|rest| rest.split_whitespace().next()) - .and_then(|kb| kb.parse::<u64>().ok()) - .map(|kb| kb * 1024) - .ok_or_else(|| io::Error::other("VmRSS not found in /proc/pid/status"))?; - - Ok((cpu_time_ns, memory_bytes)) - } - #[cfg(not(target_os = "linux"))] - { - let _ = pid; - Err(io::Error::other( - "process stats aren't implemented for this host yet", - )) - } -} diff --git a/crates/hule-vmm/src/hypervisor.rs b/crates/hule-vmm/src/hypervisor.rs deleted file mode 100644 --- a/crates/hule-vmm/src/hypervisor.rs +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -use std::fmt; -use std::path::Path; - -use async_trait::async_trait; -use hule_hmi::{Boot, MachineImage}; - -use crate::{Machine, MachineId, R, Settings}; - -/// Self-assigned backend identity, unique only within one `Monitor` -/// (checked in [`crate::Monitor::new`]) -- plugins can't coordinate globally. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct HypervisorId(pub u128); - -impl fmt::Display for HypervisorId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -/// A single hypervisor backend (qemu, firecracker, ...). -#[async_trait] -pub trait Hypervisor: Send + Sync { - fn id(&self) -> HypervisorId; - fn name(&self) -> &'static str; - - /// Whether this backend can boot the given protocol. - fn supports(&self, boot: &Boot) -> bool; - - /// Create a machine bound to `dir`. Does not start it. - async fn create( - &self, - id: MachineId, - name: Option<&str>, - image: &MachineImage, - dir: &Path, - boot: &Boot, - settings: &Settings, - ) -> R<Box<dyn Machine>>; - - /// Reconnect to a machine this backend previously created, e.g. after a - /// restart. `id`/`name`/`settings` come from the monitor's own record. - async fn reattach( - &self, - id: MachineId, - name: Option<&str>, - dir: &Path, - settings: &Settings, - ) -> R<Box<dyn Machine>>; -} diff --git a/crates/hule-vmm/src/lib.rs b/crates/hule-vmm/src/lib.rs index 681faa1..d508953 100644 --- a/crates/hule-vmm/src/lib.rs +++ b/crates/hule-vmm/src/lib.rs @@ -1,81 +1,4 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov +// SPDX-FileCopyrightText: 2026 Nikolay Govorov // SPDX-License-Identifier: Apache-2.0 -//! Machine lifecycle: hypervisor plugins, machine handles, and the monitor -//! that tracks a fleet of them. -//! -//! No OCI, registry, or storage concerns -- callers hand in an -//! already-resolved [`hule_hmi::MachineImage`] plus a directory of its -//! files. -//! -//! `Machine`/`Monitor` mirror Docker's container API term-for-term. -//! Excluded: `changes`/`export`/`archive` (no host-visible VM filesystem -//! without guest cooperation), `top` (guest internals are opaque to the -//! host by construction -- use `exec`). - -pub mod backend; -mod hypervisor; -mod machine; -mod monitor; - -use std::fmt; - -pub use hypervisor::{Hypervisor, HypervisorId}; -pub use machine::{Console, Machine, MachineId, Settings, State, Stats}; -pub use monitor::Monitor; - -#[derive(Debug)] -pub enum Error { - /// No registered hypervisor supports any boot protocol the image declares. - Unsupported(String), - - /// The image is not resolvable in this context (e.g. `boot` references an unknown disk id). - InvalidImage(String), - - /// The machine isn't in the state the operation requires. - InvalidState(String), - - /// No machine matches the given id. - NotFound(MachineId), - - /// Two registered hypervisors share a `HypervisorId`. - DuplicateHypervisor(HypervisorId), - - /// Underlying OS/process failure. - Io(std::io::Error), -} - -impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Unsupported(msg) => write!(f, "unsupported: {msg}"), - Self::InvalidImage(msg) => write!(f, "invalid image: {msg}"), - Self::InvalidState(msg) => write!(f, "invalid state: {msg}"), - Self::NotFound(id) => write!(f, "no machine '{id}'"), - Self::DuplicateHypervisor(id) => { - write!( - f, - "duplicate hypervisor id {id} registered with this monitor" - ) - } - Self::Io(err) => write!(f, "{err}"), - } - } -} - -impl std::error::Error for Error { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io(err) => Some(err), - _ => None, - } - } -} - -impl From<std::io::Error> for Error { - fn from(err: std::io::Error) -> Self { - Self::Io(err) - } -} - -pub type R<T> = std::result::Result<T, Error>; +pub const NAME: &str = "I'm a vmm library"; diff --git a/crates/hule-vmm/src/machine.rs b/crates/hule-vmm/src/machine.rs deleted file mode 100644 --- a/crates/hule-vmm/src/machine.rs +++ /dev/null @@ -1,96 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -use std::fmt; -use std::process::{ExitStatus, Output}; - -use async_trait::async_trait; -use tokio::io::{AsyncRead, AsyncWrite}; -use uuid::Uuid; - -use crate::{HypervisorId, R}; - -/// Always a UUIDv7 from [`crate::Monitor::create`], so ids sort by creation -/// time. An optional, non-unique name can ride alongside -- see -/// [`Machine::name`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct MachineId(pub Uuid); - -impl fmt::Display for MachineId { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -/// Coarse machine state, mirroring Docker's container states. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum State { - Created, - Running, - Paused, - Restarting, - Exited(i32), - Dead, -} - -/// A live duplex connection to a machine's interactive console. -pub trait Console: AsyncRead + AsyncWrite + Send + Unpin {} -impl<T: AsyncRead + AsyncWrite + Send + Unpin> Console for T {} - -/// Deployment-time config of one instance -- distinct from -/// [`hule_hmi::MachineImage`], which only declares a cpu/ram *range* and -/// knows nothing about e.g. host ports. Always concrete: callers resolve -/// image defaults before constructing this. -#[derive(Debug, Clone, PartialEq)] -pub struct Settings { - pub cpu: u32, - pub ram: u64, // megabytes - - /// (host, guest) TCP port pairs forwarded to the guest's access channel. - pub port_forwards: Vec<(u16, u16)>, -} - -/// A snapshot of resource usage, as of the call to `Machine::stats`. -#[derive(Debug, Clone, Copy)] -pub struct Stats { - pub cpu_time_ns: u64, - pub memory_bytes: u64, -} - -/// A handle to one virtual machine. Method names follow the Docker Engine -/// API's container operations (see the crate docs for the two exclusions). -/// -/// Everything that can touch disk or a socket is `async` -- this crate runs -/// on tokio throughout, no blocking calls. -#[async_trait] -pub trait Machine: Send + Sync { - fn id(&self) -> MachineId; - fn hid(&self) -> HypervisorId; - - /// Optional, caller-chosen, not required to be unique. - fn name(&self) -> Option<&str>; - - /// In-memory, not the persisted record -- see `update`/`rename` for why - /// those are `async` while this isn't. - fn settings(&self) -> Settings; - - async fn state(&self) -> State; - async fn stats(&self) -> R<Stats>; - async fn logs(&self) -> R<Vec<u8>>; - - async fn start(&mut self) -> R<()>; - async fn stop(&mut self) -> R<()>; - async fn kill(&mut self) -> R<()>; - async fn restart(&mut self) -> R<()>; - async fn delete(&mut self) -> R<()>; - - async fn pause(&mut self) -> R<()>; - async fn unpause(&mut self) -> R<()>; - - async fn update(&mut self, settings: Settings) -> R<()>; - async fn rename(&mut self, name: Option<&str>) -> R<()>; - - async fn exec(&self, cmd: &[String]) -> R<Output>; - async fn wait(&mut self) -> R<ExitStatus>; - async fn attach(&self) -> R<Box<dyn Console>>; -} diff --git a/crates/hule-vmm/src/monitor.rs b/crates/hule-vmm/src/monitor.rs deleted file mode 100644 --- a/crates/hule-vmm/src/monitor.rs +++ /dev/null @@ -1,109 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov -// SPDX-License-Identifier: Apache-2.0 - -use std::path::{Path, PathBuf}; - -use hule_hmi::MachineImage; -use tokio::sync::mpsc::Receiver; -use uuid::Uuid; - -use crate::{Error, Hypervisor, Machine, MachineId, R, Settings, State}; - -/// A fleet-wide state change, as delivered by [`Monitor::events`]. -#[derive(Debug, Clone)] -pub struct Event { - pub machine: MachineId, - pub kind: EventKind, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum EventKind { - Created, - Started, - Stopped, - Killed, - Restarted, - Paused, - Unpaused, - Removed, -} - -/// Tracks a fleet of machines, possibly across different hypervisors. -pub struct Monitor { - #[allow(dead_code)] // read by list()/get() once persisted state lands - run_dir: PathBuf, - - hypervisors: Vec<Box<dyn Hypervisor>>, -} - -impl Monitor { - pub fn new(run_dir: PathBuf, hypervisors: Vec<Box<dyn Hypervisor>>) -> R<Self> { - let mut seen = std::collections::HashSet::new(); - for hv in &hypervisors { - if !seen.insert(hv.id()) { - return Err(Error::DuplicateHypervisor(hv.id())); - } - } - Ok(Self { - run_dir, - hypervisors, - }) - } - - /// Picks the first (hypervisor, boot protocol) pair the hypervisor - /// supports and creates through it. Manifest boot order isn't significant. - pub async fn create( - &self, - image: &MachineImage, - dir: &Path, - name: Option<&str>, - settings: &Settings, - ) -> R<Box<dyn Machine>> { - let id = MachineId(Uuid::now_v7()); - let (hv, boot) = image - .machine - .boot - .iter() - .filter(|b| b.is_recognized()) - .find_map(|b| { - self.hypervisors - .iter() - .find(|hv| hv.supports(b)) - .map(|hv| (hv, b)) - }) - .ok_or_else(|| { - Error::Unsupported( - "no registered hypervisor supports any declared boot protocol".into(), - ) - })?; - hv.create(id, name, image, dir, boot, settings).await - } - - /// All machines known to this monitor, running or not. - pub async fn list(&self) -> R<Vec<Box<dyn Machine>>> { - todo!("needs a persisted run-state format -- see open design question") - } - - pub async fn get(&self, _id: MachineId) -> R<Box<dyn Machine>> { - todo!("needs a persisted run-state format -- see open design question") - } - - /// Live stream of fleet-wide state changes. Needs a publish path from - /// `Machine` impls -- same open question as `list`/`get`. - pub async fn events(&self) -> R<Receiver<Event>> { - todo!("needs a publish path from Machine implementations") - } - - /// Deletes every non-running machine (`list` + `delete`; no hypervisor - /// has a native bulk op). Returns the count deleted. - pub async fn prune(&self) -> R<usize> { - let mut deleted = 0; - for mut machine in self.list().await? { - if machine.state().await != State::Running { - machine.delete().await?; - deleted += 1; - } - } - Ok(deleted) - } -} diff --git a/crates/hule/Cargo.toml b/crates/hule/Cargo.toml index 728df1e..e5bf51f 100644 --- a/crates/hule/Cargo.toml +++ b/crates/hule/Cargo.toml @@ -1,4 +1,4 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2026 Nikolay Govorov # SPDX-License-Identifier: Apache-2.0 [package] @@ -13,9 +13,5 @@ authors.workspace = true repository.workspace = true [dependencies] -clap = { version = "4.6.1", features = ["derive"] } -hule-hmi.workspace = true hule-oci.workspace = true hule-vmm.workspace = true -tokio = { workspace = true, features = ["rt-multi-thread", "macros", "fs"] } -uuid = { version = "1", features = ["v7"] } diff --git a/crates/hule/src/main.rs b/crates/hule/src/main.rs index a1be2bb..73d3f4f 100644 --- a/crates/hule/src/main.rs +++ b/crates/hule/src/main.rs @@ -1,182 +1,10 @@ -// SPDX-FileCopyrightText: 2026 Nikolay Govorov +// SPDX-FileCopyrightText: 2026 Nikolay Govorov // SPDX-License-Identifier: Apache-2.0 -use std::fmt::Display; -use std::path::{Path, PathBuf}; -use std::process::exit; +use hule_oci; +use hule_vmm; -use clap::{Parser, Subcommand}; -use hule_hmi::{Access, MachineImage}; -use hule_vmm::backend::qemu::QemuHypervisor; -use hule_vmm::{Hypervisor, MachineId, Settings}; -use uuid::Uuid; - -type R<T> = std::result::Result<T, String>; - -#[derive(Parser)] -#[command(version, about)] -#[command(propagate_version = true)] -struct Cli { - #[command(subcommand)] - command: Commands, -} - -#[derive(Subcommand)] -enum Commands { - Image { - #[command(subcommand)] - command: ImageCommands, - }, - - Machine { - #[command(subcommand)] - command: MachineCommands, - }, -} - -#[derive(Subcommand)] -enum ImageCommands { - Pull { - name: String, - }, - - Push { - name: String, - }, - - Load { - image: String, - - reference: Option<String>, - }, -} - -#[derive(Subcommand)] -enum MachineCommands { - Run { - image: String, - - #[arg(default_value_t = 8022)] - port: u16, - }, -} - -fn die(msg: impl Display) -> ! { - eprintln!("hule: {msg}"); - exit(1); -} - -async fn cmd_run(images: &hule_oci::ImageManager, reference: &str, port: u16) -> R<()> { - if !images - .contains(reference) - .await - .map_err(|error| error.to_string())? - { - eprintln!("hule: {reference} not found locally, pulling..."); - images - .pull(reference) - .await - .map_err(|error| error.to_string())?; - } - - let scratch = std::env::temp_dir().join(format!("hule-run-{}", std::process::id())); - let config = images - .materialize(reference, &scratch) - .await - .map_err(|error| error.to_string())?; - let image = MachineImage::from_json(&config).map_err(|e| e.to_string())?; - let hv = QemuHypervisor; - - let boot = image - .machine - .boot - .iter() - .find(|b| matches!(b, hule_hmi::Boot::Linux(_)) && hv.supports(b)) - .or_else(|| image.machine.boot.iter().find(|b| hv.supports(b))) - .ok_or("no boot protocol in manifest is supported by the qemu backend")?; - - let guest_port = image - .machine - .access - .iter() - .find_map(|a| match a { - Access::Ssh { port, .. } => Some(*port), - Access::Qga { .. } | Access::Unknown(_) => None, - }) - .unwrap_or(22); - let settings = Settings { - cpu: image.machine.cpu.default as u32, - ram: image.machine.ram.default / (1024 * 1024), - port_forwards: vec![(port, guest_port)], - }; - - let mut machine = hv - .create( - MachineId(Uuid::now_v7()), - None, - &image, - &scratch, - boot, - &settings, - ) - .await - .map_err(|e| e.to_string())?; - - eprintln!( - "hule: booting {} via {} (ssh: localhost:{port})", - scratch.display(), - boot.protocol() - ); - machine.start().await.map_err(|e| e.to_string())?; - let status = machine.wait().await.map_err(|e| e.to_string())?; - exit(status.code().unwrap_or(1)); -} - -#[tokio::main] -async fn main() { - let cli = Cli::parse(); - - let home = std::env::var("HOME").unwrap_or_else(|_| die("HOME is not set")); - let root = PathBuf::from(home).join(".hule"); - - let storage = hule_oci::Storage::open(root.join("oci"), root.join("hmi")) - .await - .unwrap_or_else(|e| die(e)); - - let images = hule_oci::ImageManager::new(storage); - - match &cli.command { - Commands::Image { command } => match &command { - ImageCommands::Pull { name } => { - let digest = images.pull(name).await.unwrap_or_else(|e| die(e)); - eprintln!("hule: pulled {} ({digest})", name); - } - - ImageCommands::Push { name } => { - images.push(name).await.unwrap_or_else(|e| die(e)); - eprintln!("hule: pushed {}", name); - } - - ImageCommands::Load { reference, image } => { - let digest = images - .load(Path::new(image), reference.as_deref()) - .await - .unwrap_or_else(|e| die(e)); - - match reference { - Some(reference) => { - eprintln!("hule: loaded {} as {reference} ({digest})", image) - } - None => eprintln!("hule: loaded {} ({digest}, untagged)", image), - } - } - }, - Commands::Machine { command } => match &command { - MachineCommands::Run { image, port } => { - cmd_run(&images, image, *port) - .await - .unwrap_or_else(|e| die(e)); - } - }, - } +fn main() { + println!("oci: {}", hule_oci::NAME); + println!("vmm: {}", hule_vmm::NAME); } diff --git a/deny.toml b/deny.toml deleted file mode 100644 --- a/deny.toml +++ /dev/null @@ -1,18 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -[licenses] -allow = [ - "Apache-2.0", - "Apache-2.0 WITH LLVM-exception", - "BSD-2-Clause", - "BSD-3-Clause", - "BSL-1.0", - "CDLA-Permissive-2.0", - "ISC", - "MIT", - "MPL-2.0", - "Unicode-3.0", - "Zlib", -] -unused-allowed-license = "allow" diff --git a/docs/landscape.md b/docs/landscape.md deleted file mode 100644 --- a/docs/landscape.md +++ /dev/null @@ -1,45 +0,0 @@ -# Isolation landscape - -A cursory overview of similar or related projects that caught the author's -attention. There is no systematic approach, so great projects might be -overlooked. - -**Containers:** - -- <https://podman.io> -- <https://docker.com> -- <https://colima.run> -- <https://containerd.io> -- <https://linuxcontainers.org/incus> -- <https://github.com/apple/container> - -**Container build tools:** - -- <https://buildah.io> -- <https://github.com/lxc/distrobuilder> - -**Micro VM:** - -- <https://lima-vm.io> -- <https://microsandbox.dev> -- <https://firecracker-microvm.io> -- <https://github.com/libkrun/krunvm> - -**macOS VM:** - -- <https://tart.run> -- <https://veertu.com> - -**VM image formats:** - -- <https://www.dmtf.org/standards/ovf> -- <https://www.qemu.org/docs/master/interop/qcow2.html> - -**Hypervisor:** - -- [Xen](https://xenproject.org) -- [QEMU](https://www.qemu.org) -- [Linux KVM](https://docs.kernel.org/virt/kvm/index.html) -- [Windows Hyper-V](https://learn.microsoft.com/windows-server/virtualization/hyper-v/) -- [Apple Hypervisor.framework](https://developer.apple.com/documentation/hypervisor) -- [Apple Virtualization.framework](https://developer.apple.com/documentation/virtualization) diff --git a/docs/whitepaper.md b/docs/whitepaper.md deleted file mode 100644 --- a/docs/whitepaper.md +++ /dev/null @@ -1,224 +0,0 @@ -# Hule Whitepaper - -> [!CAUTION] -> This document describes the intended architecture and boundaries of Hule. The -> implementation is still in progress and does not yet provide every capability -> described here. - -Hule is a portable machine-image format and a set of tools for distributing, -running, and deriving virtual machines. - -Containers made Linux user spaces easy to package and distribute, but they share -the host kernel. They cannot represent a different kernel, an arbitrary -operating system, or a machine built for another CPU architecture. Virtual -machines can, but their images and configuration are commonly tied to one -hypervisor or one cloud. - -Hule provides a common boundary between a prepared virtual machine, an OCI -registry, and the hypervisor that runs it. - -## Design - -Hule is built on two existing technologies: - -- OCI solves distribution: content-addressed storage, large blobs, caching, - deduplication, authentication, and multi-platform indexes. -- Qcow2 backing files represent derived disks efficiently: a child image stores - only the blocks that differ from an immutable parent. - -Hule connects them through a filesystem format rather than through a service -API: - -```text - OCI registry - ↕ - hule-oci - ↕ -external builders → machine directory → hule-vmm - Packer, genimg, config.json ↓ - manual install, *.hmi files QEMU / native VMM - existing VM - ↓ - Hulefile runner - (commands via exec) - ↓ - derived machine directory -``` - -`hule-oci` and `hule-vmm` do not call each other. The materialized machine -directory is their only contract. A directory may be created without OCI, and a -pulled image may be inspected or copied without starting a hypervisor. - -## Machine Format - -A materialized machine is a directory containing a `config.json`, one or more -Hule Machine Image (`.hmi`) disks, and optional boot resources such as a kernel -or initrd. - -```text -machine/ -├── config.json -├── root.hmi -├── kernel -└── initrd -``` - -`config.json` describes the machine contract: - -- the guest operating system and CPU architecture; -- minimum and default resources; -- available boot protocols; -- disks and other required files; -- networking expectations; -- ways to access the guest, such as SSH or a guest agent. - -It describes what the image requires and supports, not a hypervisor command -line. Deployment-specific choices such as host port mappings, bridged networks, -and instance names are runtime settings and are not part of the immutable image. - -### HMI - -HMI is a constrained form of qcow2 intended for portable disk chains. Its -required invariant is semantic rather than byte-for-byte equivalence: given the -complete backing chain, an HMI disk and its flattened raw representation have -the same virtual size and expose the same bytes to the guest. - -This invariant enables two operations: - -1. Flatten an HMI chain into raw, then convert it if necessary for a hypervisor - that cannot consume qcow2 natively. -2. Convert a modified disk back to qcow2 and safely rebase it onto its original - base, producing a small HMI that contains only the guest-visible difference. - -Qcow2 metadata such as physical cluster placement, compression, or internal -allocation does not need to survive this round trip. The virtual disk contents -do. - -Backing images are immutable. A running instance writes to a separate overlay; -published images and shared cache entries are never used as writable instance -state. - -## Distribution - -`hule-oci` maps a machine directory and all HMI files needed by its backing -chains to OCI artifacts. Large files may be split into independently compressed -chunks so they can be transferred and verified in parallel. - -It is responsible for: - -- loading and saving already prepared Hule machines; -- pushing and pulling OCI artifacts; -- maintaining a content-addressed local cache; -- resolving complete backing chains; -- materializing a machine directory on disk. - -OCI indexes can contain variants for different guest operating systems and CPU -architectures. Native execution is an optimization, not a requirement: a user -may intentionally select a foreign architecture and run it through emulation. - -`hule-oci` does not provision guests and does not know how a machine will be -executed. - -## Runtime - -`hule-vmm` starts a materialized machine directory. Hypervisor backends -translate the machine contract into their native configuration and expose a -common machine lifecycle. - -QEMU is the tier-0 backend. It provides a widely available implementation of the -machine model and, importantly, full-system CPU emulation. This makes scenarios -such as a RISC-V NetBSD guest on an Arm macOS host valid even when they are not -fast. - -Native backends may provide better integration and performance when the host and -guest are compatible. They may flatten or convert HMI disks into their native -storage format before starting the VM. This conversion is a runtime detail and -does not change the distributed Hule image. - -`hule-vmm` does not know whether its input came from an OCI registry, a local -builder, an exported VM, or a directory copied by the user. - -## Derivation with Hulefile - -A Hulefile is a recipe for deriving one Hule image from another. Unlike an -external image builder, it does not install an operating system from scratch. -Its input is an already loaded Hule machine that can be started and controlled -through an `exec`-capable access method. - -Every Hulefile has exactly one parent image. There is no empty base and no -equivalent of `FROM scratch`: creating the first bootable machine always happens -outside the Hulefile workflow and enters Hule through load or import. - -The intended execution model is deliberately simple: - -1. Resolve and pin the immutable parent image. -2. Start it with a persistent writable instance overlay. -3. Execute the Hulefile commands sequentially inside the guest through `exec`. -4. If every command succeeds, shut the guest down and flush its disk state. -5. Rebase the resulting disk onto the parent and produce a new HMI and - `config.json`. -6. If any command fails, discard the temporary instance and produce no image. - -One Hulefile produces one image boundary. Individual commands do not create -published layers or snapshots, and intermediate states are not part of the -format. This keeps the backing chain tied to meaningful image derivations rather -than to the number of provisioning commands. - -The exact Hulefile syntax is not defined yet. It is expected to be a small shell -dialect for running arbitrary commands, with only the additional structure -needed to identify the parent and describe changes to the resulting machine -configuration. A Hulefile runs in the context of its parent guest and is not -implicitly portable across operating systems. - -## Image Lifecycle - -### Prepare, Import, and Load - -Preparing a base guest operating system is outside Hule. Users may use Packer, a -`genimg` script, an unattended installer, or a manually configured VM. A -finished Hule machine with HMI disks and a `config.json` enters the local store -through load and can be exported again through save. A qcow2 or raw disk image -instead enters through import, which converts it to HMI and constructs the -machine configuration where possible. The resulting Hule image can then be -distributed or used as the parent of a Hulefile. - -This boundary is important for systems whose prebuilt images cannot be freely -redistributed. A project can publish a recipe that downloads official -installation media, builds an image on the user's machine, and pushes the result -to the user's own OCI registry. - -### Publish - -The prepared Hule machine is loaded, validated, split into OCI blobs, and pushed -to a registry. Tags provide convenient names; digests identify immutable -versions. - -### Run - -The OCI artifact is pulled and materialized. `hule-vmm` selects a compatible -backend and boot protocol, creates writable instance state, and starts the VM. - -### Derive - -A Hulefile is the standard path for reproducibly deriving an image. A modified -instance disk may also be converted back to HMI and rebased onto the immutable -image from which it originated. Only the resulting difference needs to be -published; unchanged parent data is reused through the backing chain and OCI -content store. - -## Scope - -Hule defines how a prepared machine is represented, distributed, materialized, -run, and derived. It does not: - -- install a base guest operating system from installation media; -- replace Packer, unattended installers, or other from-scratch image builders; -- create a machine from an empty Hulefile parent; -- serve as a general-purpose workload orchestrator inside the guest; -- require a particular OCI registry; -- promise native acceleration for every host and guest combination; -- grant redistribution rights for operating systems or software contained in an - image. - -The format is the product boundary. Builders produce it, registries transport -it, and runtimes consume it independently. diff --git a/images/alpine/3.20/functions b/images/alpine/3.20/functions new file mode 120000 --- /dev/null +++ b/images/alpine/3.20/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/3.20/genimg b/images/alpine/3.20/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/3.20/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=v3.20 +exec ../genimg diff --git a/images/alpine/3.21/functions b/images/alpine/3.21/functions new file mode 120000 --- /dev/null +++ b/images/alpine/3.21/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/3.21/genimg b/images/alpine/3.21/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/3.21/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=v3.21 +exec ../genimg diff --git a/images/alpine/3.22/functions b/images/alpine/3.22/functions new file mode 120000 --- /dev/null +++ b/images/alpine/3.22/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/3.22/genimg b/images/alpine/3.22/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/3.22/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=v3.22 +exec ../genimg diff --git a/images/alpine/3.23/functions b/images/alpine/3.23/functions new file mode 120000 --- /dev/null +++ b/images/alpine/3.23/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/3.23/genimg b/images/alpine/3.23/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/3.23/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=v3.23 +exec ../genimg diff --git a/images/alpine/3.24/functions b/images/alpine/3.24/functions new file mode 120000 --- /dev/null +++ b/images/alpine/3.24/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/3.24/genimg b/images/alpine/3.24/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/3.24/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=v3.24 +exec ../genimg diff --git a/images/alpine/edge/functions b/images/alpine/edge/functions new file mode 120000 --- /dev/null +++ b/images/alpine/edge/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/alpine/edge/genimg b/images/alpine/edge/genimg new file mode 100755 --- /dev/null +++ b/images/alpine/edge/genimg @@ -0,0 +1,7 @@ +#!/bin/sh -xeu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=edge +export linux=linux-lts +exec ../genimg diff --git a/images/alpine/functions b/images/alpine/functions new file mode 100644 --- /dev/null +++ b/images/alpine/functions @@ -0,0 +1,69 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo poweroff" +default_arch=x86_64 + +boot() { + if [ "$arch" != "x86_64" ] + then + echo "Unsupported architecture $arch" >&2 + exit 1 + fi + _boot $(cpu_opts x86_64) +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost sudo apk upgrade -U + guest_ssh -p $port build@localhost sudo apk add "$@" +} + +add_repository() { + port=$1 + name=$2 + src=$3 + repo=$(echo $src | cut -d' ' -f1) + key=$(echo $src | cut -d' ' -f2) + keyname=$(echo $src | cut -d' ' -f3) + guest_ssh -p $port build@localhost \ + "curl -s '$key' | sudo tee /etc/apk/keys/'$keyname'" + if [ "${name#@}" = "${name}" ] + then + printf '%s\n' "$repo" \ + | guest_ssh -p $port build@localhost \ + "cat - /etc/apk/repositories | sudo tee /etc/apk/repositories.new" + else + printf '%s %s\n' "$name" "$repo" \ + | guest_ssh -p $port build@localhost \ + "cat - /etc/apk/repositories | sudo tee /etc/apk/repositories.new" + fi + guest_ssh -p $port build@localhost \ + "sudo mv /etc/apk/repositories.new /etc/apk/repositories" +} + +sanity_check() { + echo "Booting..." + cmd_boot x86_64 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl https://builds.sr.ht + echo "Testing apk..." + # repo cache doesn't work in this context + guest_ssh -p 8022 build@localhost \ + sudo sed -i /etc/apk/repositories -e 's/repo-cache.local/dl-2.alpinelinux.org/g' + guest_ssh -p 8022 build@localhost sudo apk update + guest_ssh -p 8022 build@localhost sudo apk upgrade + guest_ssh -p 8022 build@localhost sudo apk add htop + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Testing mercurial..." + guest_ssh -p 8022 build@localhost hg --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo poweroff || true +} diff --git a/images/alpine/genimg b/images/alpine/genimg index f5446ce..689ce7e 100755 --- a/images/alpine/genimg +++ b/images/alpine/genimg @@ -1,39 +1,11 @@ #!/bin/sh -eux -# SPDX-FileCopyrightText: 2017-2026 Drew DeVault -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault # SPDX-License-Identifier: AGPL-3.0-only -self=$(dirname "$(readlink -f "$0")") -cd "$self" - -version=${1:-} -arch="${2:-amd64}" +echo "$release" >/dev/null # fail on -u if release unset +arch="${1:-x86_64}" linux="${linux:-linux-lts}" -case $version in -3.20 | 3.21 | 3.22 | 3.23 | 3.24) - release="v$version" - ;; -edge) - release="edge" - ;; -*) - echo "usage: ${0##*/} <3.20|3.21|3.22|3.23|3.24|edge> [arch]" >&2 - exit 1 - ;; -esac - -case $arch in -amd64) apk_arch=x86_64 ;; -arm64) apk_arch=aarch64 ;; -*) - echo "unsupported architecture $arch" >&2 - exit 1 - ;; -esac - -out="$version/$arch" - cleanup() { # The order here is important if you don't want to hose your mounts sync @@ -44,24 +16,24 @@ cleanup() { umount -f /mnt/run 2>/dev/null || true umount -f /mnt/sys 2>/dev/null || true umount -f /mnt/boot 2>/dev/null || true - umount -f /mnt 2>/dev/null || true + umount -f /mnt 2>/dev/null || true swapoff /dev/nbd0p2 || true qemu-nbd --disconnect /dev/nbd0 || true } -size_gib=24 -mkdir -p "$out" +mkdir -p "$arch" -qemu-img create -f qcow2 -o compat=1.1 "$out"/root.hmi "${size_gib}G" +qemu-img create -f qcow2 "$arch"/root.img.qcow2 24G modprobe nbd max_part=16 -qemu-nbd --connect=/dev/nbd0 "$out"/root.hmi +qemu-nbd --connect=/dev/nbd0 "$arch"/root.img.qcow2 for i in $(seq 1 5); do - sleep "0.$i" + sleep 0.$i partprobe /dev/nbd0 && break done trap cleanup EXIT -if [ "$arch" = "amd64" ]; then +if [ "$arch" == "x86_64" ] || [ "$arch" == "i686" ] +then dd if=/usr/share/syslinux/mbr.bin of=/dev/nbd0 bs=1 count=440 fi sfdisk --no-reread /dev/nbd0 <<EOF @@ -80,17 +52,27 @@ mkdir /mnt/boot mount /dev/nbd0p1 /mnt/boot swapon /dev/nbd0p2 +extra="" +case $release in + 3.23) + extra="!usr-merge-nag" + ;; + edge) + extra="!usr-merge-nag" + ;; +esac + # TODO: Remove bash apk add -U \ - -X "http://dl-cdn.alpinelinux.org/alpine/$release/main/" \ - -X "http://dl-cdn.alpinelinux.org/alpine/$release/community/" \ + -X http://dl-cdn.alpinelinux.org/alpine/$release/main/ \ + -X http://dl-cdn.alpinelinux.org/alpine/$release/community/ \ --allow-untrusted \ - --arch="$apk_arch" \ + --arch="$arch" \ --root=/mnt \ --initdb \ - acct alpine-base alpine-conf alpine-sdk linux-firmware-none "$linux" \ + acct alpine-base alpine-conf alpine-sdk linux-firmware-none $linux \ git mercurial openssh sudo syslinux tzdata gnupg haveged bash curl \ - doas qemu-guest-agent + doas $extra mount --bind /dev /mnt/dev mount --bind /dev/pts /mnt/dev/pts @@ -118,7 +100,8 @@ iface eth0 inet static gateway 10.0.2.2 EOF run_root setup-dns -d example.org 8.8.8.8 9.9.9.9 1.1.1.1 -if [ "$release" = "edge" ]; then +if [ "$release" = "edge" ] +then run_root setup-timezone UTC cat >/mnt/etc/apk/repositories <<EOF http://dl-cdn.alpinelinux.org/alpine/$release/main @@ -135,29 +118,20 @@ fi extlinux -i /mnt/boot -# Alpine uses mdev rather than udev, so create the stable, named virtio-port -# symlink expected by qemu-ga without depending on controller/port numbers. -mkdir -p /mnt/etc/mdev -cat >/mnt/etc/mdev/virtio-port <<'EOF' -#!/bin/sh -name=$(cat "/sys/class/virtio-ports/$MDEV/name") || exit -[ "$name" = org.qemu.guest_agent.0 ] || exit -mkdir -p /dev/virtio-ports -ln -sf "/dev/$MDEV" "/dev/virtio-ports/$name" -EOF -chmod +x /mnt/etc/mdev/virtio-port -echo 'vport.* root:root 0600 @/etc/mdev/virtio-port' >>/mnt/etc/mdev.conf - -for i in ntpd sshd crond haveged qemu-guest-agent; do +for i in ntpd sshd crond haveged +do run_root rc-update add $i default done -for i in hwclock modules sysctl hostname bootmisc loadkmap networking seedrng syslog swap; do +for i in hwclock modules sysctl hostname bootmisc loadkmap networking seedrng syslog swap +do run_root rc-update add $i boot done -for i in devfs dmesg hwdrivers mdev; do +for i in devfs dmesg hwdrivers mdev +do run_root rc-update add $i sysinit done -for i in mount-ro killprocs savecache; do +for i in mount-ro killprocs savecache +do run_root rc-update add $i shutdown done @@ -170,26 +144,22 @@ run_root adduser build kvm run_root adduser build abuild run_root passwd -u build -printf '%s\n' "%wheel ALL=(ALL) NOPASSWD: ALL" >>/mnt/etc/sudoers +printf '%s\n' "%wheel ALL=(ALL) NOPASSWD: ALL" >> /mnt/etc/sudoers rm -f /mnt/etc/motd -printf 'permit nopass :wheel\n' >>/mnt/etc/doas.d/doas.conf - -boot_uuid=$(blkid -s UUID -o value /dev/nbd0p1) -root_uuid=$(blkid -s UUID -o value /dev/nbd0p3) -cmdline="root=UUID=$root_uuid rw modules=sd-mod,usb-storage,ext4 quiet rootfstype=ext4" +printf 'permit nopass :wheel\n' >> /mnt/etc/doas.d/doas.conf cat >/mnt/boot/extlinux.conf <<EOF DEFAULT linux LABEL linux LINUX vmlinuz-$(echo "$linux" | cut -d- -f2-) INITRD initramfs-$(echo "$linux" | cut -d- -f2-) - APPEND $cmdline + APPEND root=/dev/vda3 rw modules=sd-mod,usb-storage,ext4 quiet rootfstype=ext4 EOF cat >>/mnt/etc/fstab <<EOF -UUID=$boot_uuid /boot ext4 rw,relatime,data=ordered 0 0 -/dev/vda2 swap swap defaults 0 0 -UUID=$root_uuid / ext4 rw,relatime,data=ordered 0 0 +/dev/vda1 /boot ext4 rw,relatime,data=ordered 0 0 +/dev/vda2 swap swap defaults 0 0 +/dev/vda3 / ext4 rw,relatime,data=ordered 0 0 EOF mkdir -p /mnt/etc/docker @@ -200,62 +170,17 @@ cat >/mnt/etc/docker/daemon.json <<EOF EOF pkg_version() { - name=$(run_root apk list "$1" | grep installed | cut -d' ' -f1) - echo "${name##"$1"-}" + name=$(run_root apk list $1 | grep installed | cut -d' ' -f1) + echo ${name##$1-} } -run_root apk add "$linux=$(pkg_version "$linux")" +run_root apk add $linux=$(pkg_version $linux) -sync - -# Detach the disk so root.hmi is fully flushed before hashing; disarm cleanup. -cleanup -trap : EXIT - -# --- Hule machine configuration (`config.json`) ------------------------------ -disk_sha=$(sha256sum "$out/root.hmi" | cut -d' ' -f1) -disk_bytes=$(stat -c%s "$out/root.hmi") -virtual_bytes=$((size_gib * 1024 * 1024 * 1024)) -mem_min=$((256 * 1024 * 1024)) -mem_def=$((1024 * 1024 * 1024)) - -cat >"$out/config.json" <<EOF -{ - "schemaVersion": 1, - "kind": "MachineImage", - - "system": { - "os": "linux", - "name": "alpine", - "version": "$version", - "architecture": "$arch" - }, - - "machine": { - "cpu": { "minimum": 1, "default": 2 }, - "ram": { "minimum": $mem_min, "default": $mem_def }, - "boot": [ - { - "protocol": "firmware-disk/bios", - "disk": "root" - } - ], - "access": [ - { "type": "ssh", "port": 22, "user": "build", "auth": "empty-password" }, - { "type": "qga" } - ], - "network": { "mode": "static", "address": "10.0.2.15/24", "gateway": "10.0.2.2" } - }, - - "disks": [ - { - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:$disk_sha", - "virtSize": $virtual_bytes, - "diskSize": $disk_bytes - } - ] -} +cat >/mnt/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht EOF +chown build:build /mnt/home/build/.gitconfig + +sync diff --git a/images/control b/images/control new file mode 100755 --- /dev/null +++ b/images/control @@ -0,0 +1,248 @@ +#!/bin/sh -eu +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +self=$(readlink -f $0) +self=$(dirname "$self") + +if [ -f /etc/image-control.conf ] +then + . /etc/image-control.conf +fi + +base=$1 +cmd=$2 +shift 2 + +if [ ! -d $self/$base ] +then + printf "Image '%s' does not exist\n" "$base" >&2 + exit 1 +fi + +ssh_opts="-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no" +guestport=22 + +guest_ssh() { + ssh $ssh_opts "$@" +} + +cpu_opts() { + if [ "$(uname -m)" = "$1" ] && [ -e /dev/kvm ] + then + printf "%s" "-cpu host -enable-kvm" + return + fi + case "$1" in + aarch64) + printf "%s" "-M virt -cpu cortex-a53" + ;; + x86_64) + printf "%s" "-cpu qemu64" + ;; + ppc64le) + printf "%s" "-cpu power9 -machine pseries" + ;; + *) + printf "Unsupported architecture '%s'\n" "$arch" >&2 + exit 1 + ;; + esac +} + +_docker_boot() { + docker run -d \ + -v "$self/$base":/base:ro \ + --mount type=tmpfs,destination=/var/tmp \ + --device /dev/kvm \ + --cpus=2 \ + -p 127.0.0.1:$port:$port \ + --rm \ + --name "builds_job_${BUILD_JOB_ID:-unknown_$(date +"%s")}" \ + qemu /bin/${qemu:-qemu-system-$arch} \ + -m ${MEMORY:-4096} \ + -smp cpus=2 \ + -net nic,model=virtio -net user,hostfwd=tcp::$port-:$guestport \ + -display none \ + -device virtio-rng-pci \ + -device virtio-balloon \ + -drive file="$wd/$arch/root.img.qcow2",media=disk,snapshot=on,${driveopts:-if=virtio} \ + "$@" > /tmp/docker-$port.id +} + +_qemu_boot() { + ${qemu:-qemu-system-$arch} \ + -pidfile /tmp/qemu-$port.id \ + -m ${MEMORY:-4096} \ + -smp cpus=2 \ + -net nic,model=virtio -net user,hostfwd=tcp:127.0.0.1:$port-:$guestport \ + -display none \ + -device virtio-rng-pci \ + -device virtio-balloon \ + -drive file="$wd/$arch/root.img.qcow2",media=disk,snapshot=on,${driveopts:-if=virtio} \ + "$@" & +} + +_qemu_chroot_boot() { + qemu-chroot \ + -p /tmp/qemu-$port.id \ + -b "$self/$base":/base \ + -b /var/tmp:/var/tmp \ + /bin/${qemu:-qemu-system-$arch} \ + -m ${MEMORY:-4096} \ + -smp cpus=2 \ + -net nic,model=virtio -net user,hostfwd=tcp:127.0.0.1:$port-:$guestport \ + -display none \ + -device virtio-rng-pci \ + -device virtio-balloon \ + -drive file="$wd/$arch/root.img.qcow2",media=disk,snapshot=on,${driveopts:-if=virtio} \ + "$@" & +} + +_qemu_kvm_boot() { + qemu-kvm \ + -pidfile /tmp/qemu-$port.id \ + -m ${MEMORY:-4096} \ + -smp cpus=2 \ + -net nic,model=virtio -net user,hostfwd=tcp:127.0.0.1:$port-:$guestport \ + -display none \ + -device virtio-rng-pci \ + -device virtio-balloon \ + -drive file="$wd/$arch/root.img.qcow2",media=disk,snapshot=on,${driveopts:-if=virtio} \ + "$@" & +} + +_boot() { + if [ "$means" = "docker" ] + then + _docker_boot "$@" + elif [ "$means" = "qemu" ] + then + _qemu_boot "$@" + elif [ "$means" = "qemu-chroot" ] + then + _qemu_chroot_boot "$@" + elif [ "$means" = "qemu-kvm" ] + then + _qemu_kvm_boot "$@" + fi +} + +cmd_boot() { + arch=$1 + shift + + if [ "$arch" = "default" ] + then + arch="$default_arch" + fi + if [ ! -e "$self/$base/$arch/root.img.qcow2" ] + then + printf "Image '%s' is not available for arch '%s'\n" "$base" "$arch" >&2 + exit 1 + fi + + port=$1 + if [ "$#" -gt 1 ] + then + means=$2 + else + means="${default_means:-docker}" + fi + + if [ "$means" = "docker" ] + then + wd="/base" + elif [ "$means" = "qemu" ] + then + wd="$self/$base" + elif [ "$means" = "qemu-chroot" ] + then + wd="/base" + elif [ "$means" = "qemu-kvm" ] + then + wd="$self/$base" + else + printf "Unknown boot mode '%s'\n" "$means" >&2 + exit 1 + fi + + boot +} + +_wait_boot() { + port=$1 + attempts=0 + echo "Waiting for VM to come up..." + while ! guest_ssh -p "$port" build@localhost echo Hello world 2>&1 >/dev/null + do + sleep 5 + attempts=$((attempts + 1)) + if [ "$attempts" -eq 20 ] + then + echo "Giving up." + cmd_cleanup "$port" + exit 1 + fi + echo "Attempt $attempts..." + done +} + +cmd_cleanup() { + port=$1 + # Power off + if [ "$#" -eq 1 ] + then + if [ -e /tmp/docker-$port.id ] + then + cid=$(cat /tmp/docker-$port.id) + guest_ssh -p $port build@localhost $poweroff_cmd || true + sleep 2 + docker kill $cid && sleep 2 || true + rm /tmp/docker-$port.id + fi + if [ -e /tmp/qemu-$port.id ] + then + cid=$(cat /tmp/qemu-$port.id) + guest_ssh -p $port build@localhost $poweroff_cmd || true + sleep 2 + kill $cid || true + rm -f /tmp/qemu-$port.id + fi + fi +} + +if ! [ -e "$self/$base/functions" ] +then + printf "Missing base image functions '%s'\n" "$base" >&2 + exit 1 +fi + +. $self/$base/functions + +case "$cmd" in + boot) + cmd_boot "$@" + ;; + cleanup) + cmd_cleanup "$@" + ;; + sanity-check) + sanity_check "$@" + ;; + install) + install "$@" + ;; + add-repo) + add_repository "$@" + ;; + ssh) + port=$1 + shift + guest_ssh -p "$port" build@localhost "$@" + ;; + *) + printf "Unknown command '%s'\n" "$cmd" >&2 + exit 1 + ;; +esac diff --git a/images/debian/bookworm/functions b/images/debian/bookworm/functions new file mode 120000 --- /dev/null +++ b/images/debian/bookworm/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/debian/bookworm/genimg b/images/debian/bookworm/genimg new file mode 100755 --- /dev/null +++ b/images/debian/bookworm/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=bookworm +exec ../genimg "$@" diff --git a/images/debian/forky/functions b/images/debian/forky/functions new file mode 120000 --- /dev/null +++ b/images/debian/forky/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/debian/forky/genimg b/images/debian/forky/genimg new file mode 100755 --- /dev/null +++ b/images/debian/forky/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=forky +exec ../genimg "$@" diff --git a/images/debian/functions b/images/debian/functions new file mode 100644 --- /dev/null +++ b/images/debian/functions @@ -0,0 +1,106 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo systemctl poweroff" +default_arch=amd64 + +boot() { + case "$arch" in + amd64) + qemu=qemu-system-x86_64 + _boot $(cpu_opts x86_64) + ;; + arm64) + driveopts="id=root,if=none" + qemu=qemu-system-aarch64 + _boot \ + $(cpu_opts aarch64) \ + -device virtio-blk-pci,drive=root \ + -kernel "$wd/$arch/vmlinuz" \ + -initrd "$wd/$arch/initrd.img" \ + -append "root=/dev/vda3" + ;; + ppc64el) + driveopts="id=root,if=none" + qemu=qemu-system-ppc64 + _boot \ + $(cpu_opts ppc64le) \ + -device virtio-blk-pci,drive=root \ + -kernel "$wd/$arch/vmlinux" \ + -initrd "$wd/$arch/initrd.img" \ + -append "root=/dev/vda3" + ;; + *) + echo "Unsupported architecture $arch" >&2 + exit 1 + ;; + esac +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \ + apt-get update -y + guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \ + apt-get install -y "$@" +} + +add_repository() { + port=$1 + name=$2 + src=$3 + repo=$(echo $src | cut -d' ' -f1) + distro=$(echo $src | cut -d' ' -f2) + cmpnt=$(echo $src | cut -d' ' -f3) + key=$(echo $src | cut -d' ' -f4) + signed_by="" + if [ "$key" != "" ] + then + # Import the GPG key into a user trustdb + guest_ssh -p $port build@localhost sudo \ + gpg \ + --keyserver hkp://keyserver.ubuntu.com:80 \ + --recv-keys $key + + guest_ssh -p $port build@localhost sudo \ + mkdir -pm 0755 /etc/apt/keyrings + + # Export the GPG key to Apt's key directory + guest_ssh -p $port build@localhost sudo \ + gpg \ + --output /etc/apt/keyrings/$name.gpg \ + --export $key + + signed_by="[signed-by=/etc/apt/keyrings/$name.gpg]" + fi + printf 'deb %s %s %s %s\n' "$signed_by" "$repo" "$distro" "$cmpnt" \ + | guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list.d/$name.list + printf 'deb-src %s %s %s %s\n' "$signed_by" "$repo" "$distro" "$cmpnt" \ + | guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list.d/$name.list + guest_ssh -p "$port" build@localhost sudo apt-get update +} + +sanity_check() { + arch=$1 + shift + + echo "Booting..." + cmd_boot "$arch" 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing apt..." + guest_ssh -p 8022 build@localhost sudo apt-get update + install 8022 curl + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl https://builds.sr.ht + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Testing mercurial..." + guest_ssh -p 8022 build@localhost hg --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo systemctl poweroff || true +} diff --git a/images/debian/genimg b/images/debian/genimg index 2dedba5..9e1677b 100755 --- a/images/debian/genimg +++ b/images/debian/genimg @@ -1,42 +1,29 @@ #!/bin/sh -eux -# SPDX-FileCopyrightText: 2017-2026 Drew DeVault -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault # SPDX-License-Identifier: AGPL-3.0-only -self=$(dirname "$(readlink -f "$0")") -cd "$self" - -release=${1:-} -arch=${2:-amd64} - -case $release in -bookworm | forky | sid | trixie) ;; -*) - echo "usage: ${0##*/} <bookworm|forky|sid|trixie> [arch]" >&2 - exit 1 - ;; -esac - +echo "$release" >/dev/null # fail on -u if release unset +arch=${1:-amd64} case $arch in -amd64) - darch=amd64 - iface=ens3 - kpkg=linux-image-amd64 - ;; -arm64) - darch=arm64 - iface=enp0s1 - kpkg=linux-image-arm64 - ;; -ppc64le) - darch=ppc64el - iface=enp0s0 - kpkg=linux-image-powerpc64le - ;; -*) - echo "unsupported architecture $arch" - exit 1 - ;; + amd64) + iface=ens3 + qarch=x86_64 + kpkg=linux-image-amd64 + ;; + arm64) + iface=enp0s1 + qarch=aarch64 + kpkg=linux-image-arm64 + ;; + ppc64el) + iface=enp0s0 + qarch=ppc64le + kpkg=linux-image-powerpc64le + ;; + *) + echo "unsupported architecture $arch" + exit 1 + ;; esac cleanup() { @@ -48,28 +35,24 @@ cleanup() { umount /mnt/proc 2>/dev/null || true umount /mnt/run 2>/dev/null || true umount /mnt/sys 2>/dev/null || true - umount /mnt/boot 2>/dev/null || true - umount /mnt 2>/dev/null || true + umount /mnt/boot 2>/dev/null || true + umount /mnt 2>/dev/null || true qemu-nbd --disconnect /dev/nbd0 || true } -out="$release/$arch" -size_gib=32 -mkdir -p "$out" +mkdir -p "$arch" -# .hmi (Hule Machine Image): plain qcow2 restricted to a feature subset that -# materializes losslessly to raw (no internal snapshots/bitmaps/encryption). -# Base image = chain root, so no backing. Never `qemu-img snapshot` it. -qemu-img create -f qcow2 -o compat=1.1 "$out/root.hmi" "${size_gib}G" +qemu-img create -f qcow2 $arch/root.img.qcow2 32G modprobe nbd max_part=16 -qemu-nbd --connect=/dev/nbd0 "$out/root.hmi" +qemu-nbd --connect=/dev/nbd0 $arch/root.img.qcow2 for i in $(seq 1 5); do - sleep "0.$i" + sleep 0.$i partprobe /dev/nbd0 && break done trap cleanup EXIT -if [ "$arch" = "amd64" ]; then +if [ "$arch" = "amd64" ] +then dd if=/usr/lib/syslinux/mbr/mbr.bin of=/dev/nbd0 bs=1 count=440 fi @@ -87,10 +70,11 @@ mount /dev/nbd0p3 /mnt mkdir /mnt/boot mount /dev/nbd0p1 /mnt/boot -if [ "$arch" = "amd64" ]; then - debootstrap --include=gnupg2 --arch="$darch" "$release" /mnt +if [ "$arch" = "amd64" ] +then + debootstrap --include=gnupg2 --arch=$arch $release /mnt else - ./qemu-debootstrap --include=gnupg2 --arch="$darch" "$release" /mnt + ../qemu-debootstrap --include=gnupg2 --arch=$arch $release /mnt fi mount --bind /dev /mnt/dev @@ -109,7 +93,7 @@ run_root() { echo 'nameserver 8.8.8.8' >/mnt/etc/resolv.conf echo 'nameserver 9.9.9.9' >>/mnt/etc/resolv.conf echo 'nameserver 1.1.1.1' >>/mnt/etc/resolv.conf -cat >/mnt/etc/network/interfaces <<EOF +cat > /mnt/etc/network/interfaces <<EOF auto lo iface lo inet loopback @@ -120,31 +104,30 @@ iface $iface inet static netmask 255.255.255.0 gateway 10.0.2.2 EOF -echo build >/mnt/etc/hostname -cat >/mnt/etc/hosts <<EOF +echo build > /mnt/etc/hostname +cat > /mnt/etc/hosts <<EOF 127.0.0.1 build localhost EOF -echo 'APT::Install-Recommends "False";' >/mnt/etc/apt/apt.conf.d/60recommends +echo 'APT::Install-Recommends "False";' > /mnt/etc/apt/apt.conf.d/60recommends run_root apt-get update run_root apt-get -y install locales run_root apt-get -y install $kpkg run_root apt-get -y install build-essential git mercurial ssh sudo \ gnupg dirmngr ca-certificates apt-transport-https curl dbus \ - systemd-timesyncd ncurses-term qemu-guest-agent + systemd-timesyncd ncurses-term run_root ln -sf /usr/share/zoneinfo/UTC /etc/localtime run_root systemctl enable systemd-timesyncd.service run_root useradd -mG sudo build run_root passwd -d build -echo '%sudo ALL=(ALL) NOPASSWD: ALL' >>/mnt/etc/sudoers +echo '%sudo ALL=(ALL) NOPASSWD: ALL' >> /mnt/etc/sudoers -echo "PermitEmptyPasswords yes" >>/mnt/etc/ssh/sshd_config -echo ssh >>/mnt/etc/securetty +echo "PermitEmptyPasswords yes" >> /mnt/etc/ssh/sshd_config +echo ssh >> /mnt/etc/securetty run_root systemctl enable ssh -run_root systemctl enable qemu-guest-agent # Prevent docker from mucking up networking mkdir -p /mnt/etc/docker @@ -156,145 +139,43 @@ EOF run_root update-initramfs -u -kernel_path= -for candidate in /mnt/boot/vmlinuz-*; do - [ -e "$candidate" ] || continue - kernel_path=$candidate - break -done -[ -n "$kernel_path" ] -linuxver=${kernel_path##*/vmlinuz-} - -# Reference partitions by PARTUUID so boot survives whatever the VMM names the -# disk. cmdline is canonical: identical for every boot protocol (extlinux append -# here, -append on the direct path) -- see docs/boot-protocol.md. -boot_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p1) -swap_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p2) -root_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p3) -cmdline="root=PARTUUID=$root_partuuid rw quiet" +linuxver=$(ls /mnt/boot | grep vmlinuz | cut -d- -f2-) cat >>/mnt/etc/fstab <<EOF -PARTUUID=$boot_partuuid /boot ext4 rw,relatime,data=ordered 0 0 -PARTUUID=$swap_partuuid swap swap defaults 0 0 -PARTUUID=$root_partuuid / ext4 rw,relatime,data=ordered 0 0 +/dev/vda1 /boot ext4 rw,relatime,data=ordered 0 0 +/dev/vda2 swap swap defaults 0 0 +/dev/vda3 / ext4 rw,relatime,data=ordered 0 0 +EOF + +cat >/mnt/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht EOF +run_root chown build:build /home/build/.gitconfig -# Boot setup: amd64 self-boots via extlinux (firmware-disk/bios); other arches -# have no in-image bootloader, the VMM boots the extracted kernel directly. -case "$arch" in -amd64) - run_root apt-get -y install extlinux - extlinux -i /mnt/boot +# Boot setup +case "$arch" in + amd64) + run_root apt-get -y install extlinux + extlinux -i /mnt/boot - cat >/mnt/boot/extlinux.conf <<-EOF + cat >/mnt/boot/extlinux.conf <<-EOF default debian label debian linux vmlinuz-$linuxver initrd initrd.img-$linuxver - append $cmdline - EOF - ;; -arm64) - cp /mnt/boot/vmlinuz-* "$out/vmlinuz" - cp /mnt/boot/initrd.img-* "$out/initrd" - ;; -ppc64le) - cp /mnt/boot/vmlinux-* "$out/vmlinux" - cp /mnt/boot/initrd.img-* "$out/initrd" - ;; + append root=/dev/vda3 rw quiet + EOF + ;; + arm64) + cp /mnt/boot/vmlinuz-* $arch/vmlinuz + cp /mnt/boot/initrd.img-* $arch/initrd.img + ;; + ppc64el) + cp /mnt/boot/vmlinux-* $arch/vmlinux + cp /mnt/boot/initrd.img-* $arch/initrd.img + ;; esac sync - -# Detach the disk so root.hmi is fully flushed before hashing; disarm cleanup. -cleanup -trap : EXIT - -# --- Hule machine configuration (`config.json`) ------------------------------ -disk_sha=$(sha256sum "$out/root.hmi" | cut -d' ' -f1) -disk_bytes=$(stat -c%s "$out/root.hmi") -virtual_bytes=$((size_gib * 1024 * 1024 * 1024)) -mem_min=$((256 * 1024 * 1024)) -mem_def=$((1024 * 1024 * 1024)) - -case "$arch" in -amd64) - # Legacy BIOS: extlinux in an MBR disk, booted by the VMM's BIOS firmware. - protocols=$( - cat <<JSON - { - "protocol": "firmware-disk/bios", - "disk": "root" - } -JSON - ) - ;; -arm64) - kernel_sha=$(sha256sum "$out/vmlinuz" | cut -d' ' -f1) - initrd_sha=$(sha256sum "$out/initrd" | cut -d' ' -f1) - protocols=$( - cat <<JSON - { - "protocol": "linux/direct", - "disk": "root", - "kernel": { "path": "vmlinuz", "digest": "sha256:$kernel_sha" }, - "initrd": { "path": "initrd", "digest": "sha256:$initrd_sha" }, - "cmdline": "$cmdline" - } -JSON - ) - ;; -ppc64le) - kernel_sha=$(sha256sum "$out/vmlinux" | cut -d' ' -f1) - initrd_sha=$(sha256sum "$out/initrd" | cut -d' ' -f1) - protocols=$( - cat <<JSON - { - "protocol": "linux/direct", - "disk": "root", - "kernel": { "path": "vmlinux", "digest": "sha256:$kernel_sha" }, - "initrd": { "path": "initrd", "digest": "sha256:$initrd_sha" }, - "cmdline": "$cmdline" - } -JSON - ) - ;; -esac - -cat >"$out/config.json" <<EOF -{ - "schemaVersion": 1, - "kind": "MachineImage", - - "system": { - "os": "linux", - "name": "debian", - "version": "$release", - "architecture": "$arch" - }, - - "machine": { - "cpu": { "minimum": 1, "default": 2 }, - "ram": { "minimum": $mem_min, "default": $mem_def }, - "boot": [ -$protocols - ], - "access": [ - { "type": "ssh", "port": 22, "user": "build", "auth": "empty-password" }, - { "type": "qga" } - ], - "network": { "mode": "static", "address": "10.0.2.15/24", "gateway": "10.0.2.2" } - }, - - "disks": [ - { - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:$disk_sha", - "virtSize": $virtual_bytes, - "diskSize": $disk_bytes - } - ] -} -EOF diff --git a/images/debian/sid/functions b/images/debian/sid/functions new file mode 120000 --- /dev/null +++ b/images/debian/sid/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/debian/sid/genimg b/images/debian/sid/genimg new file mode 100755 --- /dev/null +++ b/images/debian/sid/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=sid +exec ../genimg "$@" diff --git a/images/debian/trixie/functions b/images/debian/trixie/functions new file mode 120000 --- /dev/null +++ b/images/debian/trixie/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/debian/trixie/genimg b/images/debian/trixie/genimg new file mode 100755 --- /dev/null +++ b/images/debian/trixie/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=trixie +exec ../genimg "$@" diff --git a/images/fedora/42/functions b/images/fedora/42/functions new file mode 120000 --- /dev/null +++ b/images/fedora/42/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/fedora/42/genimg b/images/fedora/42/genimg new file mode 100755 --- /dev/null +++ b/images/fedora/42/genimg @@ -0,0 +1,6 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=42 +exec ../genimg "$*" diff --git a/images/fedora/43/functions b/images/fedora/43/functions new file mode 120000 --- /dev/null +++ b/images/fedora/43/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/fedora/43/genimg b/images/fedora/43/genimg new file mode 100755 --- /dev/null +++ b/images/fedora/43/genimg @@ -0,0 +1,6 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=43 +exec ../genimg "$*" diff --git a/images/fedora/44/functions b/images/fedora/44/functions new file mode 120000 --- /dev/null +++ b/images/fedora/44/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/fedora/44/genimg b/images/fedora/44/genimg new file mode 100755 --- /dev/null +++ b/images/fedora/44/genimg @@ -0,0 +1,6 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=44 +exec ../genimg "$*" diff --git a/images/fedora/functions b/images/fedora/functions new file mode 100644 --- /dev/null +++ b/images/fedora/functions @@ -0,0 +1,52 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo systemctl poweroff" +default_arch=x86_64 + +boot() { + if [ "$arch" != "x86_64" ] + then + echo "Unsupported architecture $arch" >&2 + exit 1 + fi + _boot $(cpu_opts x86_64) +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost sudo dnf -y install "$@" +} + +add_repository() { + port=$1 + name=$2 + url=$3 + guest_ssh -p $port build@localhost sudo dnf config-manager \ + addrepo --from-repofile="$url" + guest_ssh -p $port build@localhost sudo dnf config-manager \ + setopt "$name.enabled"=1 + guest_ssh -p $port build@localhost sudo dnf makecache +} + +sanity_check() { + echo "Booting..." + cmd_boot x86_64 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl https://builds.sr.ht + echo "Testing dnf..." + guest_ssh -p 8022 build@localhost sudo dnf -y upgrade + guest_ssh -p 8022 build@localhost sudo dnf -y install htop + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Testing mercurial..." + guest_ssh -p 8022 build@localhost hg --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo systemctl poweroff || true +} diff --git a/images/fedora/genimg b/images/fedora/genimg index 8215ec5..ff62e6c 100755 --- a/images/fedora/genimg +++ b/images/fedora/genimg @@ -1,34 +1,20 @@ #!/bin/sh -eux -# SPDX-FileCopyrightText: 2017-2026 Drew DeVault -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault # SPDX-License-Identifier: AGPL-3.0-only # Network Block Device used to interact with the QCOW2 image. NBD_DEVICE=/dev/nbd0 -self=$(dirname "$(readlink -f "$0")") -cd "$self" - -release=${1:-} -arch=${2:-amd64} - -case $release in -42 | 43 | 44) ;; -*) - echo "usage: ${0##*/} <42|43|44> [arch]" >&2 - exit 1 - ;; -esac - +echo "$release" >/dev/null # fail on -u if release unset +arch=${1:-x86_64} case $arch in -amd64) - fedora_arch=x86_64 - iface=ens3 - ;; -*) - echo "unsupported architecture $arch" - exit 1 - ;; + x86_64) + iface=ens3 + ;; + *) + echo "unsupported architecture $arch" + exit 1 + ;; esac cleanup() { @@ -38,7 +24,6 @@ cleanup() { umount /mnt/dev 2>/dev/null || true umount /mnt/proc 2>/dev/null || true umount /mnt/run 2>/dev/null || true - umount /mnt/sys/firmware 2>/dev/null || true umount /mnt/sys 2>/dev/null || true umount /mnt/boot 2>/dev/null || true umount /mnt 2>/dev/null || true @@ -51,16 +36,11 @@ run_root() { sh -c "$*" } -out="$release/$arch" -size_gib=24 -mkdir -p "$out" +mkdir -p "$arch" -# .hmi (Hule Machine Image): plain qcow2 restricted to a feature subset that -# materializes losslessly to raw (no internal snapshots/bitmaps/encryption). -# Base image = chain root, so no backing. Never `qemu-img snapshot` it. -qemu-img create -f qcow2 -o compat=1.1 "$out/root.hmi" "${size_gib}G" +qemu-img create -f qcow2 "$arch/root.img.qcow2" 24G modprobe nbd max_part=16 -qemu-nbd --connect=$NBD_DEVICE "$out/root.hmi" +qemu-nbd --connect=$NBD_DEVICE "$arch/root.img.qcow2" trap cleanup EXIT # Looks like qemu-nbd is non-blocking. Wait one second to make sure $NBD_DEVICE @@ -103,15 +83,6 @@ mount --bind /proc /mnt/proc mount --bind /run /mnt/run mount --bind /sys /mnt/sys -# This is a BIOS-only image (no ESP), but the build host may boot via UEFI. Since -# /sys is bind-mounted from the host, grub2-mkconfig's 10_linux sees the host's -# /sys/firmware/efi and probes the nonexistent /boot/efi ("failed to get canonical -# path of /boot/efi/"). Shadow /sys/firmware with an empty tmpfs so the chroot's -# grub sees a BIOS platform regardless of how the host booted. Make the bind -# private first so the tmpfs doesn't propagate back and hide firmware on the host. -mount --make-rprivate /mnt/sys -mount -t tmpfs tmpfs /mnt/sys/firmware - # Remove systemd-networkd symlink, which is useless in our chroot. rm -f /mnt/etc/resolv.conf @@ -127,8 +98,8 @@ Address=10.0.2.15/24 Gateway=10.0.2.2 EOF -echo build >/mnt/etc/hostname -cat >/mnt/etc/hosts <<EOF +echo build > /mnt/etc/hostname +cat > /mnt/etc/hosts <<EOF 127.0.0.1 localhost 127.0.0.1 build EOF @@ -140,24 +111,16 @@ run_root systemctl enable systemd-timesyncd.service run_root dnf -y \ --releasever="$release" \ - install \ - @development-tools git mercurial openssh-server sudo kernel grub2 \ - qemu-guest-agent + install \ + @development-tools git mercurial openssh-server sudo kernel grub2 run_root dnf clean all # Add support for virtio block devices at boot time. -cat >/mnt/etc/dracut.conf.d/virtio-blk.conf <<EOF +cat > /mnt/etc/dracut.conf.d/virtio-blk.conf <<EOF add_drivers="virtio-blk" EOF -kernel_path= -for candidate in /mnt/boot/vmlinuz-*."$fedora_arch"; do - [ -e "$candidate" ] || continue - kernel_path=$candidate - break -done -[ -n "$kernel_path" ] -kernel_version=${kernel_path##*/vmlinuz-} +kernel_version=$(ls /mnt/boot | grep "vmlinuz.*.$arch" | cut -d- -f2-) run_root dracut --force --kver "$kernel_version" run_root grub2-install --target=i386-pc $NBD_DEVICE @@ -174,7 +137,6 @@ echo '%sudo ALL=(ALL) NOPASSWD: ALL' >>/mnt/etc/sudoers echo "PermitEmptyPasswords yes" >>/mnt/etc/ssh/sshd_config echo ssh >>/mnt/etc/securetty run_root systemctl enable sshd -run_root systemctl enable qemu-guest-agent boot_uuid=$(blkid --match-tag UUID --output value ${NBD_DEVICE}p1) swap_uuid=$(blkid --match-tag UUID --output value ${NBD_DEVICE}p2) @@ -185,58 +147,11 @@ UUID=$swap_uuid swap swap defaults 0 0 UUID=$root_uuid / ext4 rw,relatime,data=ordered 0 0 EOF -sync - -# Detach the disk so root.hmi is fully flushed before hashing; disarm cleanup. -cleanup -trap : EXIT - -# --- Hule machine configuration (`config.json`) ------------------------------ -# amd64 only, self-booting via grub2 (BIOS). No boot.cmdline: grub owns it and -# firmware-disk boot takes no cmdline from the VMM. -disk_sha=$(sha256sum "$out/root.hmi" | cut -d' ' -f1) -disk_bytes=$(stat -c%s "$out/root.hmi") -virtual_bytes=$((size_gib * 1024 * 1024 * 1024)) -mem_min=$((256 * 1024 * 1024)) -mem_def=$((1024 * 1024 * 1024)) - -cat >"$out/config.json" <<EOF -{ - "schemaVersion": 1, - "kind": "MachineImage", - - "system": { - "os": "linux", - "name": "fedora", - "version": "$release", - "architecture": "$arch" - }, - - "machine": { - "cpu": { "minimum": 1, "default": 2 }, - "ram": { "minimum": $mem_min, "default": $mem_def }, - "boot": [ - { - "protocol": "firmware-disk/bios", - "disk": "root" - } - ], - "access": [ - { "type": "ssh", "port": 22, "user": "build", "auth": "empty-password" }, - { "type": "qga" } - ], - "network": { "mode": "static", "address": "10.0.2.15/24", "gateway": "10.0.2.2" } - }, - - "disks": [ - { - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:$disk_sha", - "virtSize": $virtual_bytes, - "diskSize": $disk_bytes - } - ] -} +cat >/mnt/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht EOF +chown build:build /mnt/home/build/.gitconfig + +sync diff --git a/images/freebsd/14.x/functions b/images/freebsd/14.x/functions new file mode 120000 --- /dev/null +++ b/images/freebsd/14.x/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/freebsd/14.x/genimg b/images/freebsd/14.x/genimg new file mode 100755 --- /dev/null +++ b/images/freebsd/14.x/genimg @@ -0,0 +1,6 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release="14.4-RELEASE" +exec ../genimg "$@" diff --git a/images/freebsd/15.x/functions b/images/freebsd/15.x/functions new file mode 120000 --- /dev/null +++ b/images/freebsd/15.x/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/freebsd/15.x/genimg b/images/freebsd/15.x/genimg new file mode 100755 --- /dev/null +++ b/images/freebsd/15.x/genimg @@ -0,0 +1,7 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release="15.1-RELEASE" +export repo="FreeBSD-ports" +exec ../genimg "$@" diff --git a/images/freebsd/current/functions b/images/freebsd/current/functions new file mode 100644 --- /dev/null +++ b/images/freebsd/current/functions @@ -0,0 +1,43 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo poweroff" +default_arch=amd64 + +boot() { + if [ "$arch" != "amd64" ] + then + echo "Unsupported architecture $arch" >&2 + exit 1 + fi + qemu=qemu-system-x86_64 + _boot $(cpu_opts x86_64) +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost \ + "sudo pkg update && sudo pkg upgrade -y && sudo pkg install -y $@" +} + +sanity_check() { + echo "Booting..." + cmd_boot amd64 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + sleep 20 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl http://builds.sr.ht + echo "Testing pkg..." + guest_ssh -p 8022 build@localhost sudo pkg update + guest_ssh -p 8022 build@localhost sudo pkg upgrade -y + guest_ssh -p 8022 build@localhost sudo pkg install -y htop + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo poweroff || true +} diff --git a/images/freebsd/current/genimg b/images/freebsd/current/genimg new file mode 100755 --- /dev/null +++ b/images/freebsd/current/genimg @@ -0,0 +1,6 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release="16.0" +exec ../genpkgimg "$@" diff --git a/images/freebsd/functions b/images/freebsd/functions new file mode 100644 --- /dev/null +++ b/images/freebsd/functions @@ -0,0 +1,43 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo poweroff" +default_arch=amd64 + +boot() { + if [ "$arch" != "amd64" ] + then + echo "Unsupported architecture $arch" >&2 + exit 1 + fi + qemu=qemu-system-x86_64 + _boot $(cpu_opts x86_64) +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost \ + "sudo pkg update && sudo pkg upgrade -y && sudo pkg install -y $@" +} + +sanity_check() { + echo "Booting..." + cmd_boot amd64 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + sleep 20 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl http://builds.sr.ht + echo "Testing pkg..." + guest_ssh -p 8022 build@localhost sudo pkg update + guest_ssh -p 8022 build@localhost sudo pkg upgrade -y + guest_ssh -p 8022 build@localhost sudo pkg install -y htop + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo poweroff || true +} diff --git a/images/freebsd/genimg b/images/freebsd/genimg index 08a258c..6e86c53 100755 --- a/images/freebsd/genimg +++ b/images/freebsd/genimg @@ -1,250 +1,114 @@ #!/bin/sh -eux -# SPDX-FileCopyrightText: 2017-2026 Drew DeVault -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault # SPDX-License-Identifier: AGPL-3.0-only -self=$(dirname "$(readlink -f "$0")") -cd "$self" - -with_ports=false - -while [ $# -gt 0 ]; do - case $1 in - --with-ports) - with_ports=true - shift - ;; - --no-with-ports) - with_ports=false - shift - ;; - --) - shift - break - ;; - -*) - echo "Unknown option $1" >&2 - exit 1 - ;; - *) - break - ;; - esac -done +echo "$release" >/dev/null # fail on -u if unset +arch="${1:-amd64}" +: ${repo:=FreeBSD} + +dist_base="https://download.freebsd.org/ftp/releases/$arch/$release" -version=${1:-} -arch="${2:-amd64}" - -case $version in -14.x) - release="14.4-RELEASE" - ;; -15.x) - release="15.1-RELEASE" - ;; -current) - release="16.0" - ;; -*) - echo "usage: ${0##*/} <14.x|15.x|current> [arch]" >&2 - exit 1 - ;; -esac - -rel=${release%%.*} -out="$version/$arch" -rootfs=disk -reposdir=$(pwd)/$rootfs/usr/local/etc/pkg/repos - -export ABI="FreeBSD:$rel:$arch" -export IGNORE_OSVERSION=yes +dist_files="kernel.txz base.txz base-dbg.txz" +dist_dir="/usr/freebsd-dist/$arch/$release" + +mkdir -p "$dist_dir" +for f in $dist_files +do + fetch -m -o "$dist_dir/$f" "$dist_base/$f" +done cleanup() { - umount "$rootfs"/usr/share/keys/pkg 2>/dev/null || true - chflags -R noschg "$rootfs" || true - rm -rf "$rootfs" disk.img || true + sync || true + umount /mnt/dev || true + umount /mnt || true + mdconfig -du md0 || true } trap cleanup EXIT -rm -rf "$rootfs" disk.img -mkdir -p "$rootfs" -mkdir -p "$reposdir" +rm -f disk.img +truncate -s 8G disk.img +mdconfig -a -t vnode -f disk.img -u md0 +gpart create -s gpt /dev/md0 +gpart add -t freebsd-boot -l bootfs -b 40 -s 512K md0 +gpart bootcode -b /boot/pmbr -p /boot/gptboot -i 1 md0 +gpart add -t freebsd-ufs -l rootfs -b 1M md0 +newfs -U /dev/md0p2 -# Package repository used both to install the base (on -CURRENT) and to add -# tooling below. ${ABI} is expanded by pkg, not the shell. -cat >"$reposdir"/FreeBSD.conf <<EOF -FreeBSD: { - url: pkg+http://pkg.FreeBSD.org/\$\{ABI\}/latest - enabled: yes - mirror_type: srv - signature_type: fingerprint -} -EOF +mount /dev/md0p2 /mnt -case $version in +mkdir -p /mnt/dev +mount -t devfs devfs /mnt/dev -current) - # -CURRENT has no release tarballs; assemble the base from pkg base. - cat >>"$reposdir"/FreeBSD.conf <<EOF -FreeBSD-base: { - url: pkg+http://pkg.FreeBSD.org/\$\{ABI\}/base_latest - enabled: yes - mirror_type: srv - signature_type: fingerprint -} -EOF - # The base is not installed yet, so borrow the host's signing keys for - # the first fetch. - mkdir -p "$rootfs"/usr/share/keys/pkg - mount -t nullfs /usr/share/keys/pkg "$rootfs"/usr/share/keys/pkg - pkg -C /dev/null -R "$reposdir" -r "$rootfs" update - umount "$rootfs"/usr/share/keys/pkg - # XXX replace by group FreeBSD-base the day it is implemented :D - pkg -C /dev/null -R "$reposdir" -r "$rootfs" rquery -g "%n" "FreeBSD*" | - grep -vE "(lib32|dbg|kernel|src|tests)" | - xargs pkg -C /dev/null -R "$reposdir" -r "$rootfs" install -y - if pkg -C /dev/null -R "$reposdir" -r "$rootfs" install -y FreeBSD-kernel-generic-nodebug; then - echo "kernel=kernel.GENERIC-NODEBUG" >"$rootfs"/boot/loader.conf - else - pkg -C /dev/null -R "$reposdir" -r "$rootfs" install -y FreeBSD-kernel-generic - fi - ;; - -*) - # RELEASE: extract the published distribution tarballs into the tree. - dist_base="https://download.freebsd.org/ftp/releases/$arch/$release" - dist_files="kernel.txz base.txz" - dist_dir="/usr/freebsd-dist/$arch/$release" - - mkdir -p "$dist_dir" - for f in $dist_files; do - fetch -m -o "$dist_dir/$f" "$dist_base/$f" - done - for f in $dist_files; do - tar -C "$rootfs" -xJf "$dist_dir/$f" - done - - # Apply security patches (only defined for -RELEASE). - if [ "${release%-RELEASE}" != "$release" ]; then - env PAGER=true /usr/sbin/freebsd-update \ - -b "$rootfs" \ - --currently-running "$release" \ - --not-running-from-cron -F \ - fetch install - fi - ;; - -esac - -# --- Common: tooling, guest configuration, image assembly. --- -# pkg runs on the host against the alternate root, so it uses the host's -# resolver; the guest resolv.conf written below is purely for runtime. -pkg -C /dev/null -R "$reposdir" -r "$rootfs" update -pkg -C /dev/null -R "$reposdir" -r "$rootfs" install -y \ - pkg git-lite mercurial sudo curl qemu-guest-agent -pkg -C /dev/null -R "$reposdir" -r "$rootfs" clean -ay - -if [ "$with_ports" = true ]; then - git clone https://github.com/freebsd/freebsd-ports "$rootfs"/usr/ports \ - --depth=1 --single-branch -fi +for f in $dist_files +do + tar -C /mnt -xJf "$dist_dir/$f" +done -echo "/dev/gpt/rootfs / ufs rw,noatime 1 1" >"$rootfs"/etc/fstab -touch "$rootfs"/firstboot -echo 'autoboot_delay="-1"' >>"$rootfs"/boot/loader.conf +echo "/dev/gpt/rootfs / ufs rw,noatime 1 1" >/mnt/etc/fstab +touch /mnt/firstboot +echo 'autoboot_delay="-1"' >>/mnt/boot/loader.conf -cat >>"$rootfs"/etc/rc.conf <<EOF +cat >>/mnt/etc/rc.conf <<EOF ntpd_enable=YES sshd_enable=YES growfs_enable=YES -qemu_guest_agent_enable=YES hostname="build" ifconfig_DEFAULT="inet 10.0.2.15 netmask 255.255.255.0" defaultrouter="10.0.2.2" EOF +echo "nameserver 8.8.8.8" >/mnt/etc/resolv.conf +echo "nameserver 9.9.9.9" >>/mnt/etc/resolv.conf +echo "nameserver 1.1.1.1" >>/mnt/etc/resolv.conf +tzsetup -s -C /mnt UTC -cat >"$rootfs"/etc/resolv.conf <<EOF -nameserver 8.8.8.8 -nameserver 9.9.9.9 -nameserver 1.1.1.1 -EOF -tzsetup -s -C "$rootfs" UTC - -cat >>"$rootfs"/etc/ssh/sshd_config <<EOF +cat >>/mnt/etc/ssh/sshd_config <<EOF PermitRootLogin yes PasswordAuthentication yes PermitEmptyPasswords yes UsePAM no EOF -pw -R "$rootfs" groupadd sudo -pw -R "$rootfs" useradd -n build -u 1000 -s /bin/sh -m -w none -G sudo -echo "%sudo ALL=(ALL) NOPASSWD: ALL" >>"$rootfs"/usr/local/etc/sudoers - -# Build the UFS image straight from the directory tree, then wrap it in a -# bootable GPT qcow2 -- no md(4), mount or raw->qcow2 conversion needed. -makefs -s 8g -B little -o label=rootfs -o version=2 -o softupdates=1 disk.img "$rootfs" -mkdir -p "$out" -# .hmi (Hule Machine Image): mkimg emits a plain qcow2; keep it snapshot-free so -# it materializes losslessly to raw. Base image = chain root, no backing. -size_gib=16 -mkimg -s gpt \ - -b "$rootfs"/boot/pmbr \ - -C "${size_gib}G" \ - -p freebsd-boot:="$rootfs"/boot/gptboot \ - -p freebsd-ufs/rootfs:=disk.img \ - -f qcow2 \ - -o "$out"/root.hmi +mkdir -p /mnt/usr/local/etc/pkg/repos/ +cat >/mnt/usr/local/etc/pkg/repos/FreeBSD.conf <<EOF +$repo: { + url: pkg+http://pkg.FreeBSD.org/\$\{ABI\}/latest + enabled: yes +} +EOF + +# freebsd-update is only supported for RELEASE +if [ "${release%-RELEASE}" != "$release" ] +then + env PAGER=true /usr/sbin/freebsd-update \ + -b /mnt \ + --currently-running "$release" \ + --not-running-from-cron -F \ + fetch install +fi + +env ASSUME_ALWAYS_YES=YES pkg -c /mnt bootstrap -f +# TODO: remove bash +env ASSUME_ALWAYS_YES=YES pkg -c /mnt install git mercurial bash sudo curl + +git clone https://github.com/freebsd/freebsd-ports /mnt/usr/ports --depth=1 --single-branch + +pw -R /mnt groupadd sudo +pw -R /mnt useradd -n build -u 1000 -s /usr/local/bin/bash -m -w none -G sudo +echo "%sudo ALL=(ALL) NOPASSWD: ALL" >>/mnt/usr/local/etc/sudoers + +cat >/mnt/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht +EOF +chown build:build /mnt/home/build/.gitconfig cleanup trap : EXIT -# --- Hule machine configuration (`config.json`) ------------------------------ -# GPT + freebsd-boot (gptboot/pmbr), booted by the VMM's BIOS firmware. No -# boot.cmdline (the FreeBSD loader owns boot; firmware-disk takes none from the -# VMM). FreeBSD host tools: sha256(1) and stat -f, not GNU coreutils. -disk_sha=$(sha256 -q "$out/root.hmi") -disk_bytes=$(stat -f%z "$out/root.hmi") -virtual_bytes=$((size_gib * 1024 * 1024 * 1024)) -mem_min=$((256 * 1024 * 1024)) -mem_def=$((1024 * 1024 * 1024)) - -cat >"$out/config.json" <<CONFIG -{ - "schemaVersion": 1, - "kind": "MachineImage", - - "system": { - "os": "freebsd", - "version": "$version", - "architecture": "$arch" - }, - - "machine": { - "cpu": { "minimum": 1, "default": 2 }, - "ram": { "minimum": $mem_min, "default": $mem_def }, - "boot": [ - { - "protocol": "firmware-disk/bios", - "disk": "root" - } - ], - "access": [ - { "type": "ssh", "port": 22, "user": "build", "auth": "empty-password" }, - { "type": "qga" } - ], - "network": { "mode": "static", "address": "10.0.2.15/24", "gateway": "10.0.2.2" } - }, - - "disks": [ - { - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:$disk_sha", - "virtSize": $virtual_bytes, - "diskSize": $disk_bytes - } - ] -} -CONFIG +mkdir -p "$arch" +qemu-img convert -f raw -O qcow2 disk.img "$arch"/root.img.qcow2 +rm disk.img + +# Filesystem will be enlarged by growfs(7) on next startup +qemu-img resize "$arch"/root.img.qcow2 24G diff --git a/images/freebsd/genpkgimg b/images/freebsd/genpkgimg new file mode 100755 --- /dev/null +++ b/images/freebsd/genpkgimg @@ -0,0 +1,104 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +echo "$release" >/dev/null # fail on -u if unset +arch="${1:-amd64}" +rel=${release%%.*} + +cleanup() { + umount disk/usr/share/keys/pkg || true + chflags -R noschg disk || true + rm -rf disk || true +} +trap cleanup EXIT + +rm -f disk.img +mkdir disk +mkdir -p disk/usr/local/etc/pkg/repos +# pkg -R needs absolute path +reposdir=$(pwd)/disk/usr/local/etc/pkg/repos + +cat >${reposdir}/FreeBSD.conf <<EOF +FreeBSD: { + url: pkg+http://pkg.FreeBSD.org/\$\{ABI\}/latest + enabled: yes + mirror_type: srv + signature_type: fingerprint +} +FreeBSD-base: { + url: pkg+http://pkg.FreeBSD.org/\$\{ABI\}/base_latest + enabled: yes + mirror_type: srv + signature_type: fingerprint +} +EOF +export ABI="FreeBSD:$rel:$arch" +export IGNORE_OSVERSION=yes +mkdir -p disk/usr/share/keys/pkg +mount -t nullfs /usr/share/keys/pkg disk/usr/share/keys/pkg +pkg -C /dev/null -R ${reposdir} -r disk update +umount disk/usr/share/keys/pkg +# XXX replace by group FreeBSD-base the day it is implemented :D +pkg -C /dev/null -R ${reposdir} -r disk rquery -g "%n" "FreeBSD*" | grep -vE "(lib32|dbg|kernel|src|tests)" | \ + xargs pkg -C /dev/null -R ${reposdir} -r disk install -y +if pkg -C /dev/null -R ${reposdir} -r disk install -y FreeBSD-kernel-generic-nodebug ; then + echo "kernel=kernel.GENERIC-NODEBUG" > disk/boot/loader.conf +else + pkg -C /dev/null -R ${reposdir} -r disk install -y FreeBSD-kernel-generic +fi + +echo "/dev/gpt/rootfs / ufs rw,noatime 1 1" >disk/etc/fstab +touch disk/firstboot +echo 'autoboot_delay="-1"' >>disk/boot/loader.conf + +cat >>disk/etc/rc.conf <<EOF +ntpd_enable=YES +sshd_enable=YES +growfs_enable=YES +hostname="build" +ifconfig_DEFAULT="inet 10.0.2.15 netmask 255.255.255.0" +defaultrouter="10.0.2.2" +EOF +cat > disk/etc/resolv.conf <<EOF +nameserver 8.8.8.8 +nameserver 8.8.4.4 +EOF +tzsetup -s -C disk UTC + +cat >>disk/etc/ssh/sshd_config <<EOF +PermitRootLogin yes +PasswordAuthentication yes +PermitEmptyPasswords yes +UsePAM no +EOF + +# TODO: remove bash +pkg -r disk -R ${reposdir} install -y pkg git-lite mercurial bash sudo curl +pkg -r disk -R ${reposdir} clean -ay + +pw -R disk groupadd sudo +pw -R disk useradd -n build -u 1000 -s /usr/local/bin/bash -m -w none -G sudo +echo "%sudo ALL=(ALL) NOPASSWD: ALL" >>disk/usr/local/etc/sudoers + +cat >disk/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht +EOF +chown 1000:1000 disk/home/build/.gitconfig + +makefs -s 5g -B little -o label=rootfs -o version=2 -o softupdates=1 disk.img disk +mkdir -p "$arch" +mkimg -s gpt \ + -b disk/boot/pmbr \ + -C 16G \ + -p freebsd-boot:=disk/boot/gptboot \ + -p freebsd-ufs/rootfs:=disk.img \ + -f qcow2 \ + -o "$arch"/root.img.qcow2 + +cleanup +trap : EXIT + +rm disk.img diff --git a/images/ubuntu/functions b/images/ubuntu/functions new file mode 100644 --- /dev/null +++ b/images/ubuntu/functions @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +poweroff_cmd="sudo systemctl poweroff" +default_arch=amd64 + +boot() { + case "$arch" in + amd64) + qemu=qemu-system-x86_64 + _boot $(cpu_opts x86_64) + ;; + arm64) + driveopts="id=root,if=none" + _boot \ + $(cpu_opts aarch64) \ + -device virtio-blk-pci,drive=root \ + -kernel "$wd/$arch/vmlinuz" \ + -initrd "$wd/$arch/initrd.img" \ + -append "root=/dev/vda3" + ;; + *) + echo "Unsupported architecture $arch" >&2 + exit 1 + ;; + esac +} + +install() { + port=$1 + shift 1 + guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \ + apt-get update -y + guest_ssh -p $port build@localhost sudo env DEBIAN_FRONTEND=noninteractive \ + apt-get install -y -q "$@" +} + +add_repository() { + port=$1 + name=$2 + src=$3 + repo=$(echo $src | cut -d' ' -f1) + distro=$(echo $src | cut -d' ' -f2) + cmpnt=$(echo $src | cut -d' ' -f3) + key=$(echo $src | cut -d' ' -f4) + if [ "$key" != "" ] + then + # Import the GPG key into a user trustdb + guest_ssh -p $port build@localhost sudo \ + gpg \ + --keyserver hkp://keyserver.ubuntu.com:80 \ + --recv-keys $key + + # Export the GPG key to Apt's key directory + guest_ssh -p $port build@localhost sudo \ + gpg \ + --output /etc/apt/trusted.gpg.d/$key.gpg \ + --export $key + fi + printf 'deb %s %s %s\n' "$repo" "$distro" "$cmpnt" \ + | guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list + printf 'deb-src %s %s %s\n' "$repo" "$distro" "$cmpnt" \ + | guest_ssh -p $port build@localhost sudo tee -a /etc/apt/sources.list + guest_ssh -p "$port" build@localhost sudo apt-get update +} + +sanity_check() { + echo "Booting..." + cmd_boot amd64 8022 qemu & + trap 'cmd_cleanup 8022' EXIT + _wait_boot 8022 + echo "Testing sudo..." + guest_ssh -p 8022 build@localhost sudo ls -a + echo "Testing apt..." + guest_ssh -p 8022 build@localhost sudo apt-get update + install 8022 curl + echo "Testing networking..." + guest_ssh -p 8022 build@localhost curl https://builds.sr.ht + echo "Testing git..." + guest_ssh -p 8022 build@localhost git --version + echo "Testing mercurial..." + guest_ssh -p 8022 build@localhost hg --version + echo "Everything works!" + guest_ssh -p 8022 build@localhost sudo systemctl poweroff || true +} diff --git a/images/ubuntu/genimg b/images/ubuntu/genimg index 1980803..235b318 100755 --- a/images/ubuntu/genimg +++ b/images/ubuntu/genimg @@ -1,35 +1,22 @@ #!/bin/sh -eux -# SPDX-FileCopyrightText: 2017-2026 Drew DeVault -# SPDX-FileCopyrightText: 2026 Nikolay Govorov +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault # SPDX-License-Identifier: AGPL-3.0-only -self=$(dirname "$(readlink -f "$0")") -cd "$self" - -release=${1:-} -arch=${2:-amd64} - -case $release in -jammy | noble | resolute) ;; -*) - echo "usage: ${0##*/} <jammy|noble|resolute> [arch]" >&2 - exit 1 - ;; -esac - +echo "$release" >/dev/null # fail on -u if release unset +arch=${1:-amd64} case $arch in -amd64) - iface=ens3 - qarch=x86_64 - ;; -arm64) - iface=enp0s1 - qarch=aarch64 - ;; -*) - echo "unsupported architecture $arch" - exit 1 - ;; + amd64) + iface=ens3 + qarch=x86_64 + ;; + arm64) + iface=enp0s1 + qarch=aarch64 + ;; + *) + echo "unsupported architecture $arch" + exit 1 + ;; esac cleanup() { @@ -42,24 +29,23 @@ cleanup() { umount /mnt/run 2>/dev/null || true umount /mnt/sys 2>/dev/null || true umount /mnt/boot 2>/dev/null || true - umount /mnt 2>/dev/null || true + umount /mnt 2>/dev/null || true qemu-nbd --disconnect /dev/nbd0 || true } -out="$release/$arch" -size_gib=32 -mkdir -p "$out" +mkdir -p "$arch" -qemu-img create -f qcow2 -o compat=1.1 "$out/root.hmi" "${size_gib}G" +qemu-img create -f qcow2 $arch/root.img.qcow2 32G modprobe nbd max_part=16 -qemu-nbd --connect=/dev/nbd0 "$out/root.hmi" +qemu-nbd --connect=/dev/nbd0 $arch/root.img.qcow2 trap cleanup EXIT # Looks like qemu-nbd is non-blocking. Wait one second to make sure $NBD_DEVICE # is available. sleep 1 -if [ "$arch" = "amd64" ]; then +if [ "$arch" = "amd64" ] +then dd if=/usr/lib/syslinux/mbr/mbr.bin of=/dev/nbd0 bs=1 count=440 fi @@ -81,7 +67,7 @@ export DEBIAN_FRONTEND=noninteractive debootstrap \ --include=gnupg,ubuntu-keyring \ - --arch="$arch" "$release" \ + --arch=$arch $release \ /mnt http://archive.ubuntu.com/ubuntu/ mount --bind /dev /mnt/dev @@ -91,7 +77,8 @@ mount --bind /proc /mnt/proc mount --bind /run /mnt/run mount --bind /sys /mnt/sys -if [ "$arch" != "amd64" ]; then +if [ "$arch" != "amd64" ] +then cp /usr/bin/qemu-$qarch-static /mnt/usr/bin fi @@ -105,19 +92,13 @@ rm -f /mnt/etc/resolv.conf echo 'nameserver 8.8.8.8' >/mnt/etc/resolv.conf echo 'nameserver 9.9.9.9' >>/mnt/etc/resolv.conf echo 'nameserver 1.1.1.1' >>/mnt/etc/resolv.conf -# Network config baked into the guest; the manifest declares it (mode + params) -# so consumers know how the image is reachable. Single source, so the two stay -# in sync. -net_mode=static -net_address=10.0.2.15/24 -net_gateway=10.0.2.2 -cat >"/mnt/etc/systemd/network/25-$iface.network" <<EOF +cat >/mnt/etc/systemd/network/25-ens3.network <<EOF [Match] -Name=$iface +Name=ens3 [Network] -Address=$net_address -Gateway=$net_gateway +Address=10.0.2.15/24 +Gateway=10.0.2.2 EOF run_root systemctl enable systemd-networkd.service @@ -142,10 +123,10 @@ run_root apt-get -y install locales run_root apt-get -y install linux-base run_root apt-get -y install linux-image-generic run_root apt-get -y install \ - build-essential git mercurial ssh sudo dirmngr curl ca-certificates \ - qemu-guest-agent + build-essential git mercurial ssh sudo dirmngr curl ca-certificates -if [ "$arch" = "amd64" ]; then +if [ "$arch" = "amd64" ] +then extlinux -i /mnt/boot fi @@ -155,12 +136,11 @@ run_root systemctl enable systemd-timesyncd.service || run_root useradd -mG sudo build run_root passwd -d build -echo '%sudo ALL=(ALL) NOPASSWD: ALL' >>/mnt/etc/sudoers +echo '%sudo ALL=(ALL) NOPASSWD: ALL' >> /mnt/etc/sudoers -echo "PermitEmptyPasswords yes" >>/mnt/etc/ssh/sshd_config -echo ssh >>/mnt/etc/securetty +echo "PermitEmptyPasswords yes" >> /mnt/etc/ssh/sshd_config +echo ssh >> /mnt/etc/securetty run_root systemctl enable ssh -run_root systemctl enable qemu-guest-agent # Prevent docker from mucking up networking mkdir -p /mnt/etc/docker @@ -172,134 +152,33 @@ EOF run_root update-initramfs -u -kernel_path= -for candidate in /mnt/boot/vmlinuz-[0-9]*; do - [ -e "$candidate" ] || continue - kernel_path=$candidate - break -done -[ -n "$kernel_path" ] -linuxver=${kernel_path##*/vmlinuz-} - -# Reference partitions by PARTUUID so boot works regardless of how the VMM names -# the disk (vda/sda/nvme...). cmdline is canonical: identical for every boot -# protocol (extlinux here, and -append on the direct path) -- see -# docs/boot-protocol.md. -boot_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p1) -swap_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p2) -root_partuuid=$(blkid -s PARTUUID -o value /dev/nbd0p3) -cmdline="root=PARTUUID=$root_partuuid rw quiet" +linuxver=$(ls /mnt/boot | grep 'vmlinuz-[0-9].*' | cut -d- -f2-) cat >/mnt/boot/extlinux.conf <<EOF default ubuntu label ubuntu linux vmlinuz-$linuxver initrd initrd.img-$linuxver - append $cmdline + append root=/dev/vda3 rw quiet EOF cat >>/mnt/etc/fstab <<EOF -PARTUUID=$boot_partuuid /boot ext4 rw,relatime,data=ordered 0 0 -PARTUUID=$swap_partuuid swap swap defaults 0 0 -PARTUUID=$root_partuuid / ext4 rw,relatime,data=ordered 0 0 +/dev/vda1 /boot ext4 rw,relatime,data=ordered 0 0 +/dev/vda2 swap swap defaults 0 0 +/dev/vda3 / ext4 rw,relatime,data=ordered 0 0 EOF -if [ "$arch" != "amd64" ]; then - # Sidecar kernel/initrd for the linux-boot protocol: there is no - # in-image bootloader on non-amd64, the VMM boots these directly. - cp /mnt/boot/vmlinuz "$out/vmlinuz" - cp /mnt/boot/initrd.img "$out/initrd" +cat >/mnt/home/build/.gitconfig <<EOF +[user] + name = builds.sr.ht + email = builds@sr.ht +EOF +chown build:build /mnt/home/build/.gitconfig + +if [ "$arch" != "amd64" ] +then + cp /mnt/boot/vmlinuz $arch/vmlinuz + cp /mnt/boot/initrd.img $arch/initrd.img fi sync - -# Detach the disk so root.hmi is fully flushed before we hash it, then stop -# the cleanup trap from running a second time on exit. -cleanup -trap : EXIT - -# --- Hule machine configuration (`config.json`) ------------------------------ -# JSON description of the image: the .hmi disk(s), the boot protocols this image -# can honestly be booted with, and the surfaces it exposes. The declaration is a -# promise (see docs/boot-protocol.md); only list what this build produces. -# Self-contained: paths + checksums, no dependency on OCI (layers are transport -# only). Sizes are integer bytes, keys are camelCase, disks referenced by id. -disk_sha=$(sha256sum "$out/root.hmi" | cut -d' ' -f1) -disk_bytes=$(stat -c%s "$out/root.hmi") -virtual_bytes=$((size_gib * 1024 * 1024 * 1024)) -mem_min=$((256 * 1024 * 1024)) -mem_def=$((1024 * 1024 * 1024)) - -case "$arch" in -amd64) - # Legacy BIOS: extlinux inside an MBR-partitioned disk, booted by the - # VMM's BIOS firmware (e.g. SeaBIOS). Self-bootable, no external inputs. - protocols=$( - cat <<JSON - { - "protocol": "firmware-disk/bios", - "disk": "root" - } -JSON - ) - ;; -*) - # No in-image bootloader; the VMM boots the extracted kernel/initrd - # directly and mounts the root disk. cmdline is canonical (boot.cmdline). - kernel_sha=$(sha256sum "$out/vmlinuz" | cut -d' ' -f1) - initrd_sha=$(sha256sum "$out/initrd" | cut -d' ' -f1) - protocols=$( - cat <<JSON - { - "protocol": "linux/direct", - "disk": "root", - "kernel": { "path": "vmlinuz", "digest": "sha256:$kernel_sha" }, - "initrd": { "path": "initrd", "digest": "sha256:$initrd_sha" }, - "cmdline": "$cmdline" - } -JSON - ) - ;; -esac - -cat >"$out/config.json" <<EOF -{ - "schemaVersion": 1, - "kind": "MachineImage", - - "system": { - "os": "linux", - "name": "ubuntu", - "version": "$release", - "architecture": "$arch" - }, - - "machine": { - "cpu": { "minimum": 1, "default": 2 }, - "ram": { "minimum": $mem_min, "default": $mem_def }, - "boot": [ -$protocols - ], - "access": [ - { "type": "ssh", "port": 22, "user": "build", "auth": "empty-password" }, - { "type": "qga" } - ], - "network": { - "mode": "$net_mode", - "address": "$net_address", - "gateway": "$net_gateway" - } - }, - - "disks": [ - { - "id": "root", - "format": "qcow2", - "path": "root.hmi", - "digest": "sha256:$disk_sha", - "virtSize": $virtual_bytes, - "diskSize": $disk_bytes - } - ] -} -EOF diff --git a/images/ubuntu/jammy/functions b/images/ubuntu/jammy/functions new file mode 120000 --- /dev/null +++ b/images/ubuntu/jammy/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/ubuntu/jammy/genimg b/images/ubuntu/jammy/genimg new file mode 100755 --- /dev/null +++ b/images/ubuntu/jammy/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=jammy +exec ../genimg "$@" diff --git a/images/ubuntu/noble/functions b/images/ubuntu/noble/functions new file mode 120000 --- /dev/null +++ b/images/ubuntu/noble/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/ubuntu/noble/genimg b/images/ubuntu/noble/genimg new file mode 100755 --- /dev/null +++ b/images/ubuntu/noble/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=noble +exec ../genimg "$@" diff --git a/images/ubuntu/resolute/functions b/images/ubuntu/resolute/functions new file mode 120000 --- /dev/null +++ b/images/ubuntu/resolute/functions @@ -0,0 +1 @@ +../functions
\ No newline at end of file diff --git a/images/ubuntu/resolute/genimg b/images/ubuntu/resolute/genimg new file mode 100755 --- /dev/null +++ b/images/ubuntu/resolute/genimg @@ -0,0 +1,6 @@ +#!/bin/sh -eux +# SPDX-FileCopyrightText: 2017-2026 Drew DeVault +# SPDX-License-Identifier: AGPL-3.0-only + +export release=resolute +exec ../genimg "$@" diff --git a/mise.lock b/mise.lock deleted file mode 100644 --- a/mise.lock +++ /dev/null @@ -1,48 +0,0 @@ -# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html - -[[tools.rust]] -version = "1.97.1" -backend = "core:rust" - -[tools.rust.options] -components = "clippy,llvm-tools-preview,rustfmt" -profile = "minimal" - -[[tools.shellcheck]] -version = "0.11.0" -backend = "aqua:koalaman/shellcheck" - -[tools.shellcheck."platforms.linux-arm64"] -checksum = "sha256:12b331c1d2db6b9eb13cfca64306b1b157a86eb69db83023e261eaa7e7c14588" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.aarch64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056934" - -[tools.shellcheck."platforms.linux-arm64-musl"] -checksum = "sha256:12b331c1d2db6b9eb13cfca64306b1b157a86eb69db83023e261eaa7e7c14588" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.aarch64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056934" - -[tools.shellcheck."platforms.linux-x64"] -checksum = "sha256:8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.x86_64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056942" - -[tools.shellcheck."platforms.linux-x64-musl"] -checksum = "sha256:8c3be12b05d5c177a04c29e3c78ce89ac86f1595681cab149b65b97c4e227198" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.linux.x86_64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056942" - -[tools.shellcheck."platforms.macos-arm64"] -checksum = "sha256:56affdd8de5527894dca6dc3d7e0a99a873b0f004d7aabc30ae407d3f48b0a79" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.darwin.aarch64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056932" - -[tools.shellcheck."platforms.macos-x64"] -checksum = "sha256:3c89db4edcab7cf1c27bff178882e0f6f27f7afdf54e859fa041fca10febe4c6" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.darwin.x86_64.tar.xz" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056930" - -[tools.shellcheck."platforms.windows-x64"] -checksum = "sha256:8a4e35ab0b331c85d73567b12f2a444df187f483e5079ceffa6bda1faa2e740e" -url = "https://github.com/koalaman/shellcheck/releases/download/v0.11.0/shellcheck-v0.11.0.zip" -url_api = "https://api.github.com/repos/koalaman/shellcheck/releases/assets/279056944" diff --git a/mise.toml b/mise.toml deleted file mode 100644 --- a/mise.toml +++ /dev/null @@ -1,17 +0,0 @@ -# SPDX-FileCopyrightText: 2026 Nikolay Govorov -# SPDX-License-Identifier: Apache-2.0 - -min_version = "2026.7.5" - -[settings] -experimental = true - -[tools] -rust = { version = "1.97.1", profile = "minimal", components = [ "clippy", "llvm-tools-preview", "rustfmt" ] } -shellcheck = "0.11.0" - -[task_config] -dir = "{{cwd}}" -includes = [ - "git::https://git.dimidiumlabs.io/platform.git//tasks?ref=e5ca3be4349af3d1da2dde9d1165d52fb014a371", -] |
