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 {
vmVariant = extendVMConfig virtualisation.vmVariant;
vmVariantWithBootLoader = extendVMConfig virtualisation.vmVariantWithBootLoader;
vmVariant = extendVMConfig vmVariant;
vmVariantWithBootLoader = extendVMConfig vmVariantWithBootLoader;
};
system.build =
{
vm = lib.mkForce (
(
vm:
if (vm.name == packageName)
then
vm
else
let
originalCommand = "${vm}/bin/run-${config.system.name}-vm";
let
vm = vanillaVM;
in
if (vm.name == packageName)
then
vm
else
let
originalCommand = "${vm}/bin/run-${config.system.name}-vm";
# Have the command run in background if requested
suffix =
lib.concatStringsSep " " (
lib.optional config.virtualisation.qemu.runInBackground "&");
# Have the command run in background if requested
suffix =
lib.concatStringsSep " " (
lib.optional config.virtualisation.qemu.runInBackground "&");
shellApp = pkgs.writeShellApplication {
name = "run-${config.system.name}-vm";
text = lib.strings.concatLines (
[
"${originalCommand} ${suffix}"
] ++ (
let
# Run `remote-viewer` as normal user to limit access
viewerPrefix = "sudo -Eu\"#$SUDO_UID\" ";
spice = config.virtualisation.qemu.spice;
in
(
lib.optionals
config.virtualisation.virt-viewer
vmRunner = pkgs.writeShellApplication {
name = "run-${config.system.name}-vm";
text = lib.strings.concatLines (
[
"${originalCommand} ${suffix}"
] ++ (
# Run `remote-viewer` as normal user to limit access
(
lib.optionals
config.virtualisation.virt-viewer (
let
spice = config.virtualisation.qemu.spice;
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 %1"
])));
};
]))));
};
# Run VM as root if requested
wrapped =
if !config.virtualisation.runAsRoot
then
shellApp
else
pkgs.writeShellApplication {
name = shellApp.name;
text = ''
sudo -E ${shellApp}/bin/${shellApp.name}
'';
};
in
pkgs.symlinkJoin {
name = packageName;
paths = [ wrapped ];
})
vanillaVM);
# Run VM as root if requested
wrapped =
if !config.virtualisation.runAsRoot
then
vmRunner
else
pkgs.writeShellApplication {
inherit (vmRunner) name;
text = ''
sudo -E "${vmRunner}/bin/${vmRunner.name}"
'';
};
in
pkgs.symlinkJoin {
name = packageName;
paths = [ wrapped ];
});
};
};
}