KVM/Qemu cheat sheet

I changed from VirtualBox to KVM/Qemu. Here are some tips, hints and commands to remember:

A graphical user interface to monitor and manage virtual machines:

virt-manager

List running and not running virtual machines:

virsh list --all

Mount offline qcow2 harddisks and partitions into the host system:

modprobe nbd max_part=8
qemu-nbd --connect=/dev/nbd0 image.qcow2
fdisk /dev/nbd0 -l
mount /dev/nbd0p1 /mnt/somepoint/
...
umount /mnt/somepoint/
qemu-nbd --disconnect /dev/nbd0

Create a disk-only snapshot, for rollback, backup, host move, etc:

virsh snapshot-create-as GUEST --name SNAPNAME --disk-only --quiesce --no-metadata

This will create a new disk image or new disk images if your GUEST has more than one disk. The name for these images will be diskname.SNAPNAME. So if your old diskimage was “guest.base” it will be guest.SNAPNAME”. The old will be used read only and is the actional snapshot, and old changes will go into “guest.SNAPNAME”.

Flatten old disk images into the newest. The old backing images will still be valid, but they are not used anymore because all the data is in the newest image:

virsh blockpull GUEST DISKNAME --wait --verbose

DISKNAME is not the name of the image but the name of the mounted disk device like “sda” or “sdb”. You can lookup those device names with:

virsh domblklist GUEST

Flatten newer disk images into the old image. All changes in the new images will be copied into the oldest image. In the end the oldest (base) image will be used as the current and running image. The newer images are invalid afterwards because it’s backing image has changed:

virsh blockcommit GUEST DISKNAME --verbose --wait --pivot

Like with blockpull DISKNAME is a device name not an image name.

If you just want to commit the newest (last) image into the second to last image, so reduce only the last image in the chain, you can use “–shallow”:

virsh blockcommit GUEST DISKNAME --verbose --wait --pivot --shallow

Remove unused images or image parts. You know “rm” of course, but you can check if the image isn’t really used with this command:

lsof *

This will list all files and the programms that use these files, in the current directory. Don’t remove files you find in this output.