{ pkgs ? import {} , kernelPackages ? pkgs.linuxPackages_latest }: let inherit (pkgs) lib; nixos = import (pkgs.path + "/nixos") { inherit (pkgs.stdenv.hostPlatform) system; configuration = { modulesPath, ... }: { imports = [ (modulesPath + "/profiles/minimal.nix") (modulesPath + "/profiles/perlless.nix") ]; # 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" ]; 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" ]; }; fileSystems."/nix/store" = { device = "/dev/vda"; fsType = "erofs"; options = [ "ro" "nodev" "nosuid" ]; }; fileSystems."/xchg" = { device = "/dev/vdb"; fsType = "ext4"; noCheck = true; options = [ "x-systemd.automount" "nofail" ]; }; 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; environment.etc."resolv.conf".text = "nameserver 9.9.9.9\n"; 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; nix.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; 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 # 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" ]; }; }; }; inherit (nixos.config.system.build) toplevel kernel initialRamdisk; 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" "@TTY_ARGS@" ]); }; network-interfaces = [{ iface_id = "eth0"; host_dev_name = "@TAP@"; # see host.nix guest_mac = "@MAC@"; }]; drives = [{ drive_id = "store"; path_on_host = "@STORE_IMAGE@"; is_root_device = false; is_read_only = true; } { drive_id = "xchg"; path_on_host = "@XCHG_IMAGE@"; is_root_device = false; is_read_only = false; }]; machine-config = { vcpu_count = 2; mem_size_mib = 1024; }; }); in pkgs.writeShellScriptBin "run-firecracker-vm" /* sh */ '' # usage: run-firecracker-vm [STORE-PATH...] # Packs the closure of the guest system (plus any given store paths) into # an erofs image, which the guest mounts read-only at /nix/store. # The image of the last closure is kept in the cache directory. # The directory xchg (in the current working directory) is copied into an # ext4 image, which the guest mounts at /xchg, and copied back when the # guest exits. set -efu export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.e2fsprogs pkgs.findutils pkgs.gnugrep pkgs.gnused pkgs.gnutar pkgs.util-linux pkgs.erofs-utils pkgs.nix pkgs.firecracker ]} tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT cache=''${XDG_CACHE_HOME:-$HOME/.cache}/run-firecracker-vm mkdir -p "$cache" nix-store -qR ${toplevel} "$@" > "$tmp"/store-paths img=$cache/$(sha256sum < "$tmp"/store-paths | cut -c-32).img if ! test -e "$img"; then tar -c -P --verbatim-files-from \ --transform 'flags=rSh;s|/nix/store/||' \ --files-from "$tmp"/store-paths \ | mkfs.erofs --quiet --tar=f --force-uid=0 --force-gid=0 --hard-dereference -T 0 "$img.$$" mv "$img.$$" "$img" find "$cache" -type f ! -path "$img" -delete 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} tty_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" tty_args="$tty_args systemd.tty.rows.ttyS0=$rows systemd.tty.columns.ttyS0=$cols" fi # Take the first tap device (see host.nix) that no other VM holds. The # lock is held until the script exits. The MAC address is derived from # the tap's number, so the VM gets the same DHCP lease every time. tap= for t in $(find /sys/class/net -maxdepth 1 -name 'fctap*' -printf '%f\n' | sort -V); do exec {lock}>"''${XDG_RUNTIME_DIR:-/tmp}/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*, see host.nix" >&2 exit 1 fi n=''${tap#fctap} mac=$(printf '06:00:ac:10:%02x:%02x' $((n >> 8 & 255)) $((n & 255))) mkdir -p xchg truncate -s 1G "$tmp"/xchg.img mkfs.ext4 -q -F -d xchg "$tmp"/xchg.img sed \ -e "s|@STORE_IMAGE@|$img|" \ -e "s|@XCHG_IMAGE@|$tmp/xchg.img|" \ -e "s|@TTY_ARGS@|$tty_args|" \ -e "s|@TAP@|$tap|" \ -e "s|@MAC@|$mac|" \ ${config} > "$tmp"/config.json status=0 firecracker --no-api --config-file "$tmp"/config.json || status=$? rm -rf xchg.new mkdir xchg.new debugfs -R 'rdump / xchg.new' "$tmp"/xchg.img 2>&1 | { grep -v -e '^debugfs [0-9]' -e 'Operation not permitted while changing ownership' >&2 || :; } rm -rf xchg xchg.new/lost+found mv xchg.new xchg exit $status ''