{ pkgs ? import {} , kernelPackages ? pkgs.linuxPackages_latest # The CA of the host's egress proxy (see modules/host), if it's there. , caCert ? "/var/lib/fcbr0-egress/ca.pem" # NixOS modules, each a layer on top of the ones before, the first on # top of the base system (below). The guest runs the top layer's # system; its store has an image per layer, each with only the store # paths the layers below don't have, so the images below stay the same # for any layers on top of them. , layers ? [ ] }: let inherit (pkgs) lib; # 9P over vsock, for the store and /xchg: mount -t vsock9p PORT DIR # mounts what the host serves on vsock port PORT (see the run script). # The kernel's 9P client can't do vsock itself, but it can use the # fds of a connected socket (trans=fd), which socat passes to mount as # stdin and stdout (nofork). Separate -o options, as socat would take # commas as its own option separators. In the initrd, too, for the # store. More options for PORT can come from the kernel command line, # as fc.9pPORT=OPTIONS (see --nixpkgs-cache in the run script); they come # last, so they win. mountVsock9p = pkgs.writeShellScript "mount.vsock9p" '' # usage: mount.vsock9p PORT DIR [-o OPTIONS] set -efu opts= add() { for o in ''${1//,/ }; do case $o in x-*|nofail|auto|noauto|defaults) ;; *) opts="$opts -o $o" esac done } if test "''${3-}" = -o; then add "$4" fi read -r cmdline < /proc/cmdline for arg in $cmdline; do case $arg in fc.9p$1=*) add "''${arg#*=}" esac done exec ${pkgs.socat}/bin/socat VSOCK-CONNECT:2:"$1" EXEC:"${pkgs.util-linux}/bin/mount -t 9p -o trans=fd -o rfdno=0 -o wfdno=1 -o version=9p2000.L -o msize=1048576$opts vsock9p $2",nofork ''; # The system of the first n layers (the base system being layer 0), # with n + 1 images. evalSystem = n: import (pkgs.path + "/nixos") { inherit (pkgs.stdenv.hostPlatform) system; configuration = { config, modulesPath, ... }: { imports = [ (modulesPath + "/profiles/minimal.nix") (modulesPath + "/profiles/perlless.nix") { fileSystems = imageFileSystems (n + 1); } { systemd.generators.fc-home = homeGenerator (drive (n + 2)); } ] ++ lib.take n layers; # 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; system.stateVersion = lib.trivial.release; boot.kernelPackages = kernelPackages; boot.initrd.allowMissingModules = true; # e.g. ahci, efivarfs with a cut-down kernel boot.initrd.kernelModules = [ "virtio_mmio" "virtio_blk" "erofs" "vmw_vsock_virtio_transport" "9p" "9pnet_fd" "overlay" ]; boot.kernelParams = [ "console=ttyS0" "reboot=k" "panic=1" "8250.nr_uarts=1" # only ttyS0 exists (stops 0x2f8/0x3e8/0x2e8 probing) # Passed to (initrd and stage 2) systemd's environment. Disables the # rate limit of 5 mount events per second, which stalls the boot. "SYSTEMD_DEFAULT_MOUNT_RATE_LIMIT_BURST=0" ]; fileSystems."/" = { 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 = lib.genList (k: "/nix/.image/${toString k}") (n + 1) ++ [ "/nix/.host-store" ]; upperdir = "/nix/.rw-store/store"; workdir = "/nix/.rw-store/work"; }; # 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"; systemd.targets.getty.wants = lib.mkForce [ ]; # no getty on tty1 # A fixed machine-id, so systemd doesn't consider every boot the first. environment.etc.machine-id.text = builtins.hashString "md5" "firecracker" + "\n"; networking.useDHCP = false; networking.resolvconf.enable = false; # The host resolves every name to itself and proxies TLS to allowed # names, decrypting some with certificates from its CA, see modules/host. environment.etc."resolv.conf".text = "nameserver 172.16.0.1\n"; security.pki.certificateFiles = lib.optional (builtins.pathExists caCert) (/. + caCert); systemd.network.enable = true; systemd.network.wait-online.enable = false; systemd.network.networks.eth = { matchConfig.Type = "ether"; networkConfig.DHCP = "ipv4"; # The default client identifier is derived from the machine-id, # which is the same in every VM, so they'd all get the same lease. dhcpV4Config.ClientIdentifier = "mac"; }; boot.bcache.enable = false; boot.enableContainers = false; boot.initrd.systemd.tpm2.enable = false; boot.kexec.enable = false; networking.firewall.enable = false; powerManagement.enable = false; programs.fuse.enable = false; programs.nano.enable = false; security.sudo.enable = false; services.fstrim.enable = false; services.lvm.enable = false; services.nscd.enable = false; services.resolved.enable = false; services.timesyncd.enable = false; system.nssModules = lib.mkForce [ ]; system.switch.enable = false; system.disableInstallerTools = true; # nixos-rebuild & co., i.e. python systemd.coredump.enable = false; systemd.oomd.enable = false; systemd.tpm2.enable = false; users.manageLingering = false; # /var is empty on every boot, which makes these run every time, # in the critical path to sysinit.target. systemd.suppressedSystemUnits = [ "systemd-journal-catalog-update.service" "systemd-update-done.service" ]; services.journald.storage = "volatile"; # don't flush to /var/log # Nothing to do here, but they'd still get started at boot, each # adding to the reads from the store. systemd.units = lib.genAttrs [ "dev-hugepages.mount" "dev-mqueue.mount" "modprobe@configfs.service" "modprobe@drm.service" "modprobe@efi_pstore.service" "sys-fs-fuse-connections.mount" "sys-kernel-config.mount" "sys-kernel-debug.mount" "sys-kernel-tracing.mount" "systemd-pstore.service" "systemd-vconsole-setup.service" ] (_: { enable = lib.mkForce false; }); # Of the generators systemd runs after switching root, only fstab and # getty have anything to do here. systemd.generators = lib.genAttrs [ "systemd-bless-boot-generator" "systemd-cryptsetup-generator" "systemd-debug-generator" "systemd-factory-reset-generator" "systemd-gpt-auto-generator" "systemd-hibernate-resume-generator" "systemd-import-generator" "systemd-integritysetup-generator" "systemd-run-generator" "systemd-ssh-generator" "systemd-system-update-generator" "systemd-tpm2-generator" "systemd-veritysetup-generator" ] (_: "/dev/null"); security.pam.services.login.lastlog.enable = lib.mkForce false; # Only login needs a wrapper (unix_chkpwd), so create them in parallel # to the rest of the boot instead of holding up sysinit.target. systemd.services.suid-sgid-wrappers = { wantedBy = lib.mkForce [ "systemd-user-sessions.service" ]; before = lib.mkForce [ "systemd-user-sessions.service" "shutdown.target" ]; }; }; }; # /home: part of / (the tmpfs), or with fc.home on the kernel command # line (--home, see the run script), the drive after the images (device). # A generator rather than fileSystems, so a guest without it doesn't wait # for the drive. homeGenerator = device: pkgs.writeShellScript "fc-home-generator" '' read -r cmdline < /proc/cmdline case " $cmdline " in *" fc.home "*) ;; *) exit 0 esac printf '%s\n' \ '[Unit]' 'Before=local-fs.target' \ '[Mount]' 'What=${device}' 'Where=/home' 'Type=ext4' 'Options=noatime' \ > "$1"/home.mount ${pkgs.coreutils}/bin/mkdir -p "$1"/local-fs.target.requires ${pkgs.coreutils}/bin/ln -s ../home.mount "$1"/local-fs.target.requires/home.mount ''; # 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: lib.nameValuePair "/nix/.image/${toString k}" { device = drive (k + 1); fsType = "erofs"; options = [ "ro" "nodev" "nosuid" ]; neededForBoot = true; }) count); systems = lib.genList evalSystem (lib.length layers + 1); nixos = lib.last systems; toplevels = map (s: s.config.system.build.toplevel) systems; inherit (nixos.config.system.build) toplevel kernel initialRamdisk; # Layer k's image: the store paths of its system's closure that aren't # in the closures of the layers below, as erofs image. images = lib.imap0 (k: top: pkgs.runCommand "firecracker-layer-${toString k}.img" { nativeBuildInputs = [ pkgs.erofs-utils pkgs.gnutar ]; closure = pkgs.closureInfo { rootPaths = [ top ]; }; below = map (t: pkgs.closureInfo { rootPaths = [ t ]; }) (lib.take k toplevels); } '' for b in $below; do cat $b/store-paths; done | sort -u > below sort $closure/store-paths | comm -23 - below | tar -c -P --verbatim-files-from \ --transform 'flags=rSh;s|^/nix/store/||' \ --files-from - | mkfs.erofs --quiet --tar=f --force-uid=0 --force-gid=0 --hard-dereference -T 0 $out '') toplevels; config = pkgs.writeText "firecracker.json" (builtins.toJSON { boot-source = { kernel_image_path = "${kernel.dev}/vmlinux"; initrd_path = "${initialRamdisk}/${nixos.config.system.boot.loader.initrdFile}"; boot_args = toString (nixos.config.boot.kernelParams ++ [ "init=${toplevel}/init" "fc.registration=${pkgs.closureInfo { rootPaths = [ toplevel ]; }}/registration" "@ARGS@" ]); }; network-interfaces = [{ iface_id = "eth0"; host_dev_name = "@TAP@"; # see modules/host guest_mac = "@MAC@"; }]; # In this order: vda, vdb, ... (see drive). The run script drops home # without --home. drives = [{ drive_id = "rw-store"; path_on_host = "@RW_STORE@"; is_root_device = false; is_read_only = false; }] ++ lib.imap0 (k: image: { drive_id = "layer-${toString k}"; path_on_host = "${image}"; is_root_device = false; is_read_only = true; }) images ++ [{ drive_id = "home"; path_on_host = "@HOME@"; is_root_device = false; is_read_only = false; }]; vsock = { guest_cid = 3; uds_path = "@VSOCK@"; }; machine-config = { vcpu_count = 2; mem_size_mib = 1024; }; }); in pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' # usage: run-firecracker-vm [--store FILE] [--store-size SIZE] # [--home FILE] [--home-size SIZE] # [--nixpkgs DIR] [--nixpkgs-cache MODE] # [--egress LIST] [--name NAME] # 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). # 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. --name names the VM, for # fc-egress and as the guest's host name; only one running VM of the # user's can have a given name. set -efu export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.e2fsprogs pkgs.findutils pkgs.gnugrep pkgs.gnused pkgs.jq pkgs.util-linux pkgs.firecracker pkgs.unpfs ]} usage() { echo "usage: $0 [--store FILE] [--store-size SIZE] [--home FILE] [--home-size SIZE] [--nixpkgs DIR] [--nixpkgs-cache MODE] [--egress LIST] [--name NAME]" } args= rw_store= rw_store_size=16G home= home_size=16G egress= name= nixpkgs=${lib.escapeShellArg (toString pkgs.path)} 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 ;; --home) home=$2; shift 2 ;; --home-size) home_size=$2; shift 2 ;; --nixpkgs) nixpkgs=$2; shift 2 ;; --nixpkgs-cache) args="$args fc.9p566=cache=$2"; shift 2 ;; --egress) egress=$2; shift 2 ;; --name) name=$2; shift 2 ;; -h|--help) usage; exit ;; *) usage >&2; exit 1 esac done egress=''${egress:-''${name:-default}} tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT # 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() { local f=''${2:-$tmp/$4.img} lock if ! test -e "$f"; then truncate -s "$3" "$f" mkfs.ext4 -q -F "$f" fi f=$(realpath "$f") exec {lock}<"$f" if ! flock -n "$lock"; then echo "$0: $f is in use by another VM" >&2 exit 1 fi printf -v "$1" %s "$f" } disk rw_store "$rw_store" "$rw_store_size" rw-store if test -n "$home"; then disk home "$home" "$home_size" home args="$args fc.home" fi # Tell systemd the terminal's type and size, so it doesn't query them via # ANSI sequences (and wait up to 333ms for each answer): PID 1 asks for # the type of /dev/console when starting (in the initrd and again after # switching root), and both type and size of ttyS0 when starting the getty. term=''${TERM:-dumb} args="$args systemd.tty.term.console=$term systemd.tty.term.ttyS0=$term" if size=$(stty size 2>/dev/null) && test "$size" != "0 0"; then read -r rows cols <<< "$size" args="$args systemd.tty.rows.ttyS0=$rows systemd.tty.columns.ttyS0=$cols" fi # Take the first tap device of the user's (see modules/host) that no other # VM holds. The lock is held until the script exits. The MAC address is # derived from the tap's number, as modules/host does, for the tap's # fixed address. # Lock files in a directory of the user's own: in /tmp, another user # could take them first. lockdir=''${XDG_RUNTIME_DIR:-/run/user/$(id -u)} if ! test -d "$lockdir" -a -O "$lockdir"; then echo "$0: $lockdir isn't a directory of $(id -un)'s; set XDG_RUNTIME_DIR" >&2 exit 1 fi tap= for t in $(find /sys/class/net -maxdepth 1 -name 'fctap*' -printf '%f\n' | sort -V); do test "$(cat /sys/class/net/$t/owner)" = "$(id -u)" || continue exec {lock}>"$lockdir/run-firecracker-vm.$t.lock" if flock -n "$lock"; then tap=$t break fi exec {lock}>&- done if test -z "$tap"; then echo "$0: no free tap device fctap* of $(id -un)'s, see modules/host" >&2 exit 1 fi n=''${tap#fctap} # The VM's name: held by a lock, like the tap, so it's unique among the # user's running VMs. Not like a tap's, so fc-egress can tell them # apart. if test -n "$name"; then if ! printf %s "$name" | grep -qxE '[A-Za-z0-9][A-Za-z0-9-]{0,62}' || printf %s "$name" | grep -qxE 'fctap[0-9]+'; then echo "$0: bad name: $name (letters, digits and -, not like a tap)" >&2 exit 1 fi exec {name_lock}>"$lockdir/run-firecracker-vm.name.$name.lock" if ! flock -n "$name_lock"; then echo "$0: a VM named $name is running already" >&2 exit 1 fi args="$args systemd.hostname=$name" fi # The guest's whitelist: modules/host goes by the name in the tap's file # in /run/fc-egress (emptied again when the guest exits, below). vm=/run/fc-egress/$tap if test -w "$vm"; then if ! printf %s "$egress" | grep -qxE '[A-Za-z0-9_-]+'; then echo "$0: bad list name: $egress" >&2 exit 1 fi if ! test -f "/var/lib/fc-egress/$(id -un)/$egress"; then echo "$0: no list $egress (see fc-egress), no egress" >&2 fi printf '%s\n' "$egress" > "$vm" if test -w "$vm.name"; then printf '%s\n' "$name" > "$vm.name" fi else vm= 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. vsock=$tmp/vsock: 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=$! trap 'kill $store $xchg $nixpkgs_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 sed \ -e "s|@ARGS@|$args|" \ -e "s|@VSOCK@|$vsock|" \ -e "s|@TAP@|$tap|" \ -e "s|@MAC@|$mac|" \ -e "s|@RW_STORE@|$rw_store|" \ -e "s|@HOME@|$home|" \ ${config} | if test -n "$home"; then cat; else jq 'del(.drives[] | select(.drive_id == "home"))'; fi \ > "$tmp"/config.json status=0 firecracker --no-api --config-file "$tmp"/config.json || status=$? exit $status ''