diff options
Diffstat (limited to 'pkgs/run-rig')
| -rw-r--r-- | pkgs/run-rig/default.nix | 976 |
1 files changed, 976 insertions, 0 deletions
diff --git a/pkgs/run-rig/default.nix b/pkgs/run-rig/default.nix new file mode 100644 index 0000000..16af39d --- /dev/null +++ b/pkgs/run-rig/default.nix @@ -0,0 +1,976 @@ +{ pkgs ? import <nixpkgs> {} + # NixOS modules, part of the base system (layer 0, the first image), + # for what all layers share, like the kernel (base/kernel.nix): set in a + # layer instead, the base's kernel modules would stay in the base image, + # unused. +, base ? [ ] + # NixOS modules, each a layer on top of the ones before, the first on + # top of the base system (below). The guest runs the top layer's + # system; its store has an image per layer, each with only the store + # paths the layers below don't have, so the images below stay the same + # for any layers on top of them. +, layers ? [ ] +}: +let + inherit (pkgs) lib; + + # 9P over vsock, for the store and /xchg: mount -t vsock9p PORT DIR + # mounts what the host serves on vsock port PORT (see the run script). + # The kernel's 9P client can't do vsock itself, but it can use the + # fds of a connected socket (trans=fd), which socat passes to mount as + # stdin and stdout (nofork). Separate -o options, as socat would take + # commas as its own option separators. In the initrd, too, for the + # store. More options for PORT can come from the kernel command line, + # as rig.9pPORT=OPTIONS (see --nixpkgs-cache in the run script); they come + # last, so they win. + mountVsock9p = pkgs.writeShellScript "mount.vsock9p" '' + # usage: mount.vsock9p PORT DIR [-o OPTIONS] + set -efu + opts= + add() { + for o in ''${1//,/ }; do + case $o in x-*|nofail|auto|noauto|defaults) ;; *) opts="$opts -o $o" + esac + done + } + if test "''${3-}" = -o; then + add "$4" + fi + read -r cmdline < /proc/cmdline + for arg in $cmdline; do + case $arg in rig.9p$1=*) add "''${arg#*=}" + esac + done + exec ${pkgs.socat}/bin/socat VSOCK-CONNECT:2:"$1" EXEC:"${pkgs.util-linux}/bin/mount -t 9p -o trans=fd -o rfdno=0 -o wfdno=1 -o version=9p2000.L -o msize=1048576$opts vsock9p $2",nofork + ''; + + # The guest's side of fc-egress (see modules/host): asks the host + # whether the guest's egress allows URIs, over bash's /dev/tcp, as the + # guest may have no HTTP client. + fc-egress = pkgs.writeShellScriptBin "fc-egress" '' + # usage: fc-egress check URI... + # Whether this guest's egress allows each URI (https://HOST[/PATH], + # tcp://HOST:PORT, udp://HOST:PORT): true or false, and the URI, a line + # each. Exit status 0 if all of them are allowed, 1 if not, 2 on + # errors. The whitelist itself is the host's, see fc-egress there. + set -eu + usage() { + echo "usage: fc-egress check URI..." >&2 + exit 2 + } + test "''${1-}" = check || usage + shift + test $# -gt 0 || usage + uris=("$@") + body= + for uri; do + case $uri in *$'\n'* | *$'\r'*) + echo "fc-egress: bad URI" >&2 + exit 2 + esac + body+=$uri$'\n' + done + export LC_ALL=C # for the length in bytes + if ! exec 3<>/dev/tcp/172.16.0.1/80; then + echo "fc-egress: can't reach the host" >&2 + exit 2 + fi + printf 'POST /check HTTP/1.0\r\nHost: 172.16.0.1\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s' "''${#body}" "$body" >&3 + read -r _ status _ <&3 || status= + while IFS= read -r line <&3 && test -n "''${line%$'\r'}"; do :; done + if test "$status" != 200; then + echo "fc-egress: the host answered ''${status:-nothing}" >&2 + cat <&3 >&2 + exit 2 + fi + all=0 + i=0 + while read -r verdict <&3; do + test $i -lt $# || break + printf '%s %s\n' "$verdict" "''${uris[i]}" + test "$verdict" = true || all=1 + i=$((i + 1)) + done + if test $i != $#; then + echo "fc-egress: $i answers for $# URIs" >&2 + exit 2 + fi + exit $all + ''; + + # The system of the first n layers (the base system being layer 0), + # with n + 1 images. + evalSystem = n: import (pkgs.path + "/nixos") { + inherit (pkgs.stdenv.hostPlatform) system; + # The host's pkgs, for layers whose imports need packages, like a + # module from a source fetched with fetchFromGitHub: the guest's pkgs + # depend on the modules, so imports can't use them. + specialArgs.hostPkgs = pkgs; + configuration = { config, modulesPath, ... }: let + lowerdirs = lib.genList (k: "/nix/.image/${toString k}") (n + 1); + in { + imports = [ + (modulesPath + "/profiles/minimal.nix") + (modulesPath + "/profiles/perlless.nix") + { fileSystems = imageFileSystems (n + 1); } + { systemd.generators.rig-home = homeGenerator (label "rig-home"); } + # /xchg: a directory of the host's, via 9P on vsock port 564, only + # with rig.xchg on the kernel command line (run-rig + # --xchg DIR), mounted when first used. A generator, so a guest + # without it has no /xchg at all. + { systemd.generators.rig-xchg = pkgs.writeShellScript "rig-xchg-generator" '' + read -r cmdline < /proc/cmdline + case " $cmdline " in *" rig.xchg "*) ;; *) exit 0 + esac + printf '%s\n' '[Mount]' 'What=564' 'Where=/xchg' 'Type=vsock9p' > "$1"/xchg.mount + printf '%s\n' '[Automount]' 'Where=/xchg' > "$1"/xchg.automount + ${pkgs.coreutils}/bin/mkdir -p "$1"/local-fs.target.wants + ${pkgs.coreutils}/bin/ln -s ../xchg.automount "$1"/local-fs.target.wants/xchg.automount + ''; + } + # reboot and poweroff both end the VM, whichever the VMM (rig.vmm, + # from the run script): Firecracker ends on a reset (reboot=k), but + # stays on poweroff, with the guest halted; Cloud Hypervisor ends on + # poweroff, but restarts the guest on a reset. So the shutdown's + # last step (SuccessAction of systemd-poweroff, -halt, -reboot) + # becomes a reset in Firecracker, and a poweroff in Cloud + # Hypervisor, after the same clean shutdown. (Not a hook of + # systemd-shutdown: it runs those after unmounting, i.e. without + # /etc.) + { systemd.generators.rig-vmm-exit = pkgs.writeShellScript "rig-vmm-exit" '' + read -r cmdline < /proc/cmdline + exit_by() { # ACTION UNIT... + action=$1 + shift + for unit; do + ${pkgs.coreutils}/bin/mkdir -p "$dir/$unit.d" + printf '[Unit]\nSuccessAction=%s\n' "$action" > "$dir/$unit.d/rig-vmm-exit.conf" + done + } + dir=$1 + case " $cmdline " in + *" rig.vmm=firecracker "*) + exit_by reboot-force systemd-poweroff.service systemd-halt.service ;; + *" rig.vmm=cloud-hypervisor "*) + exit_by poweroff-force systemd-reboot.service systemd-halt.service ;; + esac + ''; + } + { + # For a layer whose state is in /home: the run script then + # refuses to start the guest without --home. + options.rig.home.required = lib.mkOption { + type = lib.types.bool; + default = false; + description = "Whether the guest needs a /home drive (--home)."; + }; + # For layers/nix.nix, which sets it: the run script gives the + # guest the drive for the rw-store, and so on. + options.rig.nix = lib.mkOption { + type = lib.types.bool; + default = false; + internal = true; + description = "Whether the guest has layers/nix.nix."; + }; + # The store's lower layers: the images (from the layers), and + # what layers add, like layers/nix.nix the host's store. + options.rig.storeLowerdirs = lib.mkOption { + type = lib.types.listOf lib.types.str; + internal = true; + description = "The store's lower layers, as in the guest's /."; + }; + options.rig.mountVsock9p = lib.mkOption { + type = lib.types.package; + default = mountVsock9p; + readOnly = true; + internal = true; + description = "mount.vsock9p, for layers/nix.nix's initrd."; + }; + # Secrets the guest needs, from the run script (--secret + # NAME=FILE, which it requires for each of these), never in the + # store: rig-secrets puts them into place, below /run, at boot. + options.rig.secrets = lib.mkOption { + type = lib.types.attrsOf (lib.types.submodule ({ name, ... }: { + options = { + path = lib.mkOption { + type = lib.types.str; + default = "/run/secrets/${name}"; + description = "Where the secret goes, below /run."; + }; + owner = lib.mkOption { type = lib.types.str; default = "root"; }; + group = lib.mkOption { type = lib.types.str; default = "root"; }; + mode = lib.mkOption { type = lib.types.str; default = "0400"; }; + }; + })); + default = { }; + description = "The secrets the guest needs, by name (--secret NAME=FILE)."; + }; + } + ] ++ base ++ lib.take n layers; + + # nix only with layers/nix.nix, which the run script needs to know + # about. + nix.enable = lib.mkDefault false; + assertions = [{ + assertion = config.nix.enable == config.rig.nix; + message = "nix.enable: use run-rig's layers/nix.nix instead."; + }] ++ lib.mapAttrsToList (name: s: { + assertion = builtins.match "[A-Za-z0-9._-]+" name != null + && builtins.match "/run/[^ ]+" s.path != null; + message = "rig.secrets.${name}: a name of letters, digits, '.', '_' and '-', with a path below /run"; + }) config.rig.secrets; + + # 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 = lib.mkDefault pkgs.linuxPackages_latest; + boot.initrd.allowMissingModules = true; # e.g. ahci, efivarfs with a cut-down kernel + # virtio over MMIO (Firecracker) or PCI (Cloud Hypervisor, qemu). + boot.initrd.kernelModules = [ "virtio_mmio" "virtio_pci" "virtio_blk" "erofs" "vmw_vsock_virtio_transport" "9p" "9pnet_fd" "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 guest's own closure from images (see + # imageFileSystems and images below), read-only, or with + # layers/nix.nix, writable. Without an upper layer, overlayfs needs + # at least two lower ones: a single image is the store itself + # (mounted a second time). Not with overlay.lowerdir: NixOS makes + # that a single option (lowerdir=A:B:...), which the mount API caps + # at 255 bytes, i.e. about 10 images; a lowerdir+= each has no such + # limit. An upper layer (layers/nix.nix) adds its own options. + rig.storeLowerdirs = lib.mkBefore lowerdirs; # images first: 9P is slow + fileSystems."/nix/store" = + if lib.length config.rig.storeLowerdirs > 1 then { + fsType = "overlay"; + device = "overlay"; + depends = config.rig.storeLowerdirs; + options = map (d: "lowerdir+=/sysroot${d}") config.rig.storeLowerdirs; + } else + (imageFileSystems 1)."/nix/.image/0"; + + system.fsPackages = [ + (pkgs.runCommand "mount.vsock9p" { } "install -D ${mountVsock9p} $out/bin/mount.vsock9p") + ]; + + # fc-egress check URI..., see fc-egress above. + environment.systemPackages = [ fc-egress ]; + + # sshd, started on demand (a layer may turn that off), with the host + # key a secret (--secret ssh_host_ed25519_key=FILE; see rig-secrets), + # in place before sshd (or its socket) starts, and never one + # generated instead. Who may log in: + # users.users.<name>.openssh.authorizedKeys, e.g. in a layer. + services.openssh = { + enable = true; + startWhenNeeded = lib.mkDefault true; + generateHostKeys = false; + hostKeys = [{ path = "/run/ssh/ssh_host_ed25519_key"; type = "ed25519"; }]; + }; + rig.secrets.ssh_host_ed25519_key = lib.mkIf config.services.openssh.enable { + path = "/run/ssh/ssh_host_ed25519_key"; + mode = "0600"; + }; + + # The secrets (rig.secrets), which the run script serves via 9P on + # vsock port 567 (--secret NAME=FILE; never in the store), copied + # into place, each with its owner and mode, before sysinit.target + # (so before any service with the default dependencies), but after + # the users get created, for the owners; any other secret the run + # script was given goes to /run/secrets/NAME, root's. The share + # gets unmounted again. + systemd.services.rig-secrets = { + wantedBy = [ "sysinit.target" ]; + before = [ "sysinit.target" "shutdown.target" ]; + after = [ "userborn.service" "systemd-sysusers.service" ]; + conflicts = [ "shutdown.target" ]; + unitConfig.DefaultDependencies = false; + serviceConfig.Type = "oneshot"; + serviceConfig.RemainAfterExit = true; + script = '' + share=$(mktemp -d -p /run) + ${mountVsock9p} 567 "$share" -o ro + trap '${pkgs.util-linux}/bin/umount "$share"; rmdir "$share"' EXIT + install -d -m 0755 /run/secrets + ${lib.concatStrings (lib.mapAttrsToList (name: s: '' + install -D -o ${lib.escapeShellArg s.owner} -g ${lib.escapeShellArg s.group} -m ${s.mode} "$share"/${name} ${lib.escapeShellArg s.path} + '') config.rig.secrets)} + for f in "$share"/*; do + test -f "$f" || continue + case ''${f##*/} in + ${lib.concatStringsSep " | " ([ "/" ] ++ lib.attrNames config.rig.secrets)}) ;; # / is no name + *) install -m 0400 "$f" /run/secrets/ + esac + done + ''; + }; + + # 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 modules/host + # (if it's there; another one: security.pki.certificateFiles). + environment.etc."resolv.conf".text = "nameserver 172.16.0.1\n"; + security.pki.certificateFiles = + lib.optional (builtins.pathExists /var/lib/fcbr0-egress/ca.pem) /var/lib/fcbr0-egress/ca.pem; + 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"; + # IPv6: the address from the MAC, which the host expects (see + # modules/host), and DNS stays the host's IPv4 address. + networkConfig.IPv6AcceptRA = true; + networkConfig.IPv6PrivacyExtensions = "no"; + ipv6AcceptRAConfig.Token = "eui64"; + ipv6AcceptRAConfig.UseDNS = false; + }; + + 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 = lib.mkDefault false; # see layers/switch.nix + system.disableInstallerTools = true; # nixos-rebuild & co., i.e. python + systemd.coredump.enable = false; + systemd.oomd.enable = false; + systemd.tpm2.enable = false; + users.manageLingering = false; + + # No screen, no X, and no hardware to tell apart, but virtio: + # neither kbd and systemd-vconsole-setup, nor fontconfig, nor su's + # xauth (shadow.nix sets it, not as a default), nor udev's hardware + # database. No console means no getty either, not even on ttyS0: + # the way in is ssh, or layers/console.nix. + console.enable = lib.mkDefault false; + fonts.fontconfig.enable = false; + security.pam.services.su.forwardXAuth = lib.mkForce false; + environment.etc."udev/hwdb.bin".enable = false; + # Nothing to unmount from a ramfs at shutdown: / is a tmpfs, and the + # store's images are read-only (systemd-shutdown remounts what's + # still busy, like the rw-store, read-only). + systemd.shutdownRamfs.enable = 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 + + # Nothing to do here, but they'd still get started at boot, each + # adding to the reads from the store. + systemd.units = lib.genAttrs [ + "dev-hugepages.mount" + "dev-mqueue.mount" + "modprobe@configfs.service" + "modprobe@drm.service" + "modprobe@efi_pstore.service" + "sys-fs-fuse-connections.mount" + "sys-kernel-config.mount" + "sys-kernel-debug.mount" + "sys-kernel-tracing.mount" + "systemd-pstore.service" + ] (_: { enable = lib.mkForce false; }); + + # 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" ]; + }; + }; + }; + + # /home: part of / (the tmpfs), or with rig.home on the kernel command + # line (--home, see the run script), the drive labelled rig-home (device). + # A generator rather than fileSystems, so a guest without it doesn't wait + # for the drive. + homeGenerator = device: pkgs.writeShellScript "rig-home-generator" '' + read -r cmdline < /proc/cmdline + case " $cmdline " in *" rig.home "*) ;; *) exit 0 + esac + printf '%s\n' \ + '[Unit]' 'Before=local-fs.target' \ + '[Mount]' 'What=${device}' 'Where=/home' 'Type=ext4' 'Options=noatime' \ + > "$1"/home.mount + ${pkgs.coreutils}/bin/mkdir -p "$1"/local-fs.target.requires + ${pkgs.coreutils}/bin/ln -s ../home.mount "$1"/local-fs.target.requires/home.mount + ''; + + # The guest's drives go by their filesystems' labels, not by vda, vdb, + # ...: those come in the order the kernel probes the drives, which + # needn't be theirs in the Firecracker configuration (with virtio_blk + # and virtio_mmio as modules, as in linuxPackages_latest, two images + # came swapped). The run script labels the rw-store and home. + label = l: "/dev/disk/by-label/${l}"; + + # The images, read-only drives, image k (of layer k) labelled + # rig-layer-K. + imageFileSystems = count: lib.listToAttrs (lib.genList (k: + lib.nameValuePair "/nix/.image/${toString k}" { + device = label "rig-layer-${toString k}"; + fsType = "erofs"; + options = [ "ro" "nodev" "nosuid" ]; + neededForBoot = true; + }) count); + + systems = lib.genList evalSystem (lib.length layers + 1); + nixos = lib.last systems; + toplevels = map (s: s.config.system.build.toplevel) systems; + inherit (nixos.config.system.build) toplevel kernel initialRamdisk; + nix = nixos.config.rig.nix; # layers/nix.nix + + # A layer's name, for its image's: its file's, if it's a file (for + # .../NAME/default.nix, NAME). + layerName = m: + if builtins.isPath m || builtins.isString m && lib.hasPrefix "/" m then + let file = baseNameOf (toString m); in + if file == "default.nix" then baseNameOf (dirOf (toString m)) + else lib.removeSuffix ".nix" file + else null; + layerNames = [ null ] ++ map layerName layers; # the base system: none + + # Layer k's image: the store paths of its system's closure that aren't + # in the closures of the layers below, as erofs image. Without any of + # the systems' initrds, which Firecracker gets from the host, and which + # the guest never reads (for nix, the host's store still has them). + initrds = map (s: "${s.config.system.build.initialRamdisk}") systems; + images = lib.imap0 (k: top: let name = lib.elemAt layerNames k; in pkgs.runCommand + "rig-layer-${toString k}${lib.optionalString (name != null) "-${lib.strings.sanitizeDerivationName name}"}.img" { + nativeBuildInputs = [ pkgs.erofs-utils pkgs.gnutar ]; + closure = pkgs.closureInfo { rootPaths = [ top ]; }; + below = map (t: pkgs.closureInfo { rootPaths = [ t ]; }) (lib.take k toplevels); + inherit initrds; + } '' + for b in $below; do cat $b/store-paths; done > below + printf '%s\n' $initrds >> below + sort -u -o below below + sort $closure/store-paths | comm -23 - below | + tar -c -P --verbatim-files-from \ + --transform 'flags=rSh;s|^/nix/store/||' \ + --files-from - | + mkfs.erofs --quiet -L rig-layer-${toString k} --tar=f --force-uid=0 --force-gid=0 --hard-dereference -T 0 $out + '') toplevels; + + 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" + ] ++ lib.optional nix + "rig.registration=${pkgs.closureInfo { rootPaths = [ toplevel ]; }}/registration" + ++ [ + "@ARGS@" + ]); + }; + network-interfaces = [{ + iface_id = "eth0"; + host_dev_name = "@TAP@"; # see modules/host + guest_mac = "@MAC@"; + }]; + # The guest finds them by label (see label). The run script drops home + # without --home. + drives = lib.optional nix { + drive_id = "rw-store"; + path_on_host = "@RW_STORE@"; + is_root_device = false; + is_read_only = false; + } ++ lib.imap0 (k: image: { + drive_id = "layer-${toString k}"; + path_on_host = "${image}"; + is_root_device = false; + is_read_only = true; + }) images ++ [{ + drive_id = "home"; + path_on_host = "@HOME@"; + is_root_device = false; + is_read_only = false; + }]; + vsock = { + guest_cid = 3; + uds_path = "@VSOCK@"; + }; + machine-config = { + vcpu_count = 2; # --vcpus + mem_size_mib = 1024; # --mem-size + }; + # No hardware virtualization for the guest (SVM, VMX), unless + # --nested (which drops this): Firecracker passes on what KVM offers. + # The bitmaps go from bit 31 to 0, x keeps a bit. + cpu-config.cpuid_modifiers = [ + { leaf = "0x80000001"; subleaf = "0x0"; flags = 0; # AMD: ECX[2] SVM + modifiers = [ { register = "ecx"; bitmap = "0bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx0xx"; } ]; } + { leaf = "0x1"; subleaf = "0x0"; flags = 0; # Intel: ECX[5] VMX + modifiers = [ { register = "ecx"; bitmap = "0bxxxxxxxxxxxxxxxxxxxxxxxxxx0xxxxx"; } ]; } + ]; + }); +in +pkgs.writeShellScriptBin "run-rig" /* sh */ '' + # usage: run-rig [--store FILE] [--store-size SIZE] + # [--home FILE] [--home-size SIZE] + # [--mem-size MIB] + # [--nixpkgs DIR] [--nixpkgs-cache MODE] + # [--egress LIST] [--name NAME] [--vcpus N] + # [--secret NAME=FILE]... + # [--vmm firecracker|cloud-hypervisor] [--nested] + # [--xchg DIR] + # With --xchg DIR (created if missing), the guest gets DIR at /xchg, via + # 9P over vsock; without, there's no /xchg. The guest's store is + # read-only, unless it has nix (layers/nix.nix). + # A guest with nix gets the host's store, read-only, the same way, and + # also nixpkgs at /nixpkgs, read-only: DIR, by default the nixpkgs the + # guest was built from. It isn't cached in the guest, so changes show + # up right away, but evaluating is slow. --nixpkgs-cache sets 9P's + # cache mode for it: loose caches everything (fast, but changes may not + # show up while the guest runs), mmap and readahead some (see the + # kernel's Documentation/filesystems/9p.rst), none is the default. + # What nix in the guest adds to the store goes to FILE (--store, which a + # guest with nix requires, and one without refuses, like --store-size, + # --nixpkgs and --nixpkgs-cache), which keeps it across boots (created + # if it doesn't exist, of --store-size, default 16G; the file is sparse, + # so that's only an upper limit). /home is part of the guest's root + # file system, gone when it exits, or with --home, on FILE, likewise (of + # --home-size, default 16G). A guest with rig.home.required (set by a + # layer) doesn't start without --home. + # --mem-size sets the guest's memory, in MiB (default 1024). + # The guest's egress goes by the user's whitelist LIST (default: the + # VM's name, or without one, default), see modules/host and fc-egress. + # --name names the VM, for fc-egress and as the guest's host name; only + # one running VM of the user's can have a given name. --vcpus: the + # guest's number of CPUs (default 2; Firecracker takes 1 to 32). + # --secret NAME=FILE: a secret for the guest, NAME letters, digits, '.', + # '_' and '-', FILE read once (it may be a pipe, like <(...)), and handed + # to the guest only, never in the store (see rig-secrets); a guest + # doesn't start without the secrets it declares (rig.secrets). + # --vmm: the hypervisor, Firecracker (default) or Cloud Hypervisor, which + # takes no commas in --store and --home. Either ends when the guest + # reboots or powers off (see rig-vmm-exit). + # --nested: hardware virtualization (SVM, VMX) for the guest, so it can + # run VMs itself (base/kernel.nix has KVM); off by default, as it's more + # of the host's KVM for the guest to reach. + set -efu + export PATH=${lib.makeBinPath [ pkgs.coreutils pkgs.e2fsprogs pkgs.findutils pkgs.gnugrep pkgs.gnused pkgs.jq pkgs.openssh pkgs.util-linux pkgs.firecracker pkgs.cloud-hypervisor pkgs.git pkgs.socat pkgs.unpfs ]} + + usage() { + echo "usage: $0 [--store FILE] [--store-size SIZE] [--home FILE] [--home-size SIZE] [--mem-size MIB] [--nixpkgs DIR] [--nixpkgs-cache MODE] [--egress LIST] [--name NAME] [--vcpus N] [--secret NAME=FILE]... [--vmm firecracker|cloud-hypervisor] [--nested] [--xchg DIR]" + } + args= + rw_store= + rw_store_size=16G + home= + home_size=16G + mem_size=1024 + egress= + name= + vcpus=2 + xchg= + vmm=firecracker + nested= + nixpkgs=${lib.escapeShellArg (toString pkgs.path)} + nixpkgs_cache= + nix_opt= # the last option that's only for a guest with nix + secrets=() # NAME=FILE, as given + locks=() # the lock fds, see close_locks + while test $# -gt 0; do + case $1 in + --*=*) set -- "''${1%%=*}" "''${1#*=}" "''${@:2}"; continue ;; + --store) rw_store=$2; nix_opt=$1; shift 2 ;; + --store-size) rw_store_size=$2; nix_opt=$1; shift 2 ;; + --home) home=$2; shift 2 ;; + --home-size) home_size=$2; shift 2 ;; + --mem-size) mem_size=$2; shift 2 ;; + --nixpkgs) nixpkgs=$2; nix_opt=$1; shift 2 ;; + --nixpkgs-cache) args="$args rig.9p566=cache=$2"; nixpkgs_cache=$2; nix_opt=$1; shift 2 ;; + --egress) egress=$2; shift 2 ;; + --name) name=$2; shift 2 ;; + --vcpus) vcpus=$2; shift 2 ;; + --xchg) xchg=$2; shift 2 ;; + --secret) secrets+=("$2"); shift 2 ;; + --vmm) vmm=$2; shift 2 ;; + --nested) nested=on; shift ;; + -h|--help) usage; exit ;; + *) usage >&2; exit 1 + esac + done + egress=''${egress:-''${name:-default}} + ${lib.optionalString nixos.config.rig.home.required '' + if test -z "$home"; then + echo "$0: the guest keeps its state in /home: --home FILE is required" >&2 + exit 1 + fi + ''} + ${if nix then '' + if test -z "$rw_store"; then + echo "$0: the guest has nix, whose store is on a drive: --store FILE is required" >&2 + exit 1 + fi + '' else '' + if test -n "$nix_opt"; then + echo "$0: $nix_opt: the guest has no nix (see layers/nix.nix)" >&2 + exit 1 + fi + ''} + if ! printf %s "$mem_size" | grep -qxE '[1-9][0-9]*'; then + echo "$0: bad memory size: $mem_size (MiB, a number)" >&2 + exit 1 + fi + if ! printf %s "$vcpus" | grep -qxE '[1-9][0-9]?' || test "$vcpus" -gt 32; then + echo "$0: bad number of CPUs: $vcpus (1 to 32)" >&2 + exit 1 + fi + case $vmm in + firecracker) ;; + cloud-hypervisor) + # Its options are KEY=VALUE,... lists. + case $rw_store$home in *,*) + echo "$0: --vmm cloud-hypervisor: no commas in --store and --home" >&2 + exit 1 + esac ;; + *) + echo "$0: bad --vmm: $vmm (firecracker or cloud-hypervisor)" >&2 + exit 1 + esac + args="$args rig.vmm=$vmm" # see rig-vmm-exit + if test -n "$xchg"; then + args="$args rig.xchg" # see rig-xchg + fi + + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + + # The secrets, copies, in a directory only the user can read, for the + # guest to copy (see rig-secrets), each FILE read once. The guest's own + # (rig.secrets) are required. + mkdir -m 700 "$tmp"/secrets + for secret in ''${secrets[@]+"''${secrets[@]}"}; do + s=''${secret%%=*} + file=''${secret#*=} + if test "$s" = "$secret" || ! printf %s "$s" | grep -qxE '[A-Za-z0-9._-]+'; then + echo "$0: --secret $secret: not NAME=FILE (NAME: letters, digits, '.', '_' and '-')" >&2 + exit 1 + fi + if test -e "$tmp/secrets/$s"; then + echo "$0: --secret $s: given twice" >&2 + exit 1 + fi + if ! cp "$file" "$tmp/secrets/$s"; then + echo "$0: --secret $s: can't read $file" >&2 + exit 1 + fi + chmod 600 "$tmp/secrets/$s" + done + # sshd takes no host key without its final newline, which, e.g., $(...) + # loses, and none with a passphrase. + key=$tmp/secrets/ssh_host_ed25519_key + if test -e "$key"; then + if test -n "$(tail -c 1 "$key")"; then + echo >> "$key" + fi + if ! ssh-keygen -y -f "$key" > /dev/null; then + echo "$0: --secret ssh_host_ed25519_key: not an SSH private key without passphrase" >&2 + exit 1 + fi + fi + for s in ${lib.escapeShellArgs (lib.attrNames nixos.config.rig.secrets)}; do + if ! test -e "$tmp/secrets/$s"; then + echo "$0: the guest needs the secret $s: --secret $s=FILE is required" >&2 + exit 1 + fi + done + for s in $(ls "$tmp"/secrets); do + case $s in + ${lib.concatStringsSep " | " ([ "/" ] ++ lib.attrNames nixos.config.rig.secrets)}) ;; # / is no name + *) echo "$0: --secret $s: the guest doesn't ask for it (rig.secrets), it goes to /run/secrets/$s" >&2 + esac + done + + # disk VAR FILE SIZE LABEL: sets VAR to the absolute path of FILE, an ext4 + # image, created (sparse, of SIZE) if it doesn't exist; locked while the + # guest runs, as two guests with the same file would wreck it. The guest + # finds it by LABEL, which gets set on images from before labels, too. + disk() { + local f=$2 lock + if ! test -e "$f"; then + truncate -s "$3" "$f" + mkfs.ext4 -q -F -L "$4" "$f" + fi + f=$(realpath "$f") + exec {lock}<"$f" + if ! flock -n "$lock"; then + echo "$0: $f is in use by another VM" >&2 + exit 1 + fi + locks+=("$lock") + if test "$(e2label "$f")" != "$4"; then + e2label "$f" "$4" + fi + printf -v "$1" %s "$f" + } + if test -n "$rw_store"; then + disk rw_store "$rw_store" "$rw_store_size" rig-store + fi + if test -n "$home"; then + disk home "$home" "$home_size" rig-home + args="$args rig.home" + 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} + args="$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" + args="$args systemd.tty.rows.ttyS0=$rows systemd.tty.columns.ttyS0=$cols" + fi + + # Take the first tap device of the user's that no other VM holds, from + # the ones modules/host lists in /etc/fc-taps (TAP USER IP MAC, with the + # tap's own address). The lock is held until the script exits. The + # guest's address, and the MAC address that DHCP hands it out by, is + # its VM's, if it has a name in /etc/fc-vms (VM USER IP MAC), else the + # tap's own; modules/host gives the tap that address once the VM's name + # is in /run/fc-egress/TAP.name (see below). + # Lock files in a directory of the user's own: in /tmp, another user + # could take them first. + lockdir=''${XDG_RUNTIME_DIR:-/run/user/$(id -u)} + if ! test -d "$lockdir" -a -O "$lockdir"; then + echo "$0: $lockdir isn't a directory of $(id -un)'s; set XDG_RUNTIME_DIR" >&2 + exit 1 + fi + if ! test -r /etc/fc-taps; then + echo "$0: no /etc/fc-taps, see modules/host" >&2 + exit 1 + fi + me=$(id -un) + tap= + while read -r t u a m; do + test "$u" = "$me" || continue + test "$(cat /sys/class/net/$t/owner 2>/dev/null)" = "$(id -u)" || continue + exec {lock}>"$lockdir/run-rig.$t.lock" + if flock -n "$lock"; then + locks+=("$lock") + tap=$t + addr=$a + mac=$m + break + fi + exec {lock}>&- + done < /etc/fc-taps + if test -z "$tap"; then + echo "$0: no free tap device fctap* of $me's, see modules/host" >&2 + exit 1 + fi + if test -n "$name" && test -r /etc/fc-vms; then + while read -r v u a m; do + if test "$v $u" = "$name $me"; then + addr=$a + mac=$m + fi + done < /etc/fc-vms + fi + # The VM's name: held by a lock, like the tap, so it's unique among the + # user's running VMs. Not like a tap's, so fc-egress can tell them + # apart. + if test -n "$name"; then + if ! printf %s "$name" | grep -qxE '[A-Za-z0-9][A-Za-z0-9-]{0,62}' || + printf %s "$name" | grep -qxE 'fctap[0-9]+'; then + echo "$0: bad name: $name (letters, digits and -, not like a tap)" >&2 + exit 1 + fi + exec {name_lock}>"$lockdir/run-rig.name.$name.lock" + if ! flock -n "$name_lock"; then + echo "$0: a VM named $name is running already" >&2 + exit 1 + fi + locks+=("$name_lock") + args="$args systemd.hostname=$name" + fi + # The guest's whitelist: modules/host goes by the name in the tap's file + # in /run/fc-egress (emptied again when the guest exits, below). + vm=/run/fc-egress/$tap + if test -w "$vm"; then + if ! printf %s "$egress" | grep -qxE '[A-Za-z0-9_-]+'; then + echo "$0: bad list name: $egress" >&2 + exit 1 + fi + if ! test -f "/var/lib/fc-egress/$(id -un)/$egress"; then + echo "$0: no list $egress (see fc-egress), no egress" >&2 + fi + printf '%s\n' "$egress" > "$vm" + printf '%s\n' "$name" > "$vm.name" + # The tap's address, by the VM's name (see above): wait for it, up to + # 10s, writing the name again every second, in case modules/host + # missed it (fcbr0-firewall@TAP was busy). + n=0 + while test "$(head -n 1 /run/fcbr0-addr/$tap 2>/dev/null)" != "$addr"; do + n=$((n + 1)) + if test $n -gt 100; then + echo "$0: $tap didn't get $addr, see fcbr0-firewall@$tap on the host" >&2 + exit 1 + fi + if test $((n % 10)) = 0; then + printf '%s\n' "$name" > "$vm.name" + fi + sleep 0.1 + done + else + vm= + fi + + # The 9P servers, for the secrets, /xchg (--xchg), and with nix, the store + # and nixpkgs, one each per VM. They run as the user running this + # script: xchg's files end up owned by the user, and the store is + # read-only to them. When the guest connects to vsock port PORT on the + # host (CID 2), the VMM connects to the socket uds_path_PORT. 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. They have to be served before the guest wants them, the + # store before its initrd does. + vsock=$tmp/vsock: + servers= + ports= + # The helpers (the 9P servers, the watcher below) run without the lock + # fds, which bash passes on to every child: one left over, after this + # script got killed, would keep the VM's files, tap and name locked. + # Only the VMM keeps them, as long as it runs. + close_locks() { + local fd + for fd in ''${locks[@]+"''${locks[@]}"}; do + eval "exec $fd<&-" + done + } + serve() { + (close_locks; RUST_LOG=off exec unpfs "unix!$tmp/vsock!_$1" "$2" > /dev/null) & + servers="$servers $!" + ports="$ports $1" + } + if test -n "$xchg"; then + mkdir -p "$xchg" + serve 564 "$xchg" + fi + serve 567 "$tmp"/secrets + ${lib.optionalString nix '' + serve 565 /nix/store + serve 566 "$nixpkgs" + # With a cache mode for nixpkgs, the guest doesn't see changes to it + # (see rig-drop-caches in layers/nix.nix). When it's a Git checkout + # whose commit changes (checkout, pull, rebase), the guest gets told + # to drop its caches: a connection to its vsock port 1235 (on the + # socket uds_path, with CONNECT PORT). Changes without a commit + # need rig-drop-caches by hand. + if test -n "$nixpkgs_cache" && git -C "$nixpkgs" rev-parse HEAD > /dev/null 2>&1; then + ( + close_locks + head=$(git -C "$nixpkgs" rev-parse HEAD) + while sleep 5; do + new=$(git -C "$nixpkgs" rev-parse HEAD 2>/dev/null) || continue + if test "$new" != "$head"; then + printf 'CONNECT 1235\n' | socat -t 10 - UNIX-CONNECT:"$tmp/vsock\:" > /dev/null 2>&1 || : + head=$new + fi + done + ) & + servers="$servers $!" + fi + ''} + trap 'kill $servers; rm -rf "$tmp"; if test -n "$vm"; then : > "$vm"; if test -w "$vm.name"; then : > "$vm.name"; fi; fi' EXIT + for port in $ports; do + while ! test -S "$vsock"_$port; do sleep 0.01; done + done + + sed \ + -e "s|@ARGS@|$args|" \ + -e "s|@VSOCK@|$vsock|" \ + -e "s|@TAP@|$tap|" \ + -e "s|@MAC@|$mac|" \ + -e "s|@RW_STORE@|$rw_store|" \ + -e "s|@HOME@|$home|" \ + ${config} | + jq --argjson vcpus "$vcpus" --argjson mem_size "$mem_size" --arg home "$home" --arg nested "$nested" ' + ."machine-config".vcpu_count = $vcpus | + ."machine-config".mem_size_mib = $mem_size | + if $home == "" then del(.drives[] | select(.drive_id == "home")) end | + if $nested != "" then del(."cpu-config") end + ' > "$tmp"/config.json + status=0 + case $vmm in + firecracker) + firecracker --no-api --config-file "$tmp"/config.json || status=$? ;; + cloud-hypervisor) + # The same configuration, as Cloud Hypervisor's options. Its vsock + # works like Firecracker's: the guest's connections to port PORT go + # to the socket SOCKET_PORT. + get() { jq -r "$1" "$tmp"/config.json; } + # image_type=raw: without it, Cloud Hypervisor guesses the type, and + # then refuses writes to sector 0, i.e. ext4's superblock (the + # rw-store, home). The images, read-only, can't be sparse. + mapfile -t disks < <(get '.drives[] | "path=\(.path_on_host),image_type=raw" + if .is_read_only then ",readonly=on,sparse=off" else "" end') + cloud-hypervisor \ + --kernel "$(get '."boot-source".kernel_image_path')" \ + --initramfs "$(get '."boot-source".initrd_path')" \ + --cmdline "$(get '."boot-source".boot_args')" \ + --cpus boot="$vcpus",nested="''${nested:-off}" --memory size="$mem_size"M \ + --disk "''${disks[@]}" \ + --net tap="$tap",mac="$mac" \ + --vsock cid=3,socket="$vsock" \ + --serial tty --console off || status=$? ;; + esac + + exit $status +'' // { + # The guest's system, for switching a running guest (see layers/switch.nix). + inherit toplevel; +} |
