aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2026-11-16 02:31:40 +0000
committertv <tv@krebsco.de>2026-11-16 02:31:40 +0000
commitf2b536e9d5adf5114025d69a68dfbadd1f8fff01 (patch)
treeb89d9619004332adeef7b2d3f05018d25b437c7f
parentc9fecb18349804f463c24b6dc1fa6bf5c51dd341 (diff)
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.
-rw-r--r--default.nix24
1 files changed, 17 insertions, 7 deletions
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
''