These days virtual machines are all the rage. They make sense in a lot of areas, and can reduce both the floorspace, power requirements, costs, testing, stability, etc. This article is not about the reasons to have a virtual machine, but rather, how to control them from a command line.
Most Linux distributions use libvirt to control the virtual machines. From a GUI desktop a very convenient way to control the VMs is the Virtual Machine manager, also known as the virt-manager program. This program provides a fairly clean interface to the libvirt library, allowing you to create, delete, start, stop and configure the VMs. I will go into this program in more detail in another article.
Sometimes you need to control the VMs from a command line. For example, if you need to have an automated process to restart a hung or crashed VM. There are a number of ways of doing this, for a complete list look at this page at http://www.linux-kvm.org/page/Management_Tools.
I had a need to restart one of a number of VMs, and have written the attached script to allow me to do so. The script can be run interactively or as an automated process.
restartVM.tar.gz (1.6 KiB, 600 hits)
To use it, install it in your path. The usage instructions are fairly simple, you can print them out by using the command: restartVM.sh -h
I’ve reproduced it below:
usage: restartVM.sh options [vm name] Options: -q Quiet. Errors will still be shown. Repeat to hide all output -d Just destroy the specified instance if it is currently running -s Just stop the specified instance, if it is currently running -w [#] Maximum amount of time to wait to let currently running instance to shutdown, range from 0-300 -h Show this message vmname Optionally, specify the VM name on the command line
To use this in a non-interactive mode, you will need to specify the name of the virtual machine as it exists in /etc/libvirt/qemu AND the image directory. They need to be the same! You don’t need to specify the suffix, if you do the script will fail.
The -d option is very dangerous. Destroying an instance stops it immediately, it is equivilant to pulling out the plug on a running server.
The -w specifies how long to wait before assuming that a server is either hung or unable to stop itself. It defaults to 60 seconds.
If run interactively, you will be asked to confirm the operation. You need to confirm by typing the word “yes” in capitol letters.
There is little configuration needed. Just make sure that following two variables are set properly:
IMAGEDIR Directory where the disk images are stored, usually /var/lib/libvirt/images
XMLDIR Directory where the qemu files are stored, usually in /etc/libvirt/qemu.