aboutsummaryrefslogtreecommitdiffstats
path: root/default.nix
blob: d562380a31db0e809c9689781c3ed6649f810ca4 (plain)
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
{ pkgs ? import <nixpkgs> {}
, 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")
      ];

      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" ];
      };
      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";
        address = [ "172.16.0.2/24" ];
        gateway = [ "172.16.0.1" ];
      };

      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
      security.pam.services.login.lastlog.enable = lib.mkForce 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" "@TTY_ARGS@" ]);
    };
    network-interfaces = [{
      iface_id = "eth0";
      host_dev_name = "fctap0"; # see host.nix
      guest_mac = "06:00:ac:10:00:02";
    }];
    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" ''
  # 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.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) when starting the
  # getty.
  tty_args=
  if test -n "''${TERM-}"; then
    tty_args="systemd.tty.term.ttyS0=$TERM"
  fi
  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

  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|" \
      ${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
''