Skip to content

Instantly share code, notes, and snippets.

@aszlig
Last active April 7, 2018 19:44
Show Gist options
  • Save aszlig/52b2ff873543d11602c1730fb782de41 to your computer and use it in GitHub Desktop.
Save aszlig/52b2ff873543d11602c1730fb782de41 to your computer and use it in GitHub Desktop.
let
configuration = { config, pkgs, lib, ... }: let
sshKeyPair = pkgs.runCommand "ssh-keypair" {
buildInputs = [ pkgs.openssh ];
} ''
mkdir "$out"
ssh-keygen -t ed25519 -f "$out/key" -N "" -C "$keyComment"
'';
in {
boot.kernelPackages = pkgs.linuxPackages_latest;
environment.systemPackages = [
pkgs.htop pkgs.vim_configurable pkgs.btrfsProgs
];
time.timeZone = "Europe/Berlin";
networking.hostName = "newkernel";
networking.firewall.enable = false;
services.openssh.enable = true;
services.journald.rateLimitInterval = "0";
system.build.wrapped-vm = let
sleep = lib.escapeShellArg "${pkgs.coreutils}/bin/sleep";
nc = lib.escapeShellArg "${pkgs.netcat-openbsd}/bin/nc";
ssh = lib.escapeShellArg "${pkgs.openssh}/bin/ssh";
in pkgs.writeScript "run-vm" ''
#!${pkgs.stdenv.shell}
kill_everything() {
retry=0
while kill -0 $(jobs -p); do
if [ $retry -ge 15 ]; then
kill -9 $(jobs -p)
else
kill $(jobs -p)
fi
retry=$(($retry + 1))
${sleep} 0.1
done 2> /dev/null || :
}
waitport() {
while ! ${nc} -z 127.0.0.1 "$1"; do ${sleep} 0.1; done
}
trap kill_everything EXIT
set -e
${nc} -u -l 127.0.0.1 3332 &
ncpid=$!
${lib.escapeShellArg config.system.build.vm}/bin/run-*-vm \
-monitor tcp:127.0.0.1:3331,server,nowait \
-serial udp:127.0.0.1:3332 \
"$@" &
vmpid=$!
waitport 3022
set +e
chmod 0400 ${lib.escapeShellArg "${sshKeyPair}/key"}
${ssh} \
-i ${lib.escapeShellArg "${sshKeyPair}/key"} \
-o UserKnownHostsFile=/dev/null \
-o GlobalKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-o ConnectionAttempts=10 \
-p 3022 root@localhost
retval=$?
set -e
echo system_powerdown | ${nc} 127.0.0.1 3331 > /dev/null
wait $vmpid || :
exit $retval
'';
systemd.services."serial-getty@ttyS0".enable = false;
systemd.services."serial-getty@hvc0".enable = false;
environment.etc."ssh/authorized_keys.d/root" = lib.mkForce {
mode = "0444";
source = "${sshKeyPair}/key.pub";
};
virtualisation.diskSize = 16384;
virtualisation.memorySize = 1024;
virtualisation.graphics = false;
virtualisation.qemu.networkingOptions = let
devOpts = lib.concatStringsSep "," [
"hostfwd=tcp:127.0.0.1:3000-:80"
"hostfwd=tcp:127.0.0.1:3022-:22"
];
in [
"-net nic,vlan=0,model=virtio"
"-net user,vlan=0,${devOpts}\${QEMU_NET_OPTS:+,$QEMU_NET_OPTS}"
];
virtualisation.qemu.options = [
"-drive file=/dev/nvme0n1,index=1,media=disk"
"-drive file=/dev/nvme1n1,index=2,media=disk"
];
};
in (import <nixpkgs/nixos/lib/eval-config.nix> {
system = builtins.currentSystem;
modules = [
configuration <nixpkgs/nixos/modules/virtualisation/qemu-vm.nix>
];
}).config.system.build.wrapped-vm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment