From f2b536e9d5adf5114025d69a68dfbadd1f8fff01 Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 16 Nov 2026 02:31:40 +0000 Subject: cache the store image Building the erofs image takes ~2.5s, as long as the guest's initrd. Keep the image of the last closure in $XDG_CACHE_HOME/run-firecracker-vm, named by the hash of the store path list, and rebuild it only when the closure changes. Older images get deleted; running VMs keep theirs open. --- default.nix | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'default.nix') diff --git a/default.nix b/default.nix index a05c0cb..207588b 100644 --- a/default.nix +++ b/default.nix @@ -100,19 +100,29 @@ 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. + # an erofs image, which the guest mounts read-only at /nix/store. + # The image of the last closure is kept in the cache directory. set -efu - export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.gnused pkgs.gnutar pkgs.erofs-utils pkgs.nix pkgs.firecracker ]} + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.findutils pkgs.gnused pkgs.gnutar 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 - 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 + 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 - sed "s|@STORE_IMAGE@|$tmp/store.img|" ${config} > "$tmp"/config.json + sed "s|@STORE_IMAGE@|$img|" ${config} > "$tmp"/config.json firecracker --no-api --config-file "$tmp"/config.json '' -- cgit v1.3.1