diff options
| author | tv <tv@krebsco.de> | 2026-11-21 02:32:31 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-21 04:03:44 +0100 |
| commit | 4e35ef641c9bca1f63c3248877295fe61d4c1d20 (patch) | |
| tree | 60d2b6e0847d07beb3e06b75cfe73ac713aae86c /pkgs | |
| parent | af7894cf1d695551ffc2211314d6f9bc5cc05feb (diff) | |
run-firecracker-vm: nix as a layer, a read-only store without it
The base system had nix, the nix-daemon, the host's store and nixpkgs
via 9P, and a writable store on a drive, a scratch file without --store.
Now all of that is in a layer of its own, layers/nix.nix, and the base
system has neither nix nor nix-daemon in its closure: its store is its
images, read-only, an overlay of them, or with a single image, the image
itself, as overlayfs needs at least two lower layers without an upper
one. This can become the base layer for guests that only run services.
As a layer, nix gets an image of its own: put first, it's the same for
all guests with nix, instead of in the image of whichever layer wants
nix. It sets fc.nix, which the run script goes by, and nix.enable;
setting nix.enable without it fails an assertion, as the run script
wouldn't give the guest the drive for its store.
The image decides, so the run script checks that the options fit it: a
guest with nix requires --store (no more scratch store), and one
without refuses --store, --store-size, --nixpkgs and --nixpkgs-cache.
Without the rw-store drive, the images come first, and home after them;
the store and nixpkgs aren't served, there's no fc.registration, and
the initrd doesn't mount anything via 9P. The run script now waits for
each of the 9P servers it starts, not only the store's.
Diffstat (limited to 'pkgs')
| -rw-r--r-- | pkgs/run-firecracker-vm/default.nix | 283 |
1 files changed, 121 insertions, 162 deletions
diff --git a/pkgs/run-firecracker-vm/default.nix b/pkgs/run-firecracker-vm/default.nix index 4c266c0..2035613 100644 --- a/pkgs/run-firecracker-vm/default.nix +++ b/pkgs/run-firecracker-vm/default.nix @@ -44,21 +44,20 @@ let # The system of the first n layers (the base system being layer 0), # with n + 1 images. - evalSystem = n: let - # The overlay's lower layers: the images, then the host's store. - lowerdirs = lib.genList (k: "/nix/.image/${toString k}") (n + 1) ++ [ "/nix/.host-store" ]; - in import (pkgs.path + "/nixos") { + evalSystem = n: import (pkgs.path + "/nixos") { inherit (pkgs.stdenv.hostPlatform) system; # The host's pkgs, for layers whose imports need packages, like a # module from a source fetched with fetchFromGitHub: the guest's pkgs # depend on the modules, so imports can't use them. specialArgs.hostPkgs = pkgs; - configuration = { config, modulesPath, ... }: { + configuration = { config, modulesPath, ... }: let + lowerdirs = lib.genList (k: "/nix/.image/${toString k}") (n + 1); + in { imports = [ (modulesPath + "/profiles/minimal.nix") (modulesPath + "/profiles/perlless.nix") - { fileSystems = imageFileSystems (n + 1); } - { systemd.generators.fc-home = homeGenerator (drive (n + 2)); } + ({ config, ... }: { fileSystems = imageFileSystems (firstImage config) (n + 1); }) + ({ config, ... }: { systemd.generators.fc-home = homeGenerator (drive (firstImage config + n + 1)); }) { # For a layer whose state is in /home: the run script then # refuses to start the guest without --home. @@ -67,9 +66,32 @@ let default = false; description = "Whether the guest needs a /home drive (--home)."; }; + # For layers/nix.nix, which sets it: the run script gives the + # guest the drive for the rw-store, and so on. + options.fc.nix = lib.mkOption { + type = lib.types.bool; + default = false; + internal = true; + description = "Whether the guest has layers/nix.nix."; + }; + options.fc.mountVsock9p = lib.mkOption { + type = lib.types.package; + default = mountVsock9p; + readOnly = true; + internal = true; + description = "mount.vsock9p, for layers/nix.nix's initrd."; + }; } ] ++ lib.take n layers; + # nix only with layers/nix.nix, which the run script needs to know + # about. + nix.enable = lib.mkDefault false; + assertions = [{ + assertion = config.nix.enable == config.fc.nix; + message = "nix.enable: use run-firecracker-vm's layers/nix.nix instead."; + }]; + # Activate and switch root from the initrd with a single program, # instead of bash running prepare-root and the activation script. system.nixos-init.enable = true; @@ -91,119 +113,26 @@ let fsType = "tmpfs"; options = [ "mode=755" ]; }; - # The store, in layers: the guest's own closure from images (see - # imageFileSystems and images below), as reading them is much faster - # than reading the host's store, which comes next, read-only via 9P - # over vsock (see mount.vsock9p and the run script), for anything - # else, like nixpkgs; then the first drive on top, so nix can add to - # the store (a scratch file, or one that persists, see the run - # script). The host's store doesn't change under a path, so 9P may - # cache freely. Store paths don't collide, so the order of the - # lower layers doesn't matter. - fileSystems."/nix/.host-store" = { - device = "565"; - fsType = "vsock9p"; - options = [ "ro" "cache=loose" ]; - noCheck = true; - neededForBoot = true; - }; - fileSystems."/nix/.rw-store" = { - device = drive 0; - fsType = "ext4"; - options = [ "noatime" ]; - noCheck = true; - neededForBoot = true; - }; - # nix's database goes there, too, so it matches what's in the store. - fileSystems."/nix/var" = { - device = "/nix/.rw-store/var"; - fsType = "none"; - options = [ "bind" ]; - depends = [ "/nix/.rw-store" ]; - }; - systemd.services.nix-var-dir = { - requiredBy = [ "nix-var.mount" ]; - before = [ "nix-var.mount" ]; - unitConfig.DefaultDependencies = false; - unitConfig.RequiresMountsFor = "/nix/.rw-store"; - serviceConfig.Type = "oneshot"; - serviceConfig.ExecStart = "${pkgs.coreutils}/bin/mkdir -p -m 0755 /nix/.rw-store/var"; - }; - fileSystems."/nix/store".overlay = { - lowerdir = lowerdirs; - upperdir = "/nix/.rw-store/store"; - workdir = "/nix/.rw-store/work"; - }; - # nix in the guest deletes a path in the store that isn't in its - # database before it adds it, like the host's store's paths. On the - # overlay, deleting a lower layer's path leaves a whiteout in the rw-store, - # or an opaque directory, which is what nix adds again, if it gets that - # far. With a persistent rw-store, that hides the path from any - # later image, too. Any path that a lower layer has is complete - # there, and the same as anything of that name in the rw-store, so - # drop such paths from the rw-store before mounting the overlay. - boot.initrd.systemd.services.fc-rw-store-unshadow = { - requiredBy = [ "sysroot-nix-store.mount" ]; - before = [ "sysroot-nix-store.mount" ]; - unitConfig.DefaultDependencies = false; - unitConfig.RequiresMountsFor = map (d: "/sysroot" + d) ([ "/nix/.rw-store" ] ++ lowerdirs); - serviceConfig.Type = "oneshot"; - script = '' - cd /sysroot/nix/.rw-store/store 2>/dev/null || exit 0 - for p in *; do - for d in ${toString (map (d: "/sysroot" + d) lowerdirs)}; do - if test -e "$d/$p"; then - rm -rf "$p" - break - fi - done - done - ''; - }; + # The store: the guest's own closure from images (see + # imageFileSystems and images below), read-only, or with + # layers/nix.nix, writable. Without an upper layer, overlayfs needs + # at least two lower ones: a single image is the store itself + # (mounted a second time). + fileSystems."/nix/store" = + if lib.length lowerdirs > 1 then { + overlay.lowerdir = lowerdirs; + } else + (imageFileSystems (firstImage config) 1)."/nix/.image/0"; - # nix, with the host's nixpkgs for nix-shell -p and the like, at - # /nixpkgs (see below). Root goes through the daemon too, so the - # paths of the guest's closure get registered (fc.registration, see - # the run script) before anything uses the store, and only once - # something does, not at boot. The rest of the host's store is - # there, too, but not registered. - nix.nixPath = [ "nixpkgs=/nixpkgs" ]; - environment.variables.NIX_REMOTE = "daemon"; - systemd.services.nix-load-db = { - requiredBy = [ "nix-daemon.service" ]; - before = [ "nix-daemon.service" ]; - serviceConfig.Type = "oneshot"; - serviceConfig.RemainAfterExit = true; - # With a persistent store, paths from an earlier image or host - # store may be gone; --verify removes them from the database. - script = '' - for arg in $(cat /proc/cmdline); do - case $arg in fc.registration=*) - ${config.nix.package.out}/bin/nix-store --load-db < "''${arg#*=}" - esac - done - ${config.nix.package.out}/bin/nix-store --verify - ''; - }; fileSystems."/xchg" = { device = "564"; fsType = "vsock9p"; noCheck = true; options = [ "x-systemd.automount" "nofail" ]; }; - # The host's nixpkgs, wherever it is (see the run script): no copy - # to the store needed, which is what made evaluating this take ~20s. - fileSystems."/nixpkgs" = { - device = "566"; - fsType = "vsock9p"; - noCheck = true; - options = [ "ro" "x-systemd.automount" "nofail" ]; - }; system.fsPackages = [ (pkgs.runCommand "mount.vsock9p" { } "install -D ${mountVsock9p} $out/bin/mount.vsock9p") ]; - boot.initrd.systemd.extraBin."mount.vsock9p" = mountVsock9p; - boot.initrd.systemd.storePaths = [ pkgs.socat pkgs.util-linux ]; services.getty.autologinUser = "root"; @@ -359,11 +288,15 @@ let # The guest's device of drive k (0: vda), see drives below. drive = k: "/dev/vd${lib.elemAt (lib.stringToCharacters "abcdefghijklmnopqrstuvwxyz") k}"; - # The images, read-only drives after the rw-store (vda): image k (of - # layer k) is drive k + 1. - imageFileSystems = count: lib.listToAttrs (lib.genList (k: + # The drive of image 0: after the rw-store (vda), if there is one, i.e. + # with layers/nix.nix, else the first. + firstImage = config: if config.fc.nix then 1 else 0; + + # The images, read-only drives from drive first on: image k (of layer + # k) is drive first + k. + imageFileSystems = first: count: lib.listToAttrs (lib.genList (k: lib.nameValuePair "/nix/.image/${toString k}" { - device = drive (k + 1); + device = drive (first + k); fsType = "erofs"; options = [ "ro" "nodev" "nosuid" ]; neededForBoot = true; @@ -373,6 +306,7 @@ let nixos = lib.last systems; toplevels = map (s: s.config.system.build.toplevel) systems; inherit (nixos.config.system.build) toplevel kernel initialRamdisk; + nix = nixos.config.fc.nix; # layers/nix.nix # A layer's name, for its image's: its file's, if it's a file (for # .../NAME/default.nix, NAME). @@ -406,7 +340,9 @@ let initrd_path = "${initialRamdisk}/${nixos.config.system.boot.loader.initrdFile}"; boot_args = toString (nixos.config.boot.kernelParams ++ [ "init=${toplevel}/init" + ] ++ lib.optional nix "fc.registration=${pkgs.closureInfo { rootPaths = [ toplevel ]; }}/registration" + ++ [ "@ARGS@" ]); }; @@ -417,12 +353,12 @@ let }]; # In this order: vda, vdb, ... (see drive). The run script drops home # without --home. - drives = [{ + drives = lib.optional nix { drive_id = "rw-store"; path_on_host = "@RW_STORE@"; is_root_device = false; is_read_only = false; - }] ++ lib.imap0 (k: image: { + } ++ lib.imap0 (k: image: { drive_id = "layer-${toString k}"; path_on_host = "${image}"; is_root_device = false; @@ -450,22 +386,24 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' # [--nixpkgs DIR] [--nixpkgs-cache MODE] # [--egress LIST] [--name NAME] [--vcpus N] # [--ssh-host-key FILE] - # The guest gets the host's store, read-only, via 9P over vsock, and the - # directory xchg (in the current working directory) at /xchg, the same - # way. VMs started in the same directory share it. Also the same way, - # nixpkgs at /nixpkgs, read-only: DIR, by default the nixpkgs the guest - # was built from. It isn't cached in the guest, so changes show up - # right away, but evaluating is slow. --nixpkgs-cache sets 9P's cache - # mode for it: loose caches everything (fast, but changes may not show - # up while the guest runs), mmap and readahead some (see the kernel's - # Documentation/filesystems/9p.rst), none is the default. - # What nix in the guest adds to the store goes to a scratch file, removed - # when the guest exits, or with --store, to FILE, which keeps it across - # boots (created if it doesn't exist, of --store-size, default 16G; the - # file is sparse, so that's only an upper limit). /home is part of the - # guest's root file system, gone when it exits, or with --home, on FILE, - # likewise (of --home-size, default 16G). A guest with fc.home.required - # (set by a layer) doesn't start without --home. + # The guest gets the directory xchg (in the current working directory) + # at /xchg, via 9P over vsock. VMs started in the same directory share + # it. Its store is read-only, unless it has nix (layers/nix.nix). + # A guest with nix gets the host's store, read-only, the same way, and + # also nixpkgs at /nixpkgs, read-only: DIR, by default the nixpkgs the + # guest was built from. It isn't cached in the guest, so changes show + # up right away, but evaluating is slow. --nixpkgs-cache sets 9P's + # cache mode for it: loose caches everything (fast, but changes may not + # show up while the guest runs), mmap and readahead some (see the + # kernel's Documentation/filesystems/9p.rst), none is the default. + # What nix in the guest adds to the store goes to FILE (--store, which a + # guest with nix requires, and one without refuses, like --store-size, + # --nixpkgs and --nixpkgs-cache), which keeps it across boots (created + # if it doesn't exist, of --store-size, default 16G; the file is sparse, + # so that's only an upper limit). /home is part of the guest's root + # file system, gone when it exits, or with --home, on FILE, likewise (of + # --home-size, default 16G). A guest with fc.home.required (set by a + # layer) doesn't start without --home. # --mem-size sets the guest's memory, in MiB (default 1024). # The guest's egress goes by the user's whitelist LIST (default: the # VM's name, or without one, default), see modules/host and fc-egress. @@ -492,16 +430,17 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' vcpus=2 ssh_host_key=''${XDG_DATA_HOME:-$HOME/.local/share}/run-firecracker-vm/ssh_host_ed25519_key nixpkgs=${lib.escapeShellArg (toString pkgs.path)} + nix_opt= # the last option that's only for a guest with nix while test $# -gt 0; do case $1 in --*=*) set -- "''${1%%=*}" "''${1#*=}" "''${@:2}"; continue ;; - --store) rw_store=$2; shift 2 ;; - --store-size) rw_store_size=$2; shift 2 ;; + --store) rw_store=$2; nix_opt=$1; shift 2 ;; + --store-size) rw_store_size=$2; nix_opt=$1; shift 2 ;; --home) home=$2; shift 2 ;; --home-size) home_size=$2; shift 2 ;; --mem-size) mem_size=$2; shift 2 ;; - --nixpkgs) nixpkgs=$2; shift 2 ;; - --nixpkgs-cache) args="$args fc.9p566=cache=$2"; shift 2 ;; + --nixpkgs) nixpkgs=$2; nix_opt=$1; shift 2 ;; + --nixpkgs-cache) args="$args fc.9p566=cache=$2"; nix_opt=$1; shift 2 ;; --egress) egress=$2; shift 2 ;; --name) name=$2; shift 2 ;; --vcpus) vcpus=$2; shift 2 ;; @@ -517,6 +456,17 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' exit 1 fi ''} + ${if nix then '' + if test -z "$rw_store"; then + echo "$0: the guest has nix, whose store is on a drive: --store FILE is required" >&2 + exit 1 + fi + '' else '' + if test -n "$nix_opt"; then + echo "$0: $nix_opt: the guest has no nix (see layers/nix.nix)" >&2 + exit 1 + fi + ''} if ! printf %s "$mem_size" | grep -qxE '[1-9][0-9]*'; then echo "$0: bad memory size: $mem_size (MiB, a number)" >&2 exit 1 @@ -549,12 +499,11 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' exit 1 fi - # disk VAR FILE SIZE NAME: sets VAR to the absolute path of FILE, an ext4 - # image, created (sparse, of SIZE) if it doesn't exist, or without FILE, - # of a scratch one, removed on exit; locked while the guest runs, as two - # guests with the same file would wreck it. + # disk VAR FILE SIZE: sets VAR to the absolute path of FILE, an ext4 + # image, created (sparse, of SIZE) if it doesn't exist; locked while the + # guest runs, as two guests with the same file would wreck it. disk() { - local f=''${2:-$tmp/$4.img} lock + local f=$2 lock if ! test -e "$f"; then truncate -s "$3" "$f" mkfs.ext4 -q -F "$f" @@ -567,9 +516,11 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' fi printf -v "$1" %s "$f" } - disk rw_store "$rw_store" "$rw_store_size" rw-store + if test -n "$rw_store"; then + disk rw_store "$rw_store" "$rw_store_size" + fi if test -n "$home"; then - disk home "$home" "$home_size" home + disk home "$home" "$home_size" args="$args fc.home" fi @@ -646,27 +597,35 @@ pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' fi mac=$(printf '06:00:ac:10:%02x:%02x' $((n >> 8 & 255)) $((n & 255))) - # The 9P servers, for the store, /xchg, and nixpkgs, one each per VM. - # They run as the user running this script: xchg's files end up owned by - # the user, and the store is read-only to them. When the guest connects to - # vsock port PORT on the host (CID 2), Firecracker connects to the socket - # uds_path_PORT. unpfs listens on ADDR:PORT (from unix!ADDR!PORT), hence - # the colon at the end of uds_path. RUST_LOG=off silences its logging - # of failed requests (like walking to a file that doesn't exist), fatal - # errors still go to stderr. The store has to be served before the - # guest's initrd wants it. + # The 9P servers, for /xchg, the SSH host key, and with nix, the store + # and nixpkgs, one each per VM. They run as the user running this + # script: xchg's files end up owned by the user, and the store is + # read-only to them. When the guest connects to vsock port PORT on the + # host (CID 2), Firecracker connects to the socket uds_path_PORT. unpfs + # listens on ADDR:PORT (from unix!ADDR!PORT), hence the colon at the end + # of uds_path. RUST_LOG=off silences its logging of failed requests + # (like walking to a file that doesn't exist), fatal errors still go to + # stderr. They have to be served before the guest wants them, the + # store before its initrd does. vsock=$tmp/vsock: + servers= + ports= + serve() { + RUST_LOG=off unpfs "unix!$tmp/vsock!_$1" "$2" > /dev/null & + servers="$servers $!" + ports="$ports $1" + } mkdir -p xchg - RUST_LOG=off unpfs "unix!$tmp/vsock!_565" /nix/store > /dev/null & - store=$! - RUST_LOG=off unpfs "unix!$tmp/vsock!_564" xchg > /dev/null & - xchg=$! - RUST_LOG=off unpfs "unix!$tmp/vsock!_566" "$nixpkgs" > /dev/null & - nixpkgs_server=$! - RUST_LOG=off unpfs "unix!$tmp/vsock!_567" "$tmp"/ssh > /dev/null & - ssh_server=$! - trap 'kill $store $xchg $nixpkgs_server $ssh_server; rm -rf "$tmp"; if test -n "$vm"; then : > "$vm"; if test -w "$vm.name"; then : > "$vm.name"; fi; fi' EXIT - while ! test -S "$vsock"_565; do sleep 0.01; done + serve 564 xchg + serve 567 "$tmp"/ssh + ${lib.optionalString nix '' + serve 565 /nix/store + serve 566 "$nixpkgs" + ''} + trap 'kill $servers; rm -rf "$tmp"; if test -n "$vm"; then : > "$vm"; if test -w "$vm.name"; then : > "$vm.name"; fi; fi' EXIT + for port in $ports; do + while ! test -S "$vsock"_$port; do sleep 0.01; done + done sed \ -e "s|@ARGS@|$args|" \ |
