1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
|
{ pkgs ? import <nixpkgs> {}
, kernelPackages ? pkgs.linuxPackages_latest
# The CA of the host's egress proxy (see host.nix), if it's there.
, caCert ? "/var/lib/fcbr0-egress/ca.pem"
}:
let
inherit (pkgs) lib;
nixos = import (pkgs.path + "/nixos") {
inherit (pkgs.stdenv.hostPlatform) system;
configuration = { config, 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" "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: the image (read-only) with a tmpfs on top, so nix can add
# to it. What it adds lives in RAM, and is gone after a reboot.
fileSystems."/nix/.ro-store" = {
device = "/dev/vda";
fsType = "erofs";
options = [ "ro" "nodev" "nosuid" ];
neededForBoot = true;
};
fileSystems."/nix/.rw-store" = {
fsType = "tmpfs";
options = [ "mode=0755" ];
neededForBoot = true;
};
fileSystems."/nix/store".overlay = {
lowerdir = [ "/nix/.ro-store" ];
upperdir = "/nix/.rw-store/store";
workdir = "/nix/.rw-store/work";
};
# nix, with the host's nixpkgs for nix-shell -p and the like. Root
# goes through the daemon too, so the paths of the image get
# registered (see the run script) before anything uses the store,
# and only once something does, not at boot.
nix.nixPath = [ "nixpkgs=${pkgs.path}" ];
environment.variables.NIX_REMOTE = "daemon";
systemd.services.nix-load-db = {
requiredBy = [ "nix-daemon.service" ];
before = [ "nix-daemon.service" ];
unitConfig.ConditionPathExists = "/nix/.ro-store/.registration";
serviceConfig.Type = "oneshot";
serviceConfig.RemainAfterExit = true;
script = "${config.nix.package.out}/bin/nix-store --load-db < /nix/.ro-store/.registration";
};
# /xchg: the host's ./xchg via 9P over vsock, see the run script,
# mounted on first access. The kernel's 9P client can't do vsock
# itself, but it can use the fds of a connected socket (trans=fd), so
# the mount goes through the helper mount.xchg: socat connects and
# passes the socket to mount as stdin and stdout (nofork). Separate
# -o options, as socat would take commas as its own option separators.
fileSystems."/xchg" = {
device = "xchg";
fsType = "xchg";
noCheck = true;
options = [ "x-systemd.automount" "nofail" ];
};
system.fsPackages = [
(pkgs.writeShellScriptBin "mount.xchg" ''
# usage: mount.xchg SPEC DIR [-o OPTIONS]
exec ${pkgs.socat}/bin/socat VSOCK-CONNECT:2:564 EXEC:"${pkgs.util-linux}/bin/mount -t 9p -o trans=fd -o rfdno=0 -o wfdno=1 -o version=9p2000.L xchg $2",nofork
'')
];
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 host.nix.
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;
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;
}];
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-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 served via 9P
# over vsock and mounted by the guest at /xchg. VMs started in the same
# directory share it.
set -efu
export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.findutils pkgs.gnugrep pkgs.gnused pkgs.gnutar pkgs.util-linux pkgs.erofs-utils pkgs.nix pkgs.firecracker pkgs.unpfs ]}
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/$({ echo v2; cat "$tmp"/store-paths; } | sha256sum | cut -c-32).img
# The image gets the paths' registration for the guest's nix database
# as .registration (nix ignores names starting with a dot).
if ! test -e "$img"; then
nix-store --dump-db $(cat "$tmp"/store-paths) > "$tmp"/.registration
{ cat "$tmp"/store-paths; echo "$tmp"/.registration; } |
tar -c -P --verbatim-files-from \
--transform 'flags=rSh;s|^/nix/store/||;s|^.*/\.registration$|.registration|' \
--files-from - \
| 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)))
# The 9P server for /xchg, one per VM. Its files end up owned by the
# user running this script. When the guest connects to vsock port 564 on
# the host (CID 2), Firecracker connects to the socket uds_path_564.
# 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.
vsock=$tmp/vsock:
mkdir -p xchg
RUST_LOG=off unpfs "unix!$tmp/vsock!_564" xchg > /dev/null &
unpfs=$!
trap 'kill $unpfs; rm -rf "$tmp"' EXIT
sed \
-e "s|@STORE_IMAGE@|$img|" \
-e "s|@TTY_ARGS@|$tty_args|" \
-e "s|@VSOCK@|$vsock|" \
-e "s|@TAP@|$tap|" \
-e "s|@MAC@|$mac|" \
${config} > "$tmp"/config.json
status=0
firecracker --no-api --config-file "$tmp"/config.json || status=$?
exit $status
''
|