From 9262be8afbd6240ee23064af5457a13c2e65ba95 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Sat, 10 Oct 2026 13:00:11 -0400 Subject: [PATCH 1/6] feat: add QEMU builds --- .envrc | 2 + .github/dependabot.yml | 9 + .github/workflows/qemu-image.yml | 73 ++++++ .gitignore | 1 + flake.lock | 398 +++++++++++++++++++++++++++++++ flake.nix | 133 +++++++++++ nixos/training-image.nix | 39 +++ nixos/training-vm.nix | 33 +++ scripts/check-vm-image.sh | 77 ++++++ scripts/run-vm.sh | 45 ++++ 10 files changed, 810 insertions(+) create mode 100644 .envrc create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/qemu-image.yml create mode 100644 flake.lock create mode 100644 flake.nix create mode 100644 nixos/training-image.nix create mode 100644 nixos/training-vm.nix create mode 100644 scripts/check-vm-image.sh create mode 100644 scripts/run-vm.sh diff --git a/.envrc b/.envrc new file mode 100644 index 0000000..36be7fc --- /dev/null +++ b/.envrc @@ -0,0 +1,2 @@ +dotenv_if_exists +use flake . --no-pure-eval diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..7fc7a9e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,9 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "master" + schedule: + interval: "weekly" + commit-message: + prefix: "ci:" diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml new file mode 100644 index 0000000..176c093 --- /dev/null +++ b/.github/workflows/qemu-image.yml @@ -0,0 +1,73 @@ +name: QEMU image + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +concurrency: + group: qemu-image-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + strategy: + fail-fast: false + matrix: + include: + - arch: x86_64 + runner: ubuntu-24.04 + - arch: aarch64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + permissions: + contents: read + steps: + - uses: actions/checkout@v6 + - uses: cachix/install-nix-action@v31 + - name: Restore and save Nix store + uses: nix-community/cache-nix-action@v7 + with: + primary-key: nix-${{ matrix.arch }}-${{ hashFiles('flake.lock') }} + restore-prefixes-first-match: nix-${{ matrix.arch }}- + save: ${{ github.ref == 'refs/heads/main' }} + gc-max-store-size-linux: 4G + - name: Build image + run: nix build .#qemu-image --out-link result + - name: Check image, boot, and SSH login + env: + VM_ARCH: ${{ matrix.arch }} + run: nix develop .#ci --command bash scripts/check-vm-image.sh result/nix-training-${{ matrix.arch }}.qcow2 + - uses: actions/upload-artifact@v4 + with: + name: nix-training-${{ matrix.arch }} + path: result/nix-training-${{ matrix.arch }}.qcow2 + if-no-files-found: error + retention-days: 90 + compression-level: 0 + + publish: + if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') + needs: build + runs-on: ubuntu-24.04 + permissions: + contents: write + actions: read + steps: + - uses: actions/download-artifact@v4 + with: + pattern: nix-training-* + path: image + merge-multiple: true + - name: Publish latest working image + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release create "vm-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" \ + image/nix-training-*.qcow2 \ + --repo "$GITHUB_REPOSITORY" \ + --target "$GITHUB_SHA" \ + --title "Nix training QEMU image" \ + --notes "Built and boot-tested from commit $GITHUB_SHA. Login: gambi / gambi. Nix flakes enabled." \ + --latest diff --git a/.gitignore b/.gitignore index 00c996c..23253f9 100644 --- a/.gitignore +++ b/.gitignore @@ -57,6 +57,7 @@ flycheck_*.el # Ignore build outputs from performing a nix-build or `nix build` command result result-* +/images/ # Ignore automatically generated direnv output .direnv diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..6b0124e --- /dev/null +++ b/flake.lock @@ -0,0 +1,398 @@ +{ + "nodes": { + "cachix": { + "inputs": { + "devenv": [ + "devenv" + ], + "flake-compat": [ + "devenv", + "flake-compat" + ], + "git-hooks": [ + "devenv", + "git-hooks" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788181969, + "narHash": "sha256-OUB6hPlFBB9FRdZgZXSye4lDOg+fbrqKe8ePv2IM7NY=", + "owner": "cachix", + "repo": "cachix", + "rev": "98093e8eea6c1635ef1337a576fa76f3e8bd4f39", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "latest", + "repo": "cachix", + "type": "github" + } + }, + "crate2nix": { + "flake": false, + "locked": { + "lastModified": 1772186516, + "narHash": "sha256-8s28pzmQ6TOIUzznwFibtW1CMieMUl1rYJIxoQYor58=", + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + }, + "original": { + "owner": "rossng", + "repo": "crate2nix", + "rev": "ba5dd398e31ee422fbe021767eb83b0650303a6e", + "type": "github" + } + }, + "devenv": { + "inputs": { + "cachix": "cachix", + "crate2nix": "crate2nix", + "flake-compat": "flake-compat", + "flake-parts": "flake-parts", + "ghostty": "ghostty", + "git-hooks": "git-hooks", + "nix": "nix", + "nixd": "nixd", + "nixpkgs": [ + "nixpkgs" + ], + "rust-overlay": "rust-overlay" + }, + "locked": { + "lastModified": 1791549372, + "narHash": "sha256-5Vu2oKeImB5wQWLFSEcWXsF0Oajm4/5MV7UlnOdelmg=", + "owner": "cachix", + "repo": "devenv", + "rev": "a73c5b84c9527760f009232988466763068f9f61", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "devenv", + "type": "github" + } + }, + "flake-compat": { + "flake": false, + "locked": { + "lastModified": 1767039857, + "narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=", + "owner": "edolstra", + "repo": "flake-compat", + "rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab", + "type": "github" + }, + "original": { + "owner": "edolstra", + "repo": "flake-compat", + "type": "github" + } + }, + "flake-parts": { + "inputs": { + "nixpkgs-lib": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788306937, + "narHash": "sha256-lbrI1UYVpFgKSsyrU9oeF7FHfnu8nLD9ja0ou9f2rxk=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "f16b25b8c3d2809b87925d0b76652d7821a75c68", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "flake-parts_2": { + "inputs": { + "nixpkgs-lib": "nixpkgs-lib" + }, + "locked": { + "lastModified": 1790898470, + "narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=", + "owner": "hercules-ci", + "repo": "flake-parts", + "rev": "024633cd702b10285db5cb19b40ad48d2399ba60", + "type": "github" + }, + "original": { + "owner": "hercules-ci", + "repo": "flake-parts", + "type": "github" + } + }, + "ghostty": { + "flake": false, + "locked": { + "lastModified": 1786026742, + "narHash": "sha256-tRtgTg/i3w1nFdRHU2IGekfJN8EyP+HARW4MtoUZyqk=", + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + }, + "original": { + "owner": "ghostty-org", + "repo": "ghostty", + "rev": "22d13172cde98a0a4dda05d3d6a3fcb0dd8ed018", + "type": "github" + } + }, + "git-hooks": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788267358, + "narHash": "sha256-nt+lUqYVpc9Y6JeMd2WmXzCDojasdadKo0mWcluvY2Y=", + "owner": "cachix", + "repo": "git-hooks.nix", + "rev": "27555e2624241fb116b49095df4caaee85a25691", + "type": "github" + }, + "original": { + "owner": "cachix", + "repo": "git-hooks.nix", + "type": "github" + } + }, + "mk-shell-bin": { + "locked": { + "lastModified": 1677004959, + "narHash": "sha256-/uEkr1UkJrh11vD02aqufCxtbF5YnhRTIKlx5kyvf+I=", + "owner": "rrbutani", + "repo": "nix-mk-shell-bin", + "rev": "ff5d8bd4d68a347be5042e2f16caee391cd75887", + "type": "github" + }, + "original": { + "owner": "rrbutani", + "repo": "nix-mk-shell-bin", + "type": "github" + } + }, + "nix": { + "inputs": { + "flake-compat": [ + "devenv", + "flake-compat" + ], + "flake-parts": [ + "devenv", + "flake-parts" + ], + "git-hooks-nix": [ + "devenv", + "git-hooks" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "nixpkgs-23-11": [ + "devenv" + ], + "nixpkgs-regression": [ + "devenv" + ] + }, + "locked": { + "lastModified": 1790176416, + "narHash": "sha256-acP7QvsB+dHghUeL9AwSSZ3qS//skpqjv484aveg1EQ=", + "owner": "cachix", + "repo": "nix", + "rev": "bd10d7f563420c6034b9d1dc75c4168fc01e5afc", + "type": "github" + }, + "original": { + "owner": "cachix", + "ref": "devenv-2.35", + "repo": "nix", + "type": "github" + } + }, + "nix2container": { + "inputs": { + "nixpkgs": [ + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1790918497, + "narHash": "sha256-tHQzYcg3iAVhUE5dtRL5KweJXbcZ7UEQG/XFGsHtQsI=", + "owner": "nlewo", + "repo": "nix2container", + "rev": "4e83e6724dcb9eb1b3e855426fa4c8cd19f5ce5a", + "type": "github" + }, + "original": { + "owner": "nlewo", + "repo": "nix2container", + "type": "github" + } + }, + "nixd": { + "inputs": { + "flake-parts": [ + "devenv", + "flake-parts" + ], + "nixpkgs": [ + "devenv", + "nixpkgs" + ], + "treefmt-nix": "treefmt-nix" + }, + "locked": { + "lastModified": 1788165251, + "narHash": "sha256-ITHt6eU6DuwQqlNV1/wehvKYPE6J8sZIlv75CpDjcHI=", + "owner": "nix-community", + "repo": "nixd", + "rev": "e2ca72c353cfbc3d63e942fe9aeae4ec497863bf", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixd", + "type": "github" + } + }, + "nixpkgs": { + "locked": { + "lastModified": 1791487292, + "narHash": "sha256-6BIvCXtdLW4HQwsOGkgH444aB3vCbHypE9TA78ireh8=", + "rev": "8edc0c72e3a38faf5434e40d1f19431125fe4b30", + "type": "tarball", + "url": "https://releases.nixos.org/nixpkgs/nixpkgs-26.11pre1088030.8edc0c72e3a3/nixexprs.tar.zst" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst" + } + }, + "nixpkgs-lib": { + "locked": { + "lastModified": 1790477367, + "narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=", + "owner": "nix-community", + "repo": "nixpkgs.lib", + "rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixpkgs.lib", + "type": "github" + } + }, + "nixpkgs_2": { + "locked": { + "lastModified": 1790149054, + "narHash": "sha256-FfjXg6mAzKQBCY+7V9keGWOXG4DV2Eym/qA987lFl8A=", + "owner": "nixos", + "repo": "nixpkgs", + "rev": "8825bebf6324e0579d012936eff73379af284b6d", + "type": "github" + }, + "original": { + "owner": "nixos", + "ref": "nixpkgs-unstable", + "repo": "nixpkgs", + "type": "github" + } + }, + "root": { + "inputs": { + "devenv": "devenv", + "flake-parts": "flake-parts_2", + "mk-shell-bin": "mk-shell-bin", + "nix2container": "nix2container", + "nixpkgs": "nixpkgs", + "treefmt-nix": "treefmt-nix_2" + } + }, + "rust-overlay": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1788332415, + "narHash": "sha256-BTFrmyh0oaVDsvA9NNw0YpbbeppTwU0t70iVx672Ew8=", + "owner": "oxalica", + "repo": "rust-overlay", + "rev": "860d7c835ab91bfc8972b67092f5f2db8e9390a0", + "type": "github" + }, + "original": { + "owner": "oxalica", + "repo": "rust-overlay", + "type": "github" + } + }, + "treefmt-nix": { + "inputs": { + "nixpkgs": [ + "devenv", + "nixd", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1786901030, + "narHash": "sha256-WSFCsDSE5ffgD2MqzkM2CYjeFiKhRF/dJUN8uedb6YE=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "27b3b12a8e6375f28ebe122f07d230ca5459bbfa", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + }, + "treefmt-nix_2": { + "inputs": { + "nixpkgs": "nixpkgs_2" + }, + "locked": { + "lastModified": 1791490544, + "narHash": "sha256-qScE7Wz6Zg7eg8ItUpnkmKgst8weWschGe0E8jM4rj4=", + "owner": "numtide", + "repo": "treefmt-nix", + "rev": "4cfe8d7065cc8ca91c0a50361b6dd74920eeb1f5", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "treefmt-nix", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..63924b2 --- /dev/null +++ b/flake.nix @@ -0,0 +1,133 @@ +{ + description = "Nix training development shell and QEMU image"; + + inputs = { + nixpkgs.url = "https://channels.nixos.org/nixpkgs-unstable/nixexprs.tar.zst"; + + devenv = { + url = "github:cachix/devenv"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + + flake-parts.url = "github:hercules-ci/flake-parts"; + + treefmt-nix.url = "github:numtide/treefmt-nix"; + + nix2container = { + url = "github:nlewo/nix2container"; + inputs.nixpkgs.follows = "nixpkgs"; + }; + + mk-shell-bin.url = "github:rrbutani/nix-mk-shell-bin"; + }; + + outputs = + inputs@{ + self, + flake-parts, + nixpkgs, + ... + }: + flake-parts.lib.mkFlake { inherit inputs; } { + imports = [ + inputs.devenv.flakeModule + inputs.treefmt-nix.flakeModule + ]; + systems = nixpkgs.lib.systems.flakeExposed; + + flake.nixosConfigurations = { + training-vm = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + modules = [ ./nixos/training-vm.nix ]; + }; + training-image = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + modules = [ + ./nixos/training-vm.nix + ./nixos/training-image.nix + ]; + }; + training-vm-aarch64 = nixpkgs.lib.nixosSystem { + system = "aarch64-linux"; + modules = [ ./nixos/training-vm.nix ]; + }; + training-image-aarch64 = nixpkgs.lib.nixosSystem { + system = "aarch64-linux"; + modules = [ + ./nixos/training-vm.nix + ./nixos/training-image.nix + ]; + }; + }; + + perSystem = + { + pkgs, + lib, + system, + ... + }: + { + # This sets `pkgs` to a nixpkgs with allowUnfree option set. + _module.args.pkgs = import nixpkgs { + inherit system; + config.allowUnfree = true; + }; + + packages = + lib.optionalAttrs (system == "x86_64-linux") { + qemu-image = self.nixosConfigurations.training-image.config.system.build.image; + } + // lib.optionalAttrs (system == "aarch64-linux") { + qemu-image = self.nixosConfigurations.training-image-aarch64.config.system.build.image; + }; + + # nix fmt + nix flake check (auto-wired by flakeModule) + treefmt = { + projectRootFile = "flake.nix"; + programs.actionlint.enable = true; + programs.nixfmt.enable = true; + }; + + # Native Nix devShells replacement + devShells = { + # nix develop .#ci + ci = pkgs.mkShell { + name = "ci-shell"; + packages = [ + pkgs.gnumake + pkgs.openssh + pkgs.qemu + pkgs.sshpass + ]; + + shellHook = '' + echo "Entering CI shell..." + ''; + }; + }; + + devenv.shells.default = { + devenv.root = + let + workingDirectory = builtins.getEnv "PWD"; + in + if workingDirectory == "" then builtins.toString ./. else workingDirectory; + + # OCI packaging is defined above; disable devenv's implicit shell + # containers so flake checks do not require unrelated container inputs. + containers = lib.mkForce { }; + + packages = with pkgs; [ + bash + gnumake + qemu + ]; + + enterShell = '' + echo "Starting Development Environment..." + ''; + }; + }; + }; +} diff --git a/nixos/training-image.nix b/nixos/training-image.nix new file mode 100644 index 0000000..9a2d9bd --- /dev/null +++ b/nixos/training-image.nix @@ -0,0 +1,39 @@ +{ + config, + lib, + modulesPath, + pkgs, + ... +}: +{ + imports = [ (modulesPath + "/virtualisation/disk-image.nix") ]; + + image.baseName = "nix-training-${pkgs.stdenv.hostPlatform.parsed.cpu.name}"; + image.efiSupport = pkgs.stdenv.hostPlatform.isAarch64; + + # Do not embed the full nixpkgs source just to provide a local flake registry. + nixpkgs.flake.setNixPath = false; + nixpkgs.flake.setFlakeRegistry = false; + + # Students use the prebuilt guest; installer and rebuild commands needlessly + # pull Python and other large tools into its store closure. + system.disableInstallerTools = true; + + boot.initrd.availableKernelModules = [ + "virtio_pci" + "virtio_blk" + ]; + + # The standard disk image module copies the entire nixpkgs source as a channel. + # Omit it so the downloadable image contains only the installed system. + system.build.image = lib.mkForce ( + import (pkgs.path + "/nixos/lib/make-disk-image.nix") { + inherit config lib pkgs; + inherit (config.virtualisation) diskSize; + inherit (config.image) baseName; + format = "qcow2-compressed"; + partitionTableType = if config.image.efiSupport then "efi" else "legacy"; + copyChannel = false; + } + ); +} diff --git a/nixos/training-vm.nix b/nixos/training-vm.nix new file mode 100644 index 0000000..29b504a --- /dev/null +++ b/nixos/training-vm.nix @@ -0,0 +1,33 @@ +{ modulesPath, pkgs, ... }: +{ + imports = [ (modulesPath + "/profiles/minimal.nix") ]; + + boot.kernelParams = [ + "console=tty0" + (if pkgs.stdenv.hostPlatform.isAarch64 then "console=ttyAMA0,115200" else "console=ttyS0,115200n8") + ]; + + networking.hostName = "nix-training"; + hardware.enableRedistributableFirmware = false; + + nix.settings.experimental-features = [ + "nix-command" + "flakes" + ]; + + services.openssh = { + enable = true; + settings = { + PasswordAuthentication = true; + PermitRootLogin = "no"; + }; + }; + + users.users.gambi = { + isNormalUser = true; + extraGroups = [ "wheel" ]; + initialPassword = "gambi"; + }; + + system.stateVersion = "25.11"; +} diff --git a/scripts/check-vm-image.sh b/scripts/check-vm-image.sh new file mode 100644 index 0000000..c841998 --- /dev/null +++ b/scripts/check-vm-image.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +set -euo pipefail + +image=${1:?Usage: check-vm-image.sh IMAGE.qcow2} +ssh_port=${VM_SSH_PORT:-2222} +qemu-img check -f qcow2 "$image" + +boot_log=$(mktemp) +qemu_pid= +cleanup() { + if [[ -n "$qemu_pid" ]]; then + kill "$qemu_pid" 2>/dev/null || true + wait "$qemu_pid" 2>/dev/null || true + fi + rm -f "$boot_log" +} +trap cleanup EXIT + +VM_HEADLESS=1 VM_SSH_PORT="$ssh_port" bash scripts/run-vm.sh "$image" \ + >"$boot_log" 2>&1 & +qemu_pid=$! + +for ((attempt = 0; attempt < 180; attempt++)); do + if grep -q 'nix-training login:' "$boot_log"; then + echo "VM reached the serial login prompt." + break + fi + if ! kill -0 "$qemu_pid" 2>/dev/null; then + cat "$boot_log" + echo "QEMU exited before the login prompt." >&2 + exit 1 + fi + sleep 1 +done + +if ! grep -q 'nix-training login:' "$boot_log"; then + cat "$boot_log" + echo "VM did not reach the login prompt within 180 seconds." >&2 + exit 1 +fi + +for ((attempt = 0; attempt < 60; attempt++)); do + if ssh_output=$(SSHPASS=gambi sshpass -e ssh \ + -F /dev/null \ + -o BatchMode=no \ + -o PreferredAuthentications=password \ + -o PubkeyAuthentication=no \ + -o StrictHostKeyChecking=no \ + -o UserKnownHostsFile=/dev/null \ + -o ConnectTimeout=2 \ + -p "$ssh_port" \ + gambi@127.0.0.1 'id -un && id -nG && printf "gambi\n" | sudo -S -p "" id -u && nix config show experimental-features' 2>/dev/null); then + ssh_user=${ssh_output%%$'\n'*} + ssh_rest=${ssh_output#*$'\n'} + ssh_groups=${ssh_rest%%$'\n'*} + ssh_rest=${ssh_rest#*$'\n'} + ssh_uid=${ssh_rest%%$'\n'*} + ssh_features=${ssh_rest#*$'\n'} + if [[ $ssh_user == gambi ]] && [[ " $ssh_groups " == *" wheel "* ]] && [[ $ssh_uid == 0 ]] && + [[ " $ssh_features " == *" nix-command "* ]] && [[ " $ssh_features " == *" flakes "* ]]; then + echo "SSH password login, sudo access, and Nix flakes succeeded." + exit 0 + fi + echo "SSH login returned unexpected user, groups, sudo access, or Nix features: $ssh_output" >&2 + exit 1 + fi + if ! kill -0 "$qemu_pid" 2>/dev/null; then + cat "$boot_log" + echo "QEMU exited before SSH login succeeded." >&2 + exit 1 + fi + sleep 1 +done + +cat "$boot_log" +echo "SSH password login did not succeed within 60 seconds." >&2 +exit 1 diff --git a/scripts/run-vm.sh b/scripts/run-vm.sh new file mode 100644 index 0000000..b604df6 --- /dev/null +++ b/scripts/run-vm.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +set -euo pipefail + +image=${1:?Usage: run-vm.sh IMAGE.qcow2} +arch=${VM_ARCH:-$(uname -m)} +ssh_port=${VM_SSH_PORT:-2222} +memory=${VM_MEMORY:-1024} + +case "$arch" in + arm64 | aarch64) arch=aarch64 ;; + amd64 | x86_64) arch=x86_64 ;; + *) echo "Unsupported VM architecture: $arch" >&2; exit 1 ;; +esac + +case "$(uname -s)" in + Darwin) accel=hvf:tcg; arm_cpu=host ;; + Linux) accel=kvm:tcg; arm_cpu=max ;; + *) echo "QEMU launch supports Linux and macOS." >&2; exit 1 ;; +esac + +qemu_args=( + -m "$memory" + -nic "user,hostfwd=tcp:127.0.0.1:${ssh_port}-:22" + -drive "file=$image,format=qcow2,if=virtio,snapshot=on" +) + +if [[ $arch == aarch64 ]]; then + qemu_args+=( + -machine "virt,accel=$accel" + -cpu "$arm_cpu" + -bios "${VM_FIRMWARE:-edk2-aarch64-code.fd}" + ) + qemu=qemu-system-aarch64 +else + qemu_args+=(-machine "accel=$accel") + qemu=qemu-system-x86_64 +fi + +if [[ ${VM_HEADLESS:-0} == 1 ]]; then + qemu_args+=(-display none -monitor none -serial stdio -no-reboot) +else + qemu_args+=(-nographic -monitor none) +fi + +exec "$qemu" "${qemu_args[@]}" From adc5d9303d70f0bc9803f8a90ca27ef1b6894582 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Sun, 11 Oct 2026 19:48:26 -0400 Subject: [PATCH 2/6] feat: add QEMU builds --- Makefile | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 55 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 Makefile diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..4d197e6 --- /dev/null +++ b/Makefile @@ -0,0 +1,67 @@ +HOST_OS ?= $(shell uname -s) +HOST_ARCH ?= $(shell uname -m) +VM_SSH_PORT ?= 2222 +TEST_SSH_PORT ?= 2223 +VM_MEMORY ?= 1024 + +ifneq ($(filter $(HOST_ARCH),arm64 aarch64),) +VM_ARCH := aarch64 +else ifneq ($(filter $(HOST_ARCH),x86_64 amd64),) +VM_ARCH := x86_64 +else +$(error Unsupported host architecture: $(HOST_ARCH)) +endif + +ifeq ($(HOST_OS),Darwin) +VM_IMAGE := images/nix-training-$(VM_ARCH).qcow2 +else ifeq ($(HOST_OS),Linux) +VM_IMAGE := result/nix-training-$(VM_ARCH).qcow2 +else +$(error Unsupported host OS: $(HOST_OS)) +endif + +.DEFAULT_GOAL := help +.PHONY: help image vm run test + +help: + @printf '%s\n' \ + 'make image Build or download the $(VM_ARCH) qcow2 image' \ + 'make vm Build the NixOS VM launcher (Linux only)' \ + 'make run Boot the image in QEMU (SSH on localhost:$(VM_SSH_PORT))' \ + 'make test Check the image, boot, SSH login, and sudo access' + +ifeq ($(HOST_OS),Darwin) +image: $(VM_IMAGE) + +$(VM_IMAGE): + mkdir -p '$(@D)' + curl --fail --location --retry 3 \ + 'https://github.com/PerplexSystems/nix-training/releases/latest/download/$(@F)' \ + --output '$@.tmp' + mv '$@.tmp' '$@' +else +image: + nix build .#qemu-image --out-link result +endif + +vm: +ifeq ($(HOST_OS),Darwin) + @printf '%s\n' 'The NixOS VM launcher requires Linux; use make run on macOS.' >&2 + @exit 1 +else + nix build .#nixosConfigurations.training-vm$(if $(filter aarch64,$(VM_ARCH)),-aarch64).config.system.build.vm --out-link result-vm +endif + +run: image + @printf '%s\n' 'VM login: gambi / gambi' 'SSH: ssh -p $(VM_SSH_PORT) gambi@127.0.0.1' +ifeq ($(HOST_OS),Darwin) + VM_ARCH='$(VM_ARCH)' VM_SSH_PORT='$(VM_SSH_PORT)' VM_MEMORY='$(VM_MEMORY)' \ + bash scripts/run-vm.sh '$(VM_IMAGE)' +else + VM_ARCH='$(VM_ARCH)' VM_SSH_PORT='$(VM_SSH_PORT)' VM_MEMORY='$(VM_MEMORY)' \ + nix develop .#ci --command bash scripts/run-vm.sh '$(VM_IMAGE)' +endif + +test: image + VM_ARCH='$(VM_ARCH)' VM_SSH_PORT='$(TEST_SSH_PORT)' \ + nix develop .#ci --command bash scripts/check-vm-image.sh '$(VM_IMAGE)' diff --git a/README.md b/README.md index 32cc7ca..7cebc0e 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,7 @@ 🌐 Read this in other languages: [🇺🇸 English](README.md) | [🇧🇷 Português](README.pt-br.md) -Notes and tutorials for our Nix training, originally created for [Gambiconf -2026](https://gambiconf.dev/ "Gambiconf 2026"). +Notes and tutorials for our Nix training, originally created for [Gambiconf 2026](https://gambiconf.dev/ "Gambiconf 2026"). ## What is Nix? @@ -49,5 +48,57 @@ Nix runs on Linux, macOS and even Windows [Through NixOS-WSL](https://github.com - Nix manual pages are cited at version **2.34**. - Try the examples in `nix repl` or a scratch directory as you go. +## Training VM + +Download the latest boot-tested [x86_64 or aarch64 qcow2 image](https://github.com/PerplexSystems/nix-training/releases/latest) from GitHub Releases. The [QEMU image workflow](https://github.com/PerplexSystems/nix-training/actions/workflows/qemu-image.yml) also provides both artifacts for each successful run (retained for up to 90 days). The latest release is updated only after both builds pass the image check and boot to a login prompt. + +To build the same image locally on an x86_64 Linux host (with Nix): + +```sh +nix build .#qemu-image +``` + +The Makefile detects x86_64 or ARM64 hosts and provides the matching image, interactive QEMU boot, and automated boot, SSH, and sudo checks: + +```sh +make image +make run +make test +``` + +On Linux, `make image` builds the matching NixOS image. On macOS, it downloads the matching image from the latest release; `make run` needs QEMU, while `make test` also needs Nix. `make run` prints the guest login (`gambi` / `gambi`), forwards SSH to `127.0.0.1:2222`, and discards guest changes on exit. `make test` uses port `2223`, so both can run at once. Override `VM_SSH_PORT`, `TEST_SSH_PORT`, or `VM_MEMORY` on the `make` command line if needed. On ARM64, QEMU boots with UEFI firmware; set `VM_FIRMWARE` to a firmware file if QEMU cannot find `edk2-aarch64-code.fd` in its data directory. `make vm` builds the local VM launcher on Linux. + +For quick local experiments with Nix installed, build the VM launcher from the same guest configuration: + +```sh +make vm +QEMU_KERNEL_PARAMS=console=ttyS0 ./result-vm/bin/run-nix-training-vm -nographic +``` + +The launcher uses your host's Nix store and writes guest state to `nix-training.qcow2` in the current directory. The downloadable image includes its own Nix store. + +Run a downloaded file directly with QEMU, or use `make run` to select the correct command. This example is for x86_64; for a local build, use `result/nix-training-x86_64.qcow2` as the drive path: + +```sh +qemu-system-x86_64 -m 1024 -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic +``` + +Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The guest enables `nix-command` and `flakes`, so commands such as `nix flake show ` work inside it (remote flake inputs need network access). You can also add this to `~/.ssh/config`: + +``` +Host gambiconf + Hostname 127.0.0.1 + User gambi + Port 2222 + UserKnownHostsFile=/dev/null + StrictHostKeyChecking=no +``` + +Then connect to the VM and enter `gambi` when SSH prompts for the password: + +``` +ssh gambiconf +``` + --- Source: From 25f7549a57fec6b9edfae29b1e97ecdb8110a5f5 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Sun, 11 Oct 2026 19:52:47 -0400 Subject: [PATCH 3/6] feat: add QEMU builds --- .github/workflows/qemu-image.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 176c093..137cd51 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -1,4 +1,4 @@ -name: QEMU image +name: "[QEMU] Build and Publish NixOS Image" on: push: From 47eb393e9ec5f573bec887c3ebb1e169b7aaaa8d Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Sun, 11 Oct 2026 21:07:43 -0400 Subject: [PATCH 4/6] feat: add QEMU builds --- .github/workflows/qemu-image.yml | 8 +++ nixos/training-image.nix | 93 ++++++++++++++++++++++++++------ scripts/check-vm-image.sh | 10 ++-- scripts/run-vm.sh | 5 +- 4 files changed, 95 insertions(+), 21 deletions(-) diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 137cd51..1328afc 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -18,8 +18,14 @@ jobs: include: - arch: x86_64 runner: ubuntu-24.04 + boot_timeout: 180 + ssh_timeout: 60 - arch: aarch64 runner: ubuntu-24.04-arm + # The ARM runner has no KVM, so QEMU boots the guest with TCG + # emulation, which needs much longer to reach the login prompt. + boot_timeout: 900 + ssh_timeout: 180 runs-on: ${{ matrix.runner }} permissions: contents: read @@ -38,6 +44,8 @@ jobs: - name: Check image, boot, and SSH login env: VM_ARCH: ${{ matrix.arch }} + VM_BOOT_TIMEOUT: ${{ matrix.boot_timeout }} + VM_SSH_TIMEOUT: ${{ matrix.ssh_timeout }} run: nix develop .#ci --command bash scripts/check-vm-image.sh result/nix-training-${{ matrix.arch }}.qcow2 - uses: actions/upload-artifact@v4 with: diff --git a/nixos/training-image.nix b/nixos/training-image.nix index 9a2d9bd..41d4df9 100644 --- a/nixos/training-image.nix +++ b/nixos/training-image.nix @@ -5,11 +5,85 @@ pkgs, ... }: +let + inherit (pkgs.stdenv.hostPlatform) efiArch; +in { - imports = [ (modulesPath + "/virtualisation/disk-image.nix") ]; + imports = [ (modulesPath + "/image/repart.nix") ]; - image.baseName = "nix-training-${pkgs.stdenv.hostPlatform.parsed.cpu.name}"; - image.efiSupport = pkgs.stdenv.hostPlatform.isAarch64; + # Build the image with systemd-repart entirely in userspace, so no + # KVM-capable builder (e.g. GitHub's ARM runners) is required. + image.repart = { + enable = true; + name = "nix-training-${pkgs.stdenv.hostPlatform.parsed.cpu.name}"; + # Compress the final qcow2 with qemu-img instead of the raw image. + compression.enable = false; + # The Nix store is inode-heavy; mkfs.ext4 defaults are too low for it. + mkfsOptions.ext4 = [ + "-i" + "8192" + ]; + partitions = { + esp = { + contents = { + # Fallback bootloader path, so the image also boots on UEFI + # firmware without any NVRAM boot entries. + "/EFI/BOOT/BOOT${lib.toUpper efiArch}.EFI".source = + "${config.systemd.package}/lib/systemd/boot/efi/systemd-boot${efiArch}.efi"; + # Unified kernel image (kernel + initrd + cmdline), which + # systemd-boot discovers automatically in /EFI/Linux. + "/EFI/Linux/${config.system.boot.loader.ukiFile}".source = + "${config.system.build.uki}/${config.system.boot.loader.ukiFile}"; + }; + repartConfig = { + Type = "esp"; + Format = "vfat"; + Label = "ESP"; + # aarch64 kernels and initrds are roughly twice as large. + SizeMinBytes = if pkgs.stdenv.hostPlatform.isx86_64 then "512M" else "1G"; + }; + }; + root = { + storePaths = [ config.system.build.toplevel ]; + repartConfig = { + Type = "root"; + Format = "ext4"; + Label = "nixos"; + Minimize = "guess"; + SizeMinBytes = "8G"; + }; + }; + }; + }; + + # Convert the raw repart image to a compressed qcow2 within the same + # derivation, so the large raw file never lands in the Nix store. + system.build.image = lib.mkForce ( + config.image.repart.image.overrideAttrs (previousAttrs: { + nativeBuildInputs = previousAttrs.nativeBuildInputs ++ [ pkgs.qemu-utils ]; + + postBuild = '' + qemu-img convert -f raw -O qcow2 -c ${config.image.baseName}.raw ${config.image.baseName}.qcow2 + rm ${config.image.baseName}.raw + ''; + }) + ); + + boot.loader.systemd-boot.enable = true; + + boot.growPartition = true; + + fileSystems = { + "/" = { + device = "/dev/disk/by-label/nixos"; + autoResize = true; + fsType = "ext4"; + }; + "/boot" = { + device = "/dev/disk/by-label/ESP"; + fsType = "vfat"; + }; + }; # Do not embed the full nixpkgs source just to provide a local flake registry. nixpkgs.flake.setNixPath = false; @@ -23,17 +97,4 @@ "virtio_pci" "virtio_blk" ]; - - # The standard disk image module copies the entire nixpkgs source as a channel. - # Omit it so the downloadable image contains only the installed system. - system.build.image = lib.mkForce ( - import (pkgs.path + "/nixos/lib/make-disk-image.nix") { - inherit config lib pkgs; - inherit (config.virtualisation) diskSize; - inherit (config.image) baseName; - format = "qcow2-compressed"; - partitionTableType = if config.image.efiSupport then "efi" else "legacy"; - copyChannel = false; - } - ); } diff --git a/scripts/check-vm-image.sh b/scripts/check-vm-image.sh index c841998..cfdef1c 100644 --- a/scripts/check-vm-image.sh +++ b/scripts/check-vm-image.sh @@ -3,6 +3,8 @@ set -euo pipefail image=${1:?Usage: check-vm-image.sh IMAGE.qcow2} ssh_port=${VM_SSH_PORT:-2222} +boot_timeout=${VM_BOOT_TIMEOUT:-180} +ssh_timeout=${VM_SSH_TIMEOUT:-60} qemu-img check -f qcow2 "$image" boot_log=$(mktemp) @@ -20,7 +22,7 @@ VM_HEADLESS=1 VM_SSH_PORT="$ssh_port" bash scripts/run-vm.sh "$image" \ >"$boot_log" 2>&1 & qemu_pid=$! -for ((attempt = 0; attempt < 180; attempt++)); do +for ((attempt = 0; attempt < boot_timeout; attempt++)); do if grep -q 'nix-training login:' "$boot_log"; then echo "VM reached the serial login prompt." break @@ -35,11 +37,11 @@ done if ! grep -q 'nix-training login:' "$boot_log"; then cat "$boot_log" - echo "VM did not reach the login prompt within 180 seconds." >&2 + echo "VM did not reach the login prompt within ${boot_timeout} seconds." >&2 exit 1 fi -for ((attempt = 0; attempt < 60; attempt++)); do +for ((attempt = 0; attempt < ssh_timeout; attempt++)); do if ssh_output=$(SSHPASS=gambi sshpass -e ssh \ -F /dev/null \ -o BatchMode=no \ @@ -73,5 +75,5 @@ for ((attempt = 0; attempt < 60; attempt++)); do done cat "$boot_log" -echo "SSH password login did not succeed within 60 seconds." >&2 +echo "SSH password login did not succeed within ${ssh_timeout} seconds." >&2 exit 1 diff --git a/scripts/run-vm.sh b/scripts/run-vm.sh index b604df6..40f61f4 100644 --- a/scripts/run-vm.sh +++ b/scripts/run-vm.sh @@ -32,7 +32,10 @@ if [[ $arch == aarch64 ]]; then ) qemu=qemu-system-aarch64 else - qemu_args+=(-machine "accel=$accel") + qemu_args+=( + -machine "accel=$accel" + -bios "${VM_FIRMWARE:-edk2-x86_64-code.fd}" + ) qemu=qemu-system-x86_64 fi From 39ac2c2f473023395130c33ecc89ba1e23fc0cf4 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Mon, 12 Oct 2026 13:26:49 -0400 Subject: [PATCH 5/6] nix: fix qemu build --- README.md | 4 ++-- scripts/run-vm.sh | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 7cebc0e..c9da433 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ make run make test ``` -On Linux, `make image` builds the matching NixOS image. On macOS, it downloads the matching image from the latest release; `make run` needs QEMU, while `make test` also needs Nix. `make run` prints the guest login (`gambi` / `gambi`), forwards SSH to `127.0.0.1:2222`, and discards guest changes on exit. `make test` uses port `2223`, so both can run at once. Override `VM_SSH_PORT`, `TEST_SSH_PORT`, or `VM_MEMORY` on the `make` command line if needed. On ARM64, QEMU boots with UEFI firmware; set `VM_FIRMWARE` to a firmware file if QEMU cannot find `edk2-aarch64-code.fd` in its data directory. `make vm` builds the local VM launcher on Linux. +On Linux, `make image` builds the matching NixOS image. On macOS, it downloads the matching image from the latest release; `make run` needs QEMU, while `make test` also needs Nix. `make run` prints the guest login (`gambi` / `gambi`), forwards SSH to `127.0.0.1:2222`, and discards guest changes on exit. `make test` uses port `2223`, so both can run at once. Override `VM_SSH_PORT`, `TEST_SSH_PORT`, or `VM_MEMORY` on the `make` command line if needed. QEMU boots the image with UEFI firmware on both architectures; set `VM_FIRMWARE` to a firmware file if QEMU cannot find `edk2-x86_64-code.fd` or `edk2-aarch64-code.fd` in its data directory. `make vm` builds the local VM launcher on Linux. For quick local experiments with Nix installed, build the VM launcher from the same guest configuration: @@ -80,7 +80,7 @@ The launcher uses your host's Nix store and writes guest state to `nix-training. Run a downloaded file directly with QEMU, or use `make run` to select the correct command. This example is for x86_64; for a local build, use `result/nix-training-x86_64.qcow2` as the drive path: ```sh -qemu-system-x86_64 -m 1024 -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic +qemu-system-x86_64 -m 1024 -machine q35 -drive if=pflash,format=raw,readonly=on,file=/path/to/edk2-x86_64-code.fd -drive file=nix-training-x86_64.qcow2,format=qcow2,if=virtio -nic user,hostfwd=tcp:127.0.0.1:2222-:22 -nographic ``` Log in on the console as `gambi` with password `gambi`, or connect with `ssh -p 2222 gambi@127.0.0.1`. The guest enables `nix-command` and `flakes`, so commands such as `nix flake show ` work inside it (remote flake inputs need network access). You can also add this to `~/.ssh/config`: diff --git a/scripts/run-vm.sh b/scripts/run-vm.sh index 40f61f4..73647ae 100644 --- a/scripts/run-vm.sh +++ b/scripts/run-vm.sh @@ -24,6 +24,27 @@ qemu_args=( -drive "file=$image,format=qcow2,if=virtio,snapshot=on" ) +# Resolve a bare firmware name against the QEMU data directories. +find_firmware() { + local firmware=$1 + if [[ -e $firmware ]]; then + printf '%s\n' "$firmware" + return 0 + fi + local qemu_bin candidate + qemu_bin=$(command -v "qemu-system-${arch}") + for candidate in \ + "$(dirname "$(dirname "$qemu_bin")")/share/qemu/$firmware" \ + "/usr/share/qemu/$firmware" + do + if [[ -e $candidate ]]; then + printf '%s\n' "$candidate" + return 0 + fi + done + return 1 +} + if [[ $arch == aarch64 ]]; then qemu_args+=( -machine "virt,accel=$accel" @@ -32,9 +53,16 @@ if [[ $arch == aarch64 ]]; then ) qemu=qemu-system-aarch64 else + # QEMU's bundled x86_64 EDK2 image is too large for -bios, so attach it + # as a read-only pflash device instead. + firmware=${VM_FIRMWARE:-edk2-x86_64-code.fd} + if ! firmware=$(find_firmware "$firmware"); then + echo "UEFI firmware '${VM_FIRMWARE:-edk2-x86_64-code.fd}' not found; set VM_FIRMWARE." >&2 + exit 1 + fi qemu_args+=( - -machine "accel=$accel" - -bios "${VM_FIRMWARE:-edk2-x86_64-code.fd}" + -machine "q35,accel=$accel" + -drive "if=pflash,format=raw,readonly=on,file=$firmware" ) qemu=qemu-system-x86_64 fi From e7443317d1d60720223cf77d218daacd86d45e84 Mon Sep 17 00:00:00 2001 From: Marcos Benevides Date: Mon, 12 Oct 2026 13:51:41 -0400 Subject: [PATCH 6/6] nix: fix qemu build --- .github/workflows/qemu-image.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/qemu-image.yml b/.github/workflows/qemu-image.yml index 1328afc..ddeffd6 100644 --- a/.github/workflows/qemu-image.yml +++ b/.github/workflows/qemu-image.yml @@ -32,6 +32,10 @@ jobs: steps: - uses: actions/checkout@v6 - uses: cachix/install-nix-action@v31 + - name: Enable unprivileged user namespaces + run: | + sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + unshare --map-root-user true - name: Restore and save Nix store uses: nix-community/cache-nix-action@v7 with: