From 83b09ab2a025b68cc49db74f59aa71f6a67df0f0 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 15 Nov 2026 21:06:27 +0000 Subject: init firecracker NixOS guest Boot a NixOS guest in Firecracker and drop into a root shell on ttyS0. Firecracker can't share directories with the guest (no 9p or virtio-fs), so the host store is exposed as a read-only block device: run-firecracker-vm packs the guest system's closure, plus the closures of any store paths given as arguments, into a temporary erofs image, which the guest mounts at /nix/store. Root is a tmpfs. --- default.nix | 69 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 default.nix (limited to 'default.nix') diff --git a/default.nix b/default.nix new file mode 100644 index 0000000..a246ad4 --- /dev/null +++ b/default.nix @@ -0,0 +1,69 @@ +{ pkgs ? import {} }: +let + inherit (pkgs) lib; + + nixos = import (pkgs.path + "/nixos") { + inherit (pkgs) system; + configuration = { config, ... }: { + system.stateVersion = lib.trivial.release; + + boot.loader.grub.enable = false; + boot.initrd.kernelModules = [ "virtio_mmio" "virtio_blk" "erofs" ]; + boot.kernelParams = [ "console=ttyS0" "reboot=k" "panic=1" ]; + + fileSystems."/" = { + fsType = "tmpfs"; + options = [ "mode=755" ]; + }; + fileSystems."/nix/store" = { + device = "/dev/vda"; + fsType = "erofs"; + options = [ "ro" ]; + }; + + services.getty.autologinUser = "root"; + networking.useDHCP = false; + nix.enable = false; + documentation.enable = false; + }; + }; + + 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" ]); + }; + drives = [{ + drive_id = "store"; + path_on_host = "@STORE_IMAGE@"; + is_root_device = false; + is_read_only = true; + }]; + machine-config = { + vcpu_count = 2; + mem_size_mib = 1024; + }; + }); +in +pkgs.writeShellScriptBin "run-firecracker-vm" '' + # usage: run-firecracker-vm [STORE-PATH...] + # Packs the closure of the guest system (plus any given store paths) into + # a temporary erofs image, which the guest mounts read-only at /nix/store. + set -efu + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnused pkgs.gnutar pkgs.erofs-utils pkgs.nix pkgs.firecracker ]} + + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + + nix-store -qR ${toplevel} "$@" > "$tmp"/store-paths + 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 "$tmp"/store.img + + sed "s|@STORE_IMAGE@|$tmp/store.img|" ${config} > "$tmp"/config.json + firecracker --no-api --config-file "$tmp"/config.json +'' -- cgit v1.3.1