When you have read the article about tunneling a vnc socket over ssh, you already know that I am a fan of using simple technologies like Unix sockets and ssh to access virtual machine information.

I am currently in a project to create a new virtual machine infrastructure based on Qemu/KVM. The problem we were facing is "How to shutdown a virtual machine, when the host is being shut down".


Qemu/KVM has a so called monitor to control the VM. Usually this monitor is reachable from the VNC socket (or whatever you use to view the console) by pressing Ctrl-Alt-2.

This is inappropriate for automatic shutdown (I'm not in the mood to script vnc sessions currently), so there must be a better solution.

The solution

Qemu/KVM is able to redirect the monitor to a "character device". There are ways to create a character device with Qemu/KVM and then attach the monitor to it, but you can have it more easy by connecting the monitor directly to a UNIX socket:

qemu-kvm ... -monitor unix:/opt/,server,nowait

This way we can connect (and control!) Qemu/KVM using [socat](]:

socat - UNIX-CONNECT:/opt/

And when we can connect to it, we can also shutdown a virtual machine:

echo system_powerdown | socat - UNIX-CONNECT:/opt/

Or we could reset it:

echo system_reset | socat - UNIX-CONNECT:/opt/

The full implementation

The full command line for running a VM as we do it in this project looks like this:

[root@kvm-hw-inx01]# cat start
/usr/libexec/qemu-kvm -m 65536 \
    -hda /opt/ \
    -vnc unix:/opt/ \
    -boot order=nc \
    -net nic,macaddr=00:16:3e:00:00:2d,vlan=200 \
        -net tap,script=/opt/,downscript=/opt/,vlan=200 \
    -net nic,macaddr=00:16:3e:00:00:2e,vlan=300 \
        -net tap,script=/opt/,downscript=/opt/,vlan=300 \
    -smp 16 \
    -name \
    -enable-kvm \
    -monitor unix:/opt/,server,nowait

As the VMs are currently not performing as well as they should, we will do some investigations into performance tuning of Qemu/KVM. So stay tuned, if you are interested in this topic.