Allow enabling USB redirection

This commit is contained in:
Manuel Thalmann 2024-05-08 11:13:07 +02:00
parent 88b8bdc16b
commit 157a1cf990
2 changed files with 27 additions and 3 deletions

View file

@ -15,6 +15,7 @@
vmConfig = {
virtualisation = {
sharedHostKeys = true;
usb-redirect = true;
virt-viewer = true;
cores = 4;
memorySize = 4 * 1024;

View file

@ -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"
]))));