Automatically disabling output using XrandR when a VM starts via libvirt @ kp | Tuesday, Mar 27, 2018 | 3 minutes read | Update at Tuesday, Mar 27, 2018

when a monitor supports input scanning, disabling the output will force the monitor to switch to the passed-through GPU

this is mostly for libvirt.

Obviously everyone else starting with a script can just add the relevant xrandr commands and be done with it.

I use libvirt to manage my VMs. I also have 3 monitors, and 2 GPUs. One of the GPUs is dedicated directly to a Windows 10 VM. When I start the VM, I switch my ASUS 32" curved display to the DVI input, acting sort of as a basic KVM.

I really like this, but the monitor is mounted on my wall above two others in a triangle formation and reaching up to manually switch inputs can be a real pain as it’s almost just out of reach.

To enhance my laziness further, I decided to have libvirt automatically disable the DVI output when a particular Windows VM starts, causing the monitor’s auto scan to pick up on the signal and automatically display the image.

because libvirt 0.8+ support hooks for qemu

libvirt 0.8 is required.

On most distributions, you can simply create the /etc/libvirt/hooks directory, and touch /etc/libvirt/hooks/qemu ; chmod +x /etc/libvirt/hooks/qemu as root to get the party started.

sample XML contents

We can edit the file using nano -w /etc/libvirt/hooks/qemu and use the following contents:

#!/bin/bash
export USERNAME="yourusernamehere"
export XAUTHORITY=/home/${USERNAME}/.Xauthority
export DISPLAY=:0.0
export LOG_FILE=/tmp/scripty.log

echo "script running as user $(whoami)" > $LOG_FILE
if [[ "$1" == "win10-8core" ]] || [[ "$1" == "win10" ]]; then
        echo "$(date) RUNNING THE ${2} SCRIPTY THINGY FOR ${1}" >> $LOG_FILE
else
        echo "$(date) NOT RUNNING THE ${2} SCRIPTY THINGY FOR ${1}" >> $LOG_FILE
        exit 0
fi

if [[ $2 == "stopped" ]] ; then
        echo "RUNNING THE XRANDR ON!" >> $LOG_FILE
        xrandr --output DP-1 --mode 1920x1080 --pos 988x-1080 2>&1 >> $LOG_FILE || exit 1
fi

if [[ $2 == "start" ]] ; then
        xrandr --output DP-1 --off || exit 1
fi

I use two Windows 10 VM configurations in libvirt, one with 8 core / 2 NUMA zones and another with 4 cores on a single NUMA zone.

This script allows me to shut the display off for only these two VMs. I have other Ubuntu, CentOS, Gentoo VMs, that do not have PCI passthrough and have no need for this function.

Using xrandr by itself will help you determine the name to use for --output <output name>.

The --pos is what I must apply to have my third monitor positioned centred above the other two.

a word on the Xauthority path

Your Xauthority file might not be in ~ - and for these people, you shall have to look through the entire system, unfortunately. Maybe a locate Xauthority will help.

© 2022 tripleback

Powered by Hugo with theme Dream.