diff --git a/lib/configuration.nix b/lib/configuration.nix index 749995a..1138829 100644 --- a/lib/configuration.nix +++ b/lib/configuration.nix @@ -15,6 +15,7 @@ vmConfig = { virtualisation = { sharedHostKeys = true; + usb-redirect = true; virt-viewer = true; cores = 4; memorySize = 4 * 1024; diff --git a/lib/modules/custom-build-vm.nix b/lib/modules/custom-build-vm.nix index 00936a2..422ce6c 100644 --- a/lib/modules/custom-build-vm.nix +++ b/lib/modules/custom-build-vm.nix @@ -36,6 +36,12 @@ in { default = false; }; + usb-redirect = lib.mkOption { + type = lib.types.bool; + description = lib.mdDoc "Whether to enable USB redirection to the VM."; + default = false; + }; + virt-viewer = lib.mkOption { type = lib.types.bool; description = "Whether to use `remote-viewer` for displaying the VM."; @@ -84,7 +90,9 @@ in { virtualisation = { # Enable root permissions to get access to the `/etc/ssh` directory - runAsRoot = lib.mkIf vmVariant.virtualisation.sharedHostKeys true; + runAsRoot = lib.mkIf + (vmVariant.virtualisation.sharedHostKeys || vmVariant.virtualisation.usb-redirect) + true; # Enable spice and run QEMU in background to let `remote-viewer` take over qemu = { @@ -94,7 +102,22 @@ in { options = with { inherit (vmVariant.virtualisation.qemu) spice; + inherit (vmVariant.virtualisation) usb-redirect; }; + ( + lib.optionals usb-redirect ( + [ + "-usb" + "-device qemu-xhci" + ] ++ (builtins.concatMap + (index: + let + devName = "usbredirchardev${toString index}"; + in [ + "-chardev spicevmc,name=usbredir,id=${devName}" + "-device usb-redir,chardev=${devName},id=usbredirdev${toString index}" + ]) + (lib.lists.range 1 3)))) ++ ( lib.optional (spice.enable) ("-spice " + ( @@ -147,6 +170,7 @@ in { vmRunner = pkgs.writeShellApplication { name = "run-${config.system.name}-vm"; + runtimeInputs = lib.optional config.virtualisation.usb-redirect pkgs.spice-gtk; text = lib.strings.concatLines ( [ @@ -159,10 +183,9 @@ in { 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 ${remoteAddress}" + "${pkgs.virt-viewer}/bin/remote-viewer ${remoteAddress}" # Kill QEMU after `remote-viewer` finished running "kill %1" ]))));