Improve readability of custom-build-vm code

This commit is contained in:
Manuel Thalmann 2024-05-01 15:06:31 +02:00
parent 3a2ce0ed87
commit ea620730a6

View file

@ -118,68 +118,74 @@ in {
}; };
}; };
virtualisation = config.virtualisation; inherit (config.virtualisation)
vmVariant
vmVariantWithBootLoader
;
in { in {
vmVariant = extendVMConfig virtualisation.vmVariant; vmVariant = extendVMConfig vmVariant;
vmVariantWithBootLoader = extendVMConfig virtualisation.vmVariantWithBootLoader; vmVariantWithBootLoader = extendVMConfig vmVariantWithBootLoader;
}; };
system.build = system.build =
{ {
vm = lib.mkForce ( vm = lib.mkForce (
( let
vm: vm = vanillaVM;
if (vm.name == packageName) in
then if (vm.name == packageName)
vm then
else vm
let else
originalCommand = "${vm}/bin/run-${config.system.name}-vm"; let
originalCommand = "${vm}/bin/run-${config.system.name}-vm";
# Have the command run in background if requested # Have the command run in background if requested
suffix = suffix =
lib.concatStringsSep " " ( lib.concatStringsSep " " (
lib.optional config.virtualisation.qemu.runInBackground "&"); lib.optional config.virtualisation.qemu.runInBackground "&");
shellApp = pkgs.writeShellApplication { vmRunner = pkgs.writeShellApplication {
name = "run-${config.system.name}-vm"; name = "run-${config.system.name}-vm";
text = lib.strings.concatLines (
[ text = lib.strings.concatLines (
"${originalCommand} ${suffix}" [
] ++ ( "${originalCommand} ${suffix}"
let ] ++ (
# Run `remote-viewer` as normal user to limit access # Run `remote-viewer` as normal user to limit access
viewerPrefix = "sudo -Eu\"#$SUDO_UID\" "; (
spice = config.virtualisation.qemu.spice; lib.optionals
in config.virtualisation.virt-viewer (
( let
lib.optionals spice = config.virtualisation.qemu.spice;
config.virtualisation.virt-viewer remoteAddress = "spice://${lib.escapeShellArg spice.bindAddress}:${toString spice.port}";
viewerPrefix = "sudo -Eu\"#$SUDO_UID\" ";
in
[ [
"${viewerPrefix}${pkgs.virt-viewer}/bin/remote-viewer spice://${lib.escapeShellArg spice.bindAddress}:${toString spice.port}" "${viewerPrefix}${pkgs.virt-viewer}/bin/remote-viewer ${remoteAddress}"
# Kill QEMU after `remote-viewer` finished running # Kill QEMU after `remote-viewer` finished running
"kill %1" "kill %1"
]))); ]))));
}; };
# Run VM as root if requested # Run VM as root if requested
wrapped = wrapped =
if !config.virtualisation.runAsRoot if !config.virtualisation.runAsRoot
then then
shellApp vmRunner
else else
pkgs.writeShellApplication { pkgs.writeShellApplication {
name = shellApp.name; inherit (vmRunner) name;
text = ''
sudo -E ${shellApp}/bin/${shellApp.name} text = ''
''; sudo -E "${vmRunner}/bin/${vmRunner.name}"
}; '';
in };
pkgs.symlinkJoin { in
name = packageName; pkgs.symlinkJoin {
paths = [ wrapped ]; name = packageName;
}) paths = [ wrapped ];
vanillaVM); });
}; };
}; };
} }