个人工具

“UbuntuHelp:KVM”的版本间的差异

来自Ubuntu中文

跳转至: 导航, 搜索
第5行: 第5行:
 
=== Preliminary notes ===
 
=== Preliminary notes ===
 
* '''This is still work in progress! Feel free to jump in and extend this documentation! '''
 
* '''This is still work in progress! Feel free to jump in and extend this documentation! '''
* '''The previous version of this page (which was documenting KVM for Feisty) has been moved to [[UbuntuHelp:KVMFeisty|KVMFeisty]]'''
+
* '''The previous version of this page (which was documenting KVM for Feisty) has been moved to [[KVMFeisty]]'''
 +
* '''Also checkout the official docs, http://doc.ubuntu.com/ubuntu/serverguide/C/virtualization.html'''
 +
* The use case targeted when KVM was moved into main is '''"Single host server virtualization"'''.  This means that even though KVM can be used to serve other purposes, it has been designed to be run on Ubuntu Server Edition to host server operating systems.  If you are looking for a desktop virtualization tool, [[UbuntuHelp:VirtualBox|VirtualBox]], Parallel workstation or [[UbuntuHelp:VMware|VMware]] Player/Server can be more suitable alternatives.
 
=== Basic info ===
 
=== Basic info ===
Ubuntu uses [http://kvm.qumranet.com/ kvm] as the backend virtualisation technology. To manage VMs we use [http://libvirt.org/ libvirt] as the basic toolbox and [http://virt-manager.et.redhat.com/ virt-manager] as the graphical frontend for managing your vm's.
+
Ubuntu uses [[http://kvm.qumranet.com/|kvm]] as the backend virtualisation technology. To manage VMs we use [[http://libvirt.org/|libvirt]] as the basic toolbox and [[http://virt-manager.et.redhat.com/|virt-manager]] as the graphical frontend for managing your vm's.
 
== How to get started ==
 
== How to get started ==
 
=== How to check if your CPU supports hardware virtualisation ===
 
=== How to check if your CPU supports hardware virtualisation ===
第13行: 第15行:
 
<pre><nowiki>
 
<pre><nowiki>
 
egrep '(vmx|svm)' /proc/cpuinfo
 
egrep '(vmx|svm)' /proc/cpuinfo
 +
 
</nowiki></pre>
 
</nowiki></pre>
 
If nothing is printed, it means that your CPU doesn't support hardware virtualisation. Otherwise, it does - but you still need to make sure that virtualisation is enabled in the BIOS.
 
If nothing is printed, it means that your CPU doesn't support hardware virtualisation. Otherwise, it does - but you still need to make sure that virtualisation is enabled in the BIOS.
 +
=== Use a 64 bit kernel if you need more than 2GB RAM for your VMs ===
 +
To serve more than 2047 MB of RAM for your VMs, you '''must''' use a 64 bit kernel (see [[32bit_and_64bit]]). On a 32 bit kernel install, you'll be limited to 2GB RAM at maximum for a given VM.
 +
To see if your processor is 64 bit, you can run the following command:
 +
<pre><nowiki>
 +
grep ' lm ' /proc/cpuinfo
 +
</nowiki></pre>
 +
If nothing is printed, it means that your CPU is not 64 bit. ''lm'' stands for Long Mode, so 64 bit CPU.
 +
To see if your running kernel is 64 bit, just issue the following command:
 +
<pre><nowiki>
 +
uname -m
 +
</nowiki></pre>
 +
'''x86_64''' indicates a 64-bit kernel running. If you use see i386, i486, i586 or i686, you're running a 32 bit kernel.
 
=== Installation of KVM ===
 
=== Installation of KVM ===
For the following setup, we will assume that you are deploying KVM on a server, and therefore do not have any X server on the machine.  
+
For the following setup, we will assume that you are deploying KVM on a server, and therefore do not have any X server on the machine.
 
You need to install a few packages first:
 
You need to install a few packages first:
 
<pre><nowiki>
 
<pre><nowiki>
$ sudo apt-get install kvm libvirt-bin ubuntu-vm-builder
+
$ sudo apt-get install kvm libvirt-bin ubuntu-vm-builder qemu bridge-utils
 
</nowiki></pre>
 
</nowiki></pre>
 
* libvirt-bin provides libvirtd which you need to administer qemu and kvm instances using libvirt
 
* libvirt-bin provides libvirtd which you need to administer qemu and kvm instances using libvirt
 
* kvm is the backend
 
* kvm is the backend
 
* ubuntu-vm-builder powerful command line tool for building virtual machines
 
* ubuntu-vm-builder powerful command line tool for building virtual machines
Then, add yourself to the ''libvirtd'' and ''kvm'' groups:
+
* bridge-utils provides a bridge from your network to the virtual machines
 +
You might also want to install ''virt-viewer'', for viewing instances
 +
'''8.10 (intrepid) Notes''':
 +
* Two meta packages have been added: <code><nowiki>ubuntu-virt-server</nowiki></code> and <code><nowiki>ubuntu-virt-mgmt</nowiki></code>.  <code><nowiki>Ubuntu-virt-server</nowiki></code> installs the packages needed to setup a base virtulization host (kvm, libvirt-bin and openssh-server) and <code><nowiki>ubuntu-virt-mgmt</nowiki></code> installs what you need to administer it from a management station (virt-manager, python-vm-builder and virt-viewer). 
 +
* <code><nowiki>ubuntu-vm-builder</nowiki></code> has been replaced by <code><nowiki>python-vm-builder</nowiki></code> ([[JeOSVMBuilder|tutorial]]).
 +
=== Adding Users ===
 +
Add yourself to the ''libvirtd'' group (note that there is no need to add yourself to the ''kvm'' group):
 
<pre><nowiki>
 
<pre><nowiki>
 
$ sudo adduser `id -un` libvirtd
 
$ sudo adduser `id -un` libvirtd
$ sudo adduser `id -un` kvm
 
 
</nowiki></pre>
 
</nowiki></pre>
 
This will give you access to the system-wide libvirtd instance. This is preferable for you because it gives you access to the advanced networking options rather than simply the "userspace networking" option as you may know it from QEmu.
 
This will give you access to the system-wide libvirtd instance. This is preferable for you because it gives you access to the advanced networking options rather than simply the "userspace networking" option as you may know it from QEmu.
Note: You need to log out and log back in for the new group membership to take effect.
+
'''Note: You need to log out and log back in for the new group membership to take effect.'''
 
Note: The `id -un` command will return the current username, for example if your username is ''joe'' you will be effectively be running ''sudo adduser joe libvirtd''.
 
Note: The `id -un` command will return the current username, for example if your username is ''joe'' you will be effectively be running ''sudo adduser joe libvirtd''.
 
You can test if your install has been successful with the following command:
 
You can test if your install has been successful with the following command:
第48行: 第68行:
 
</nowiki></pre>
 
</nowiki></pre>
 
Something is wrong and you probably want to fix this before you move on. The critical point here is whether or not you have write access to ''/var/run/libvirt/libvirt-sock''.
 
Something is wrong and you probably want to fix this before you move on. The critical point here is whether or not you have write access to ''/var/run/libvirt/libvirt-sock''.
== Network Bridging ==
+
== Networking ==
There are a few different ways to allow a virtual machine access to the external network. The default virtual network configuration is usermode networking, which uses the SLIRP protocol and traffic is NATed through the host interface to the outside network.
+
There are a few different ways to allow a virtual machine access to the external network. The default virtual network configuration is usermode networking, which uses the SLIRP protocol and traffic is NATed through the host interface to the outside network. If you do not want to access network services on your virtual machine then you can skip this next step.
To enable external hosts to directly access services on virtual machines a bridge needs to be configured. This allows the virtual interfaces to connect to the outside network through the physical interface, making them appear as normal hosts to the rest of the network.  
+
However to enable external hosts to directly access services on virtual machines a bridge needs to be configured. This allows the virtual interfaces to connect to the outside network through the physical interface, making them appear as normal hosts to the rest of the network.
 
'''Warning:''' Network bridging will not work when the physcial network device (eg eth1, ath0) used for bridging is a wireless device (eg ipw3945), as most wireless device drivers do not support bridging!
 
'''Warning:''' Network bridging will not work when the physcial network device (eg eth1, ath0) used for bridging is a wireless device (eg ipw3945), as most wireless device drivers do not support bridging!
 +
'''Warning 2:''' It seems that due to the implementation of CAP_NET_ADMIN in kernel 2.6.18, root access is needed to bring tap interfaces up and down. This means you'll need to run the VM Manager with gksudo (bad) or place a wrapper around the bits that bring up the taps (messy). More info when I figure this one out. (srodden)
 
=== Creating a network bridge on the host ===
 
=== Creating a network bridge on the host ===
To setup a bridge interface edit /etc/network/interfaces and either comment or replace the existing config with (replace with the values for your network):
+
We are going to change the network configuration. To do it properly, we should first stop networking<<FootNote(This is needed for example when you move from DHCP to static address: it will stop the DHCP client, which a restart won't do if you changed the configuration already. If you are changing this remotely, then you should prepare your new configuration into a separate file and the use a script to stop networking, put the new configuration in place and start it back.)>>:
 +
<pre><nowiki>
 +
invoke-rc.d networking stop
 +
</nowiki></pre>
 +
To setup a bridge interface, edit /etc/network/interfaces and either comment or replace the existing config with (replace with the values for your network):
 
<pre><nowiki>
 
<pre><nowiki>
 
auto lo
 
auto lo
 
iface lo inet loopback
 
iface lo inet loopback
 +
 +
auto eth0
 +
iface eth0 inet manual
  
 
auto br0
 
auto br0
第71行: 第99行:
 
         bridge_stp off
 
         bridge_stp off
  
iface eth0 inet static
 
address 172.16.5.0
 
netmask 255.255.255.0
 
 
</nowiki></pre>
 
</nowiki></pre>
 
or to use DHCP
 
or to use DHCP
第79行: 第104行:
 
auto lo
 
auto lo
 
iface lo inet loopback
 
iface lo inet loopback
 +
 +
auto eth0
 +
iface eth0 inet manual
  
 
auto br0
 
auto br0
第88行: 第116行:
 
         bridge_stp off
 
         bridge_stp off
  
iface eth0 inet static
 
address 172.16.5.0
 
netmask 255.255.255.0
 
 
</nowiki></pre>
 
</nowiki></pre>
This will create a virtual interface br0. Don't worry about the static eth0 line. It gets overwritten by the bridge but the statement is necessary or you get an eth0 error.  
+
This will create a virtual interface br0.
Now restart networking :
+
Now restart networking:
 
<pre><nowiki>
 
<pre><nowiki>
 
sudo /etc/init.d/networking restart
 
sudo /etc/init.d/networking restart
第128行: 第153行:
 
     </interface>
 
     </interface>
 
</nowiki></pre>
 
</nowiki></pre>
 +
'''Note: Make sure the first octet in your MAC address is EVEN (eg. 00:)''' as MAC addresses with ODD first-bytes (eg. 01:) are reserved for multicast communication and can cause confusing problems for you.  For instance, the guest will be able to receive ARP packets and reply to them, but the reply will confuse other machines.  This is not a KVM issue, but just the way Ethernet works.
 
You do not need to restart libvirtd to reload the changes; the easiest way is to log into virsh (a command line tool to manage VMs), stop the VM, reread its configuration file, and restart the VM:
 
You do not need to restart libvirtd to reload the changes; the easiest way is to log into virsh (a command line tool to manage VMs), stop the VM, reread its configuration file, and restart the VM:
 
<pre><nowiki>
 
<pre><nowiki>
 
yhamon@paris:/etc/libvirt/qemu$ ls
 
yhamon@paris:/etc/libvirt/qemu$ ls
 
mirror.xml  networks  vm2.xml
 
mirror.xml  networks  vm2.xml
yhamon@paris:/etc/libvirt/qemu$ sudo virsh
+
yhamon@paris:/etc/libvirt/qemu$ virsh --connect qemu:///system
 
Connecting to uri: qemu:///system
 
Connecting to uri: qemu:///system
 
Welcome to virsh, the virtualization interactive terminal.
 
Welcome to virsh, the virtualization interactive terminal.
第156行: 第182行:
 
</nowiki></pre>
 
</nowiki></pre>
 
The VM "mirror" is now using bridged networking.
 
The VM "mirror" is now using bridged networking.
 +
=== DNS and DHCP Guests ===
 +
libvirt uses dnsmasq to hand out IP addresses to guests which are configured to use dhcp. If on your host machine, you add 192.168.122.1 (the default IP of your host in libvirt) as your first nameserver in /etc/resolv.conf, then you can do name resolution for your guests. dnsmasq is smart enough to use the other 'nameserver' entries in your /etc/resolv.conf for resolving non-libvirt addresses. For example, if your current /etc/resolv.conf is:<pre><nowiki>
 +
search example.com
 +
nameserver 10.0.0.1
 +
</nowiki></pre>
 +
Change this to be:<pre><nowiki>
 +
search example.com
 +
nameserver 192.168.122.1
 +
nameserver 10.0.0.1
 +
</nowiki></pre>
 +
Now, if you have a virtual machine named 'hardy-amd64', after starting it, you can do: <pre><nowiki>
 +
$ host hardy-amd64
 +
hardy-amd64 has address <IP address given by dnsmasq>
 +
</nowiki></pre>
 +
Note that when using ssh you may need to use a trailing '.' after the hostname:<pre><nowiki>
 +
$ ssh hardy-amd64.
 +
</nowiki></pre>
 +
Finally, for this to work, your guest must send its hostname as part of the dhcp request. This is done automatically on many operating systems. For systems that do not send this automatically and use dhcp3, you can adjust the dhclient.conf file. For example, on Ubuntu 6.06 LTS (Dapper), adjust /etc/dhcp3/dhclient.conf to have:<pre><nowiki>
 +
send host-name "<your guest hostname here>";
 +
</nowiki></pre>
 +
'''IMPORTANT:''' Depending on your network configuration, your host's /etc/resolv.conf file might be periodically overwritten. You will have to either adjust the dhcp server on your network to hand out the additional libvirt name server for your libvirt hosts, or adjust each host machine accordingly. As there are many possible configurations for host machines, user's are encouraged to look at <code><nowiki>resolvconf</nowiki></code> and/or <code><nowiki>man interfaces</nowiki></code>.
 +
=== Booting Over the Network Using PXE ===
 +
The current Ubuntu release does not ship pxe binary ROM images because the source code is not included to recreate the images in the upstream tarball.  There may be a way to automate the creation of these files as part of the package.  In order to use boot -n, you will need to download or create the appropriate ROM images from [[http://etherboot.org]]
 +
KVM and QEMU can emulate a number of network cards.  Here is the current ROM files
 +
{|border="1" cellspacing="0"
 +
| 'KVM Name' ''nic,model='' |||| 'Etherboot Identification' |||| 'Etherboot Filename' |||| 'KVM filename'
 +
|-
 +
| i82551 |||| |||| |||| pxe-i82551.bin
 +
|-
 +
| i82557b |||| |||| |||| pxe-i82557b.bin
 +
|-
 +
| i82559er |||| |||| |||| pxe-i82559er.bin
 +
|-
 +
| ne2k_pci (default) |||| ns8390:rtl8029 -- [10ec,8029] |||| gpxe-0.9.3-rtl8029.rom |||| pxe-ne2k_pci.bin
 +
|-
 +
| ne2k_isa |||| |||| |||| pxe-ne2k_isa.bin
 +
|-
 +
| pcnet |||| |||| |||| pxe-pcnet.bin
 +
|-
 +
| rtl8139 |||| |||| |||| pxe-rtl8139.bin
 +
|-
 +
| e1000 |||| ((e1000:e1000-0x1026 -- [8086,1026])) |||| gpxe-0.9.3-e1000-0x1026.rom |||| pxe-e1000.bin
 +
|-
 +
| smc91c111 |||| |||| |||| pxe-smc91c111.bin
 +
|-
 +
| lance |||| |||| |||| pxe-lance.bin
 +
|-
 +
| mcf_fec |||| |||| |||| pxe-mcf_fec.bin
 +
|}
 +
Copy the respective file to /usr/share/kvm and/or /usr/share/qemu.
 
== Creating virtual machines ==
 
== Creating virtual machines ==
Now that KVM is installed, let s see how we install our first VM. There is a tool to manage VMs on a remote host: virt-manager. Sadly, VM creation on a remote host is not supported yet - therefore you will have to create the VM in command line.
+
Now that KVM is installed, let s see how we install our first VM. There is a tool to manage VMs on a remote host: virt-manager. Sadly, VM creation on a remote host is not supported yet through virt-manager - therefore you will have to create the VM in command line.
There are two different tools to do this; virt-install, a python script developed by redhat, and ubuntu-vm-builder, developed by Canonical.  
+
There are two different tools to do this; virt-install, a python script developed by Red Hat, and ubuntu-vm-builder, developed by Canonical.
 
=== Ubuntu-vm-builder: the fast & powerful way to create Ubuntu JEOS VMs ===
 
=== Ubuntu-vm-builder: the fast & powerful way to create Ubuntu JEOS VMs ===
[http://doc.ubuntu.com/ubuntu/serverguide/C/ubuntu-vm-builder.html Ubuntu-vm-builder] is probably the best tool to use if you want to create VMs running Ubuntu JEOS 8.04, as the install is entirely scripted (very fast).  
+
[[http://doc.ubuntu.com/ubuntu/serverguide/C/ubuntu-vm-builder.html|Ubuntu-vm-builder]] is probably the best tool to use if you want to create VMs running Ubuntu JEOS 8.04, as the install is entirely scripted (very fast).
 
This tool is packaged, and in universe:
 
This tool is packaged, and in universe:
 
<pre><nowiki>
 
<pre><nowiki>
第171行: 第247行:
 
</nowiki></pre>
 
</nowiki></pre>
 
This will create an Ubuntu Hardy, with all options set to default.
 
This will create an Ubuntu Hardy, with all options set to default.
 +
Or you can use this URL to a Javascript tool that generates the lengthy set of parameters available for ubuntu-vm-builder:
 +
* http://people.ubuntu.com/~kirkland/ubuntu-vm-builder.html
 +
Note: if you want to use Virsh to manage your virtual machines as detailed below, you must add
 +
<pre><nowiki>
 +
--libvirt qemu:///system
 +
</nowiki></pre>
 +
to the list of arguments that the javascript produces. The javascript does not have an option for this itself, unfortunately.
 
==== More complex example ====
 
==== More complex example ====
 
Now here is a somewhat more complex example:
 
Now here is a somewhat more complex example:
第190行: 第273行:
 
                   --mirror http://archive.localubuntumirror.net/ubuntu \
 
                   --mirror http://archive.localubuntumirror.net/ubuntu \
 
                   --components main,universe \
 
                   --components main,universe \
                   --addpkg vim \
+
                   --addpkg vim openssh-server \
 
                   --libvirt qemu:///system ;
 
                   --libvirt qemu:///system ;
 
</nowiki></pre>
 
</nowiki></pre>
This will create a new Ubuntu Hardy VM called "newvm", the hostname will be set to "hostnameformyvm", the network will be configured with a static IP address and a gateway at address 192.168.0.1. The --mirror will tell the script to download the packages from a local Ubuntu mirror instead of the default server (this may speed up by a lot the time necessary to create the VM). The components argument will enable main and universe by default on the VM, --addpkg vim will install vim, and finally the last argument will automatically add the newly created VM to KVM.  
+
This will create a new Ubuntu Hardy VM called "newvm", the hostname will be set to "hostnameformyvm", the network will be configured with a static IP address and a gateway at address 192.168.0.1. The --mirror will tell the script to download the packages from a local Ubuntu mirror instead of the default server (this may speed up by a lot the time necessary to create the VM). The components argument will enable main and universe by default on the VM, --addpkg vim will install vim, and finally the last argument will automatically add the newly created VM to KVM.
 +
By adding 'openssh-server' with --addpkg, we will be able to ssh into our new machine once its started (provided the networking works correctly).
 
Note: The manual isn't specific about the --exec option, used to execute a script file during the vm build process. If you specify the --exec option then you must provide the full path to the script you are executing. Not doing so will cause the installer to tell you that it can't find the script file.
 
Note: The manual isn't specific about the --exec option, used to execute a script file during the vm build process. If you specify the --exec option then you must provide the full path to the script you are executing. Not doing so will cause the installer to tell you that it can't find the script file.
 +
'''Bug notice: ''' it seems that the package 'linux-package' is not found during the machine building process unless 'restricted' is also specified as a component option to ubuntu-vm-builder. If not specified, you'll get a non-functioning system that boots into grub only. This line makes it work for me:
 +
<pre><nowiki>
 +
--components 'main,universe,restricted'
 +
</nowiki></pre>
 +
I'm assuming this is a bug in ubuntu-vm-builder.
 
==== Install on a raw block device ====
 
==== Install on a raw block device ====
 
Ubuntu-vm-builder doesn't allow you to create the VM on a raw block device yet (like a standalone partition, or a iSCSI share). You can use ubuntu-vm-builder to create the qcow2 image and then move the VM to the block device with qemu-img though; if /dev/sdb is the disk device on which you want to move the virtual machine:
 
Ubuntu-vm-builder doesn't allow you to create the VM on a raw block device yet (like a standalone partition, or a iSCSI share). You can use ubuntu-vm-builder to create the qcow2 image and then move the VM to the block device with qemu-img though; if /dev/sdb is the disk device on which you want to move the virtual machine:
第205行: 第294行:
 
</nowiki></pre>
 
</nowiki></pre>
 
Redefine the VM and start it; it is now running from /dev/sdb.
 
Redefine the VM and start it; it is now running from /dev/sdb.
Ubuntu-vm-builder is a very powerful tool - to get a more detailed list of its capabilities, use ubuntu-vm-builder --help.  
+
Ubuntu-vm-builder is a very powerful tool - to get a more detailed list of its capabilities, use ubuntu-vm-builder --help.
 +
=== Use virtio for Ubuntu Hardy guests ===
 +
You may find the performances of the network relatively poor (approx. 100/120mbits on my servers, which are quite fast). If you are running Ubuntu Hardy, you can enable virtio. Go to the definition file of your VM, and add the virtio line to the definition of your network interface:
 +
<pre><nowiki>
 +
    <interface type='bridge'>
 +
      <mac address='52:54:00:a0:41:92'/>
 +
      <source bridge='br0'/>
 +
      <model type='virtio'/>  <-- add this line, leave the rest
 +
    </interface>
 +
</nowiki></pre>
 +
This improves the network performances by a lot (factor 10, nearly). But this works only with ubuntu hardy guests for the moment, which is why it is not by default.
 
=== Create VMs running other operating systems: virt-install ===
 
=== Create VMs running other operating systems: virt-install ===
Virt-install is radically different in the way it works. Instead of creating automagically a new VM, it will allow you to boot on an iso, and therefore to install almost any operating system.  For a list of supported operating system, consult [http://kvm.qumranet.com/kvmwiki/Guest_Support_Status kvm's official webpage].
+
Virt-install is radically different in the way it works. Instead of creating automagically a new VM, it will allow you to boot on an iso, and therefore to install almost any operating system.  For a list of supported operating system, consult [[http://kvm.qumranet.com/kvmwiki/Guest_Support_Status|kvm's official webpage]].
 +
==== Example Windows install ====
 +
{{http://waste.mandragor.org/windows-kvm.png}}
 
Copy the ISO of the system you want to install to your working directory:
 
Copy the ISO of the system you want to install to your working directory:
 
<pre><nowiki>
 
<pre><nowiki>
第213行: 第314行:
 
ubuntu-8.04-server-i386.iso  windowsxpsp2.iso
 
ubuntu-8.04-server-i386.iso  windowsxpsp2.iso
 
</nowiki></pre>
 
</nowiki></pre>
Then, run virt-install:
+
or create an ISO from a cd/dvd:
 +
<pre><nowiki>
 +
dd if=/dev/dvd of=dvd.iso
 +
</nowiki></pre>
 +
Install virt-install:
 +
<pre><nowiki>
 +
sudo apt-get install python-virtinst
 +
</nowiki></pre>
 +
Then, run virt-install (the install of windows XP doesn't work when accelerated with --accelerate, so run the install and then replace qemu by kvm in the XML file once installed):
 
<pre><nowiki>
 
<pre><nowiki>
sudo virt-install -n xpsp2 -r 512 -f devserver.img -s 5 -c windowsxpsp2.iso --accelerate --vnc --noautoconsole
+
sudo virt-install --connect qemu:///system -n xpsp2 -r 512 -f windows.qcow2 -s 12 -c windowsxpsp2.iso --vnc --noautoconsole --os-type windows --os-variant winxp
 
</nowiki></pre>
 
</nowiki></pre>
 
This will boot a new VM from the ISO. Connect to the new VM using virt-viewer:
 
This will boot a new VM from the ISO. Connect to the new VM using virt-viewer:
 
<pre><nowiki>
 
<pre><nowiki>
virt-viewer -c qemu+ssh://10.10.10.10/system xpsp2
+
virt-viewer -c qemu:///system xpsp2
 +
</nowiki></pre>
 +
Or if KVM is running on a different server:
 +
<pre><nowiki>
 +
virt-viewer -c qemu+ssh://ip/system xpsp2
 
</nowiki></pre>
 
</nowiki></pre>
 
You should now have a graphical interface to install your VM!
 
You should now have a graphical interface to install your VM!
 +
==== Example Ubuntu install ====
 +
You can perform the following to install Ubuntu Hardy:<pre><nowiki>
 +
sudo virt-install --connect qemu:///system -n hardy -r 512 -f hardy.qcow2 -s 12 -c hardy-server-amd64.iso --vnc --noautoconsole --os-type linux --os-variant ubuntuHardy --accelerate --network=network:default
 +
</nowiki></pre>
 +
The '--network' option sets up the machine to use the default libvirt network. You can see available libvirt networks with:<pre><nowiki>
 +
virsh net-list --all
 +
</nowiki></pre>
 +
==== Other Operating Systems ====
 +
Other Operating Systems can be installed using the same method as above. See 'man virt-install' for more information on different options for your virtual machine and supported OS types and OS variants.
 +
'''Warning:''' this method fails with Fedora [[UbuntuHelp:LiveCD|LiveCD]] installations and possibly others; see the bug here: https://bugs.launchpad.net/ubuntu/+source/kvm/+bug/220463
 +
=== Cloning a virtual machine ===
 +
You can clone an existing virtual machine using the virt-clone tool.  This duplicates the disk image and sets up the virtual machine domain configuration.
 +
If you wish to clone a virtual machine named ''srchost'' to a new machine ''newhost'', ensure that the virtual machine ''srchost'' is not running and execute the following command.
 +
<pre><nowiki>
 +
$ virt-clone --connect=qemu:///system -o srchost -n newhost -f /path/to/newhost.qcow2
 +
</nowiki></pre>
 
== Manage your virtual machines ==
 
== Manage your virtual machines ==
 
=== From the shell ===
 
=== From the shell ===
You can manage your VMs from the shell using [http://linux.die.net/man/1/virsh virsh]. You can get a list of the available commands if you type "help". Type "help command" to get additional infos for a particular command.
+
You can manage your VMs from the shell using [[http://linux.die.net/man/1/virsh|virsh]]. You can get a list of the available commands if you type "help". Type "help command" to get additional infos for a particular command.
 +
==== Define your new VM ====
 +
Before you can manage your new VM with virsh, you must define it:
 +
<pre><nowiki>
 +
$ virsh --connect qemu:///system
 +
Connecting to uri: qemu:///system
 +
Welcome to virsh, the virtualization interactive terminal.
 +
 
 +
Type:  'help' for help with commands
 +
      'quit' to quit
 +
 
 +
virsh # define /etc/libvirt/qemu/newvm.xml
 +
Domain newvm defined from /etc/libvirt/qemu/newvm.xml
 +
</nowiki></pre>
 +
Note that to list newvm, you must use 'list --inactive' or 'list --all', since list without any options will only list currently running machines.
 
==== List your VMs ====
 
==== List your VMs ====
 
Virsh allows you to list the virtual machines available on the current host:
 
Virsh allows you to list the virtual machines available on the current host:
 
<pre><nowiki>
 
<pre><nowiki>
yhamon@paris:/etc/libvirt/qemu$ sudo virsh
+
yhamon@paris:/etc/libvirt/qemu$ virsh --connect qemu:///system
 
Connecting to uri: qemu:///system
 
Connecting to uri: qemu:///system
 
Welcome to virsh, the virtualization interactive terminal.
 
Welcome to virsh, the virtualization interactive terminal.
第261行: 第404行:
 
  16 vm2                  running
 
  16 vm2                  running
 
   - test5                shut off
 
   - test5                shut off
</nowiki></pre>  
+
</nowiki></pre>
 
==== Define, undefine, start, shutdown, destroy VMs ====
 
==== Define, undefine, start, shutdown, destroy VMs ====
 
The VMs you see with list --all are VMs that have been "defined" from an XML file. Every VM is configured via a XML file in /etc/libvirt/qemu. If you want to remove a VM from the list of VMs, you need to undefine it:
 
The VMs you see with list --all are VMs that have been "defined" from an XML file. Every VM is configured via a XML file in /etc/libvirt/qemu. If you want to remove a VM from the list of VMs, you need to undefine it:
第313行: 第456行:
 
</nowiki></pre>
 
</nowiki></pre>
 
10.10.10.10 being the IP address of your host running KVM.
 
10.10.10.10 being the IP address of your host running KVM.
https://help.ubuntu.com/community/KVM?action=AttachFile&do=get&target=virt-manager.png
+
{{http://waste.mandragor.org/virt-manager-screenshot.png}}
== How-to edit the attributes of a Virtual Machine (add CPUs, RAM) ==
+
If you are only managing machines on your own host you can use only:
KVM allows you to create SMP guests: If you have several processors/cores on the KVM host, each VM can use one or more than one of these. To add CPUs to one VM, you need to edit the '/etc/libvirt/qemu/yourvm.xml' file:
+
 
<pre><nowiki>
 
<pre><nowiki>
 +
$ virt-manager -c qemu:///system
 +
</nowiki></pre>
 +
== Editing the attributes of a Virtual Machine ==
 +
libvirt stores it's configuration as xml in '/etc/libvirt/qemu'. The xml is easy to understand, and is similar to [[UbuntuHelp:VMware|VMware]] *.vmx files. While it is possible to edit these files in place and restart libvirt-bin for the changes to take affect, the recommended method for modifying the attributes of a virtual machine is via virsh (or virt-manager, if it supports changing the hardware you want to change). The concept is simple:
 +
<ol><li>export (aka 'dump') the xml of the virtual machine you want to edit
 +
</li><li>edit the xml
 +
</li><li>import (aka 'define') the xml</li></ol>
 +
 +
For example, to edit the machine named 'foo' (you can get a list of your machines with 'virsh list --all'), do:<pre><nowiki>
 +
$ virsh dumpxml foo > /tmp/foo.xml
 +
(edit /tmp/foo.xml as needed)
 +
$ virsh define /tmp/foo.xml
 +
</nowiki></pre>
 +
=== Adding CPUs ===
 +
KVM allows you to create SMP guests. To allocate two CPUs to a VM, dump the xml as above, then edit your xml to have:<pre><nowiki>
 
<domain type='kvm'>
 
<domain type='kvm'>
   <name>mirror</name>
+
   ...
   <uuid>ec13fb81-7960-ec5a-fa99-d8928f75d3ea</uuid>
+
   <vcpu>2</vcpu>
   <memory>524288</memory>
+
   ...
  <currentMemory>524288</currentMemory>
+
</domain>
  <vcpu>1</vcpu>
+
</nowiki></pre>
  <os>
+
Now define the VM as above.
    <type>hvm</type>
+
=== Adding Memory ===
    <boot dev='hd'/>
+
To change the memory allocation in a VM, dump the xml as above, then edit your xml to have:<pre><nowiki>
   </os>
+
<domain type='kvm'>
   <clock offset='utc'/>
+
   ...
   <on_poweroff>destroy</on_poweroff>
+
   <memory>262144</memory>
   <on_reboot>restart</on_reboot>
+
   <currentMemory>262144</currentMemory>
  <on_crash>destroy</on_crash>
+
   ...
  <devices>
+
</domain>
    <emulator>/usr/bin/kvm</emulator>
+
</nowiki></pre>
    <disk type='file' device='disk'>
+
Now define the VM as above.  Keep in mind that the memory allocation is in kilobytes, so to allocate 512MB of memory, use 512 * 1024, or 524288.
      <source file='/home/yhamon/mirror.img'/>
+
=== Changing the Network Card Model ===
      <target dev='hda' bus='ide'/>
+
kvm and qemu currently default to using the rtl8139 NIC. Supported NICs in Ubuntu 8.04 LTS are i82551, i82557b, i82559er, ne2k_pci, pcnet, rtl8139, e1000, and virtio. To use an alternate NIC, dump the xml as above, then edit your xml to have:<pre><nowiki>
    </disk>
+
<domain type='kvm'>
     <interface type='bridge'>
+
  ...
       <mac address='00:16:3e:4d:94:c0'/>
+
     <interface type='network'>
       <source bridge='br0'/>
+
       ...
 +
       <model type='e1000'/>
 
     </interface>
 
     </interface>
    <input type='mouse' bus='ps2'/>
+
  ...
    <graphics type='vnc' port='-1' listen='127.0.0.1'/>
+
  </devices>
+
 
</domain>
 
</domain>
 
</nowiki></pre>
 
</nowiki></pre>
This file is the equivalent of *.vmx files in vmware, and is pretty easy to understand. To assign 2 CPUs to your VM, just change '<vcpu>1</vcpu>' by '<vcpu>2</vcpu>'. You will need to shutdown your vm, redefine it, and restart it, to have the changes active (see previous chapter for how to do this).
+
Now define the VM as above.
 +
=== Get new IDs ===
 +
To get a new mac address to paste into your xml file, use this command:
 +
MACADDR="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"; echo $MACADDR
 +
To get a new uuid for your xml file, use: uuidgen
 +
== KVM from the command line ==
 +
KVM is very similar to qemu and it is possible to run machines from the command line. The basic syntax is :
 +
<pre><nowiki>
 +
kvm -m 512 -hda disk.img -cdrom ubuntu.iso -boot d -smp 2
 +
</nowiki></pre>
 +
* -m = memory (in MB)
 +
* -hda = first hard drive
 +
* You can use a number of image file types including .img, .cow
 +
* You can also boot a hard drive. '''Be careful with this option as you do not want to boot the host root partition'''
 +
* Syntax -hda /dev/sda
 +
* This will call your grub menu from your MBR when you boot kvm.
 +
* -cdrom can be an iso image or a CD/DVD drive.
 +
* -boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)
 +
* -smp = number of CPU
 +
* -alt-grab change Ctrl-Alt mouse grab combination for Ctrl-Alt-Shift (very practical if you often use some control key combinations like Ctrl-Alt-Del or Windows-E)
 +
There are a number of additional options and additional help is available with :
 +
<pre><nowiki>
 +
kvm --help
 +
</nowiki></pre>
 +
=== Bridged Networking ===
 +
In order to run KVM using bridged networking as a user we need to perform some configuration.
 +
1. First bridge your network card as above [[UbuntuHelp:KVM#Creating_a_network_bridge_on_the_host|| Creating a network bridge on the host]]
 +
2. Install uml-utilities
 +
 
 +
<pre><nowiki>
 +
sudo apt-get install uml-utilities
 +
</nowiki></pre>
 +
3. Set permissions on your tun device. Using any editor, edit ''/etc/udev/rules.d/40-permissions.rules'', add this line at the bottom of the file :
 +
 
 +
<pre><nowiki>
 +
KERNEL=="tun", GROUP="kvm", MODE="0660"
 +
</nowiki></pre>
 +
4. Reboot (to bring up your bridge and tun device).
 +
5. Edit ''/etc/kvm/kvm-ifup'' adding sudo in front of the ifconfig and brctl commands
 +
 
 +
<pre><nowiki>
 +
#!/bin/sh
 +
 
 +
switch=$(ip route ls | awk '/^default / { for(i=0;i<NF;i++) { if ($(i) == "dev") print $(i+1) }}')
 +
'''sudo''' /sbin/ifconfig $1 0.0.0.0 up
 +
'''sudo''' /usr/sbin/brctl addif ${switch} $1
 +
exit 0
 +
</nowiki></pre>
 +
6. We need a wrapper script for launching kvm. I put this script in ~/bin and call it '''kvm-bridge'''. If ~/bin is on your path you can call the command directly with '''kvm-bridge'''. This script was modified from a number of sources
 +
 
 +
<pre><nowiki>
 +
#!/usr/bin/env bash
 +
# script to manage tap interface allocation
 +
# for linux kernels >= 2.6.18
 +
 
 +
# modified by bodhi.zazen from :
 +
# http://calamari.reverse-dns.net:980/cgi-bin/moin.cgi/FrequentlyAskedQuestions#head-2511814cb92c14dbe1480089c04f83c281117a86
 +
# http://ubuntuforums.org/showthread.php?t=528046
 +
# http://www.howtoforge.com/using-kvm-on-ubuntu-gutsy-gibbon
 +
 
 +
# set up a tap interface for qemu
 +
# USERID - uid qemu is being run under.
 +
USERID=`whoami`
 +
 
 +
# generate a random mac address for the qemu nic
 +
# shell script borrowed from user pheldens @ qemu forum
 +
 
 +
ranmac=$(echo -n DE:AD:BE:EF ; for i in `seq 1 2` ; \
 +
do echo -n `echo ":$RANDOM$RANDOM" | cut -n -c -3` ;done)
 +
 
 +
# specify which NIC to use - see qemu.org for others
 +
# model=r8169
 +
# Set model based on this how-to
 +
# http://www.howtoforge.com/using-kvm-on-ubuntu-gutsy-gibbon
 +
 
 +
model=rtl8139
 +
iface=`sudo tunctl -b -u $USERID`
 +
 
 +
# start kvm with our parameters
 +
# echo "Bringing up interface $iface with mac address $ranmac"
 +
# nohup added to allow kvm to run independent of the terminal
 +
nohup kvm -net nic,vlan=0,macaddr=$ranmac -net tap,vlan=0,ifname=$iface $@
 +
 
 +
# kvm has stopped - no longer using tap interface
 +
sudo tunctl -d $iface &> /dev/null
 +
</nowiki></pre>
 +
7. Set the executable bit on the new script you just created:
 +
 
 +
<pre><nowiki>
 +
chmod 0755 ~/bin/kvm-bridge
 +
</nowiki></pre>
 +
8. Modify sudoers to allow members of the kvm group to run the wrapper kvm-bridge and create a bridged network interface without running KVM as root.
 +
 
 +
<pre><nowiki>
 +
visudo
 +
</nowiki></pre>
 +
Add these line at the end of the file :
 +
<pre><nowiki>
 +
# Allow members of the kvm group to configure a bridged virtual network interface
 +
%kvm ALL=(ALL) NOPASSWD: /sbin/ifconfig, /usr/sbin/brctl, /usr/sbin/tunctl
 +
</nowiki></pre>
 +
9. Now start kvm from the command line. '''You do not need to declare a network interface'''
 +
 
 +
<pre><nowiki>
 +
kvm-bridge -m 512 -hda disk.img -cdrom ubuntu.iso -boot -d -smp 2
 +
</nowiki></pre>
 +
=== iptables ===
 +
Add these rules to iptables :
 +
<pre><nowiki>
 +
# allow incoming packets for kvm guest
 +
IPTABLES -A FORWARD -d $IPADDR_FROM_GUEST_OS -j ACCEPT
 +
# allow outgoing packets from kvm
 +
IPTABLES -A FORWARD -s $IPADDR_FROM_GUEST_OS -j ACCEPT
 +
</nowiki></pre>
 +
Change "$IPADDR_FROM_GUEST_OS" to the actual ip address of the kvm guest (I advise you configure your guests to have a static IP address).
 +
If you use ufw, add these rules to ''/etc/ufw/before.rules''
 +
* See [[https://help.ubuntu.com/8.04/serverguide/C/firewall.html | Ubuntu Server Guide Firewall]]
 
== Troubleshooting/FAQ ==
 
== Troubleshooting/FAQ ==
 +
=== Virtualbox and KVM ===
 +
Installing kvm loads the module kvm (or kvm-intel in my case) which does not allow other virtualization software to run, e.g. virtualbox. See [[UbuntuHelp:KVM#head-e46c0245ab3a34e43db63059478fa1a68d18128f|Removal|section]] to set this straight :)
 
=== How to boot Dapper, Edgy, Feisty or Gutsy ISO ===
 
=== How to boot Dapper, Edgy, Feisty or Gutsy ISO ===
 
* Q: I'm on Intel hardware, and I'm trying to boot Dapper, Edgy, Feisty, or Gutsy, but kvm fails immediately.
 
* Q: I'm on Intel hardware, and I'm trying to boot Dapper, Edgy, Feisty, or Gutsy, but kvm fails immediately.
第355行: 第629行:
 
</nowiki></pre>
 
</nowiki></pre>
 
/!\ Don't change the above command! The length of the string mustn't change or you will have knackered the filesystem on the CD.
 
/!\ Don't change the above command! The length of the string mustn't change or you will have knackered the filesystem on the CD.
A slightly safer way is to download gfxboot-disable from [http://hg.codemonkey.ws/gfxboot-disable] and then run:
+
A slightly safer way is to download gfxboot-disable from [[http://hg.codemonkey.ws/gfxboot-disable]] and then run:
 
<pre><nowiki>
 
<pre><nowiki>
 
$ gfxboot-disable ubuntu-7.10-server-amd64.iso
 
$ gfxboot-disable ubuntu-7.10-server-amd64.iso
 
</nowiki></pre>
 
</nowiki></pre>
 +
=== Boot a VM into single mode ===
 +
A VM has a complete BIOS, and also runs GRUB. Bad point is, it disappears after a couple of seconds, most of the time you won't even have time to connect using virt-viewer. There is a small trick here: shutdown the VM, run virt-viewer with the argument --wait (that way it will wait for the VM to start and pop up directly after that), and then start the VM; this should give you a good 2 seconds time to enter the bios or access grub.
 +
If you are running a VM built with ubuntu-vm-builder, there is a small bug that will prevent you from logging in; in grub, select the recovery line and press "e"; select the line beginning with kernel, press "e" again. At the end of the line, add "init=/bin/sh" (without the quotes). Confirm with enter, and press b to boot the kernel with these settings.
 
=== How to convert [[UbuntuHelp:VMware|VMware]] machines to virt-manager ===
 
=== How to convert [[UbuntuHelp:VMware|VMware]] machines to virt-manager ===
 
kvm has the ability to use [[UbuntuHelp:VMware|VMware]]'s vmdk disk files directly, as long as the disk is wholly contained in the vmdk (ie [[UbuntuHelp:VMware|VMware]] allows splitting a disk into smaller, usually 2GB, vmdk files. kvm can't use these). Point kvm at the vmdk with the appropriate options (see <code><nowiki> man kvm-qemu </nowiki></code>), and it should work.
 
kvm has the ability to use [[UbuntuHelp:VMware|VMware]]'s vmdk disk files directly, as long as the disk is wholly contained in the vmdk (ie [[UbuntuHelp:VMware|VMware]] allows splitting a disk into smaller, usually 2GB, vmdk files. kvm can't use these). Point kvm at the vmdk with the appropriate options (see <code><nowiki> man kvm-qemu </nowiki></code>), and it should work.
第366行: 第643行:
 
$ virsh -c qemu:///system define file.xml
 
$ virsh -c qemu:///system define file.xml
 
</nowiki></pre>
 
</nowiki></pre>
The first command converts the [[UbuntuHelp:VMware|VMware]] 'file.vmx' file to the libvirt compatible 'file.xml'. See <code><nowiki> man vmware2libvirt </nowiki></code> for details. '''Note:''' until vmware2libvirt is shipped with the libvirt packages, you can download it from [http://people.ubuntu.com/~soren/vmware2libvirt/]. The second command imports file.xml into libvirt. The imported .xml files are stored in /etc/libvirt/qemu.
+
The first command converts the [[UbuntuHelp:VMware|VMware]] 'file.vmx' file to the libvirt compatible 'file.xml'. See <code><nowiki> man vmware2libvirt </nowiki></code> for details. '''Note:''' until vmware2libvirt is shipped with the libvirt packages, you can download it from [[http://people.ubuntu.com/~soren/vmware2libvirt/]]. The second command imports file.xml into libvirt. The imported .xml files are stored in /etc/libvirt/qemu.
 
'''IMPORTANT:''' keep in mind that while the .vmx file is converted to .xml, the disks are used as is. Please make backups, especially if you want to use the virtual machine in [[UbuntuHelp:VMware|VMware]] later.
 
'''IMPORTANT:''' keep in mind that while the .vmx file is converted to .xml, the disks are used as is. Please make backups, especially if you want to use the virtual machine in [[UbuntuHelp:VMware|VMware]] later.
 
==== Caveats ====
 
==== Caveats ====
第383行: 第660行:
 
</li><li>vmware2libvirt does not (and cannot) convert anything that was VMware-specific within the guest. See 'Guest Notes' below for more details.</li></ol>
 
</li><li>vmware2libvirt does not (and cannot) convert anything that was VMware-specific within the guest. See 'Guest Notes' below for more details.</li></ol>
  
==== Guest notes ====
+
=== Guest notes ===
<ol><li>Be sure to remove vmware-tools if you have it installed (otherwise it will overwrite xorg.conf on reboot)
+
<ol><li>If converting from vmware to libvirt, be sure to remove vmware-tools if you have it installed (otherwise it will overwrite xorg.conf on reboot)
 
</li><li>Guests should not use ntp to synchronize the clock, so be sure to remove/disable ntpd
 
</li><li>Guests should not use ntp to synchronize the clock, so be sure to remove/disable ntpd
 
</li><li>Linux guests with Xorg should be using the 'cirrus' video driver.  To use, adjust /etc/X11/xorg.conf to have: <pre><nowiki>
 
</li><li>Linux guests with Xorg should be using the 'cirrus' video driver.  To use, adjust /etc/X11/xorg.conf to have: <pre><nowiki>
第400行: 第677行:
 
EndSection
 
EndSection
 
</nowiki></pre>
 
</nowiki></pre>
</li><li>Linux guests with Xorg need to adjust the resolution for Xorg in /etc/X11/xorg.conf.  Look for the Screen section, and make sure each of the 'Modes' lines has a reasonable resolution for your system (due to [https://bugs.launchpad.net/ubuntu/+source/libvirt/+bug/193456 bug #193456] the resolution in the guest's resolution needs to be smaller than the host). Eg: <pre><nowiki>
+
</li><li>Linux guests with Xorg need to adjust the resolution for Xorg in /etc/X11/xorg.conf.  Look for the Screen section, and make sure each of the 'Modes' lines has a reasonable resolution for your system (due to [[https://bugs.launchpad.net/ubuntu/+source/libvirt/+bug/193456|bug #193456]] the resolution in the guest's resolution needs to be smaller than the host). Eg: <pre><nowiki>
 
Section "Screen"
 
Section "Screen"
 
         ...
 
         ...
第420行: 第697行:
 
<features/>
 
<features/>
 
</nowiki></pre>
 
</nowiki></pre>
</li><li>Windows Vista virtual machines should add these to the /etc/libvirt/qemu/my-vista.xml file: <pre><nowiki>
+
</li><li>Windows Vista virtual machines should add this to the xml file: <pre><nowiki>
 
<domain type='kvm'>
 
<domain type='kvm'>
 
...
 
...
第436行: 第713行:
 
</nowiki></pre> and run: <pre><nowiki>
 
</nowiki></pre> and run: <pre><nowiki>
 
# update-grub
 
# update-grub
</nowiki></pre></li></ol>
+
</nowiki></pre>
 +
</li><li>OpenBSD 4.1 (and probably others) when using the rtl8139 network driver may realize poor network performance and see this message on the console:<pre><nowiki>
 +
re0: watchdog timeout
 +
</nowiki></pre> The fix is to use another NIC (e1000 appears to work well). See 'Changing the Network Card Model' above.</li></ol>
  
 +
== Removing KVM ==
 +
Removing kvm is pretty easy:<pre><nowiki>
 +
# sudo apt-get remove --purge kvm
 +
</nowiki></pre>
 +
But kvm-intel or kvm module will still be loaded, to remove it completely and stop kvm modules from loading automatically on each boot:<pre><nowiki>
 +
# sudo rm -rf /etc/kvm/ /etc/udev/rules.d/45-kvm.rules /etc/init.d/kvm
 +
</nowiki></pre>
 
----
 
----
 
[[category:CategoryVirtualization]]
 
[[category:CategoryVirtualization]]
  
 
[[category:UbuntuHelp]]
 
[[category:UbuntuHelp]]

2008年10月19日 (日) 12:38的版本

  1. title The Kernel Virtual Machine

目录

Introduction

Preliminary notes

  • This is still work in progress! Feel free to jump in and extend this documentation!
  • The previous version of this page (which was documenting KVM for Feisty) has been moved to KVMFeisty
  • Also checkout the official docs, http://doc.ubuntu.com/ubuntu/serverguide/C/virtualization.html
  • The use case targeted when KVM was moved into main is "Single host server virtualization". This means that even though KVM can be used to serve other purposes, it has been designed to be run on Ubuntu Server Edition to host server operating systems. If you are looking for a desktop virtualization tool, VirtualBox, Parallel workstation or VMware Player/Server can be more suitable alternatives.

Basic info

Ubuntu uses [[1]] as the backend virtualisation technology. To manage VMs we use [[2]] as the basic toolbox and [[3]] as the graphical frontend for managing your vm's.

How to get started

How to check if your CPU supports hardware virtualisation

To run KVM, you need a processor that supports virtualisation; Intel and AMD both have developed extensions for their processors, respectively INTEL-VT and AMD-V. To see if your processor supports one of these, you can run the following command:

egrep '(vmx|svm)' /proc/cpuinfo

If nothing is printed, it means that your CPU doesn't support hardware virtualisation. Otherwise, it does - but you still need to make sure that virtualisation is enabled in the BIOS.

Use a 64 bit kernel if you need more than 2GB RAM for your VMs

To serve more than 2047 MB of RAM for your VMs, you must use a 64 bit kernel (see 32bit_and_64bit). On a 32 bit kernel install, you'll be limited to 2GB RAM at maximum for a given VM. To see if your processor is 64 bit, you can run the following command:

grep ' lm ' /proc/cpuinfo

If nothing is printed, it means that your CPU is not 64 bit. lm stands for Long Mode, so 64 bit CPU. To see if your running kernel is 64 bit, just issue the following command:

uname -m

x86_64 indicates a 64-bit kernel running. If you use see i386, i486, i586 or i686, you're running a 32 bit kernel.

Installation of KVM

For the following setup, we will assume that you are deploying KVM on a server, and therefore do not have any X server on the machine. You need to install a few packages first:

$ sudo apt-get install kvm libvirt-bin ubuntu-vm-builder qemu bridge-utils
  • libvirt-bin provides libvirtd which you need to administer qemu and kvm instances using libvirt
  • kvm is the backend
  • ubuntu-vm-builder powerful command line tool for building virtual machines
  • bridge-utils provides a bridge from your network to the virtual machines

You might also want to install virt-viewer, for viewing instances 8.10 (intrepid) Notes:

  • Two meta packages have been added: ubuntu-virt-server and ubuntu-virt-mgmt. Ubuntu-virt-server installs the packages needed to setup a base virtulization host (kvm, libvirt-bin and openssh-server) and ubuntu-virt-mgmt installs what you need to administer it from a management station (virt-manager, python-vm-builder and virt-viewer).
  • ubuntu-vm-builder has been replaced by python-vm-builder (tutorial).

Adding Users

Add yourself to the libvirtd group (note that there is no need to add yourself to the kvm group):

$ sudo adduser `id -un` libvirtd

This will give you access to the system-wide libvirtd instance. This is preferable for you because it gives you access to the advanced networking options rather than simply the "userspace networking" option as you may know it from QEmu. Note: You need to log out and log back in for the new group membership to take effect. Note: The `id -un` command will return the current username, for example if your username is joe you will be effectively be running sudo adduser joe libvirtd. You can test if your install has been successful with the following command:

$ virsh -c qemu:///system list
 Id Name                 State
----------------------------------

$

If on the other hand you get something like this:

$ virsh -c qemu:///system list
libvir: Remote error : Permission denied
error: failed to connect to the hypervisor
$

Something is wrong and you probably want to fix this before you move on. The critical point here is whether or not you have write access to /var/run/libvirt/libvirt-sock.

Networking

There are a few different ways to allow a virtual machine access to the external network. The default virtual network configuration is usermode networking, which uses the SLIRP protocol and traffic is NATed through the host interface to the outside network. If you do not want to access network services on your virtual machine then you can skip this next step. However to enable external hosts to directly access services on virtual machines a bridge needs to be configured. This allows the virtual interfaces to connect to the outside network through the physical interface, making them appear as normal hosts to the rest of the network. Warning: Network bridging will not work when the physcial network device (eg eth1, ath0) used for bridging is a wireless device (eg ipw3945), as most wireless device drivers do not support bridging! Warning 2: It seems that due to the implementation of CAP_NET_ADMIN in kernel 2.6.18, root access is needed to bring tap interfaces up and down. This means you'll need to run the VM Manager with gksudo (bad) or place a wrapper around the bits that bring up the taps (messy). More info when I figure this one out. (srodden)

Creating a network bridge on the host

We are going to change the network configuration. To do it properly, we should first stop networking<<FootNote(This is needed for example when you move from DHCP to static address: it will stop the DHCP client, which a restart won't do if you changed the configuration already. If you are changing this remotely, then you should prepare your new configuration into a separate file and the use a script to stop networking, put the new configuration in place and start it back.)>>:

invoke-rc.d networking stop

To setup a bridge interface, edit /etc/network/interfaces and either comment or replace the existing config with (replace with the values for your network):

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet static
        address 192.168.0.10
        network 192.168.0.0
        netmask 255.255.255.0
        broadcast 192.168.0.255
        gateway 192.168.0.1
        bridge_ports eth0
        bridge_fd 9
        bridge_hello 2
        bridge_maxage 12
        bridge_stp off

or to use DHCP

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

auto br0
iface br0 inet dhcp
        bridge_ports eth0
        bridge_fd 9
        bridge_hello 2
        bridge_maxage 12
        bridge_stp off

This will create a virtual interface br0. Now restart networking:

sudo /etc/init.d/networking restart

Configuring ubuntu-vm-builder to create bridged guests by default

Virtual machines are defined in XML files; ubuntu-vm-builder, the tool we will use to create VMs, bases them on the template file /usr/share/ubuntu-vm-builder/templates/libvirt.tmpl. Open that file, and change:

    <interface type='network'>
      <mac address='%MAC%'/>
      <source network='default'/>
    </interface>

To:

    <interface type='bridge'>
      <mac address='%MAC%'/>
      <source bridge='br0'/>
    </interface>

Converting an existing guest

If you have already created VMs before, you can make them use bridged networking if you change the XML definition (in /etc/libvirt/qemu/) for the network interface, adjusting the mac address as desired from:

    <interface type='network'>
      <mac address='00:11:22:33:44:55'/>
      <source network='default'/>
    </interface>

to:

    <interface type='bridge'>
      <mac address='00:11:22:33:44:55'/>
      <source bridge='br0'/>
    </interface>

Note: Make sure the first octet in your MAC address is EVEN (eg. 00:) as MAC addresses with ODD first-bytes (eg. 01:) are reserved for multicast communication and can cause confusing problems for you. For instance, the guest will be able to receive ARP packets and reply to them, but the reply will confuse other machines. This is not a KVM issue, but just the way Ethernet works. You do not need to restart libvirtd to reload the changes; the easiest way is to log into virsh (a command line tool to manage VMs), stop the VM, reread its configuration file, and restart the VM:

yhamon@paris:/etc/libvirt/qemu$ ls
mirror.xml  networks  vm2.xml
yhamon@paris:/etc/libvirt/qemu$ virsh --connect qemu:///system
Connecting to uri: qemu:///system
Welcome to virsh, the virtualization interactive terminal.

Type:  'help' for help with commands
       'quit' to quit

virsh # list
 Id Name                 State
----------------------------------
 10 vm2                  running
 15 mirror               running

virsh # shutdown mirror
Domain mirror is being shutdown

virsh # define mirror.xml
Domain mirror defined from mirror.xml

virsh # start mirror
Domain mirror started

The VM "mirror" is now using bridged networking.

DNS and DHCP Guests

libvirt uses dnsmasq to hand out IP addresses to guests which are configured to use dhcp. If on your host machine, you add 192.168.122.1 (the default IP of your host in libvirt) as your first nameserver in /etc/resolv.conf, then you can do name resolution for your guests. dnsmasq is smart enough to use the other 'nameserver' entries in your /etc/resolv.conf for resolving non-libvirt addresses. For example, if your current /etc/resolv.conf is:
search example.com
nameserver 10.0.0.1
Change this to be:
search example.com
nameserver 192.168.122.1
nameserver 10.0.0.1
Now, if you have a virtual machine named 'hardy-amd64', after starting it, you can do:
$ host hardy-amd64
hardy-amd64 has address <IP address given by dnsmasq>
Note that when using ssh you may need to use a trailing '.' after the hostname:
$ ssh hardy-amd64.
Finally, for this to work, your guest must send its hostname as part of the dhcp request. This is done automatically on many operating systems. For systems that do not send this automatically and use dhcp3, you can adjust the dhclient.conf file. For example, on Ubuntu 6.06 LTS (Dapper), adjust /etc/dhcp3/dhclient.conf to have:
send host-name "<your guest hostname here>";

IMPORTANT: Depending on your network configuration, your host's /etc/resolv.conf file might be periodically overwritten. You will have to either adjust the dhcp server on your network to hand out the additional libvirt name server for your libvirt hosts, or adjust each host machine accordingly. As there are many possible configurations for host machines, user's are encouraged to look at resolvconf and/or man interfaces.

Booting Over the Network Using PXE

The current Ubuntu release does not ship pxe binary ROM images because the source code is not included to recreate the images in the upstream tarball. There may be a way to automate the creation of these files as part of the package. In order to use boot -n, you will need to download or create the appropriate ROM images from [[4]] KVM and QEMU can emulate a number of network cards. Here is the current ROM files

'KVM Name' nic,model= 'Etherboot Identification' 'Etherboot Filename' 'KVM filename'
i82551 pxe-i82551.bin
i82557b pxe-i82557b.bin
i82559er pxe-i82559er.bin
ne2k_pci (default) ns8390:rtl8029 -- [10ec,8029] gpxe-0.9.3-rtl8029.rom pxe-ne2k_pci.bin
ne2k_isa pxe-ne2k_isa.bin
pcnet pxe-pcnet.bin
rtl8139 pxe-rtl8139.bin
e1000 ((e1000:e1000-0x1026 -- [8086,1026])) gpxe-0.9.3-e1000-0x1026.rom pxe-e1000.bin
smc91c111 pxe-smc91c111.bin
lance pxe-lance.bin
mcf_fec pxe-mcf_fec.bin

Copy the respective file to /usr/share/kvm and/or /usr/share/qemu.

Creating virtual machines

Now that KVM is installed, let s see how we install our first VM. There is a tool to manage VMs on a remote host: virt-manager. Sadly, VM creation on a remote host is not supported yet through virt-manager - therefore you will have to create the VM in command line. There are two different tools to do this; virt-install, a python script developed by Red Hat, and ubuntu-vm-builder, developed by Canonical.

Ubuntu-vm-builder: the fast & powerful way to create Ubuntu JEOS VMs

[[5]] is probably the best tool to use if you want to create VMs running Ubuntu JEOS 8.04, as the install is entirely scripted (very fast). This tool is packaged, and in universe:

sudo apt-get install ubuntu-vm-builder

Basic use

Here is a very basic example of how to use it:

sudo ubuntu-vm-builder kvm hardy

This will create an Ubuntu Hardy, with all options set to default. Or you can use this URL to a Javascript tool that generates the lengthy set of parameters available for ubuntu-vm-builder:

Note: if you want to use Virsh to manage your virtual machines as detailed below, you must add

--libvirt qemu:///system

to the list of arguments that the javascript produces. The javascript does not have an option for this itself, unfortunately.

More complex example

Now here is a somewhat more complex example:

ubuntu-vm-builder kvm hardy \
                  --domain newvm \
                  --dest newvm \
                  --arch i386 \
                  --hostname hostnameformyvm \
                  --mem 256 \
                  --user john \
                  --pass doe \
                  --ip 192.168.0.12 \
                  --mask 255.255.255.0 \
                  --net 192.168.0.0 \
                  --bcast 192.168.0.255 \
                  --gw 192.168.0.1 \
                  --dns 192.168.0.1 \
                  --mirror http://archive.localubuntumirror.net/ubuntu \
                  --components main,universe \
                  --addpkg vim openssh-server \
                  --libvirt qemu:///system ;

This will create a new Ubuntu Hardy VM called "newvm", the hostname will be set to "hostnameformyvm", the network will be configured with a static IP address and a gateway at address 192.168.0.1. The --mirror will tell the script to download the packages from a local Ubuntu mirror instead of the default server (this may speed up by a lot the time necessary to create the VM). The components argument will enable main and universe by default on the VM, --addpkg vim will install vim, and finally the last argument will automatically add the newly created VM to KVM. By adding 'openssh-server' with --addpkg, we will be able to ssh into our new machine once its started (provided the networking works correctly). Note: The manual isn't specific about the --exec option, used to execute a script file during the vm build process. If you specify the --exec option then you must provide the full path to the script you are executing. Not doing so will cause the installer to tell you that it can't find the script file. Bug notice: it seems that the package 'linux-package' is not found during the machine building process unless 'restricted' is also specified as a component option to ubuntu-vm-builder. If not specified, you'll get a non-functioning system that boots into grub only. This line makes it work for me:

--components 'main,universe,restricted'

I'm assuming this is a bug in ubuntu-vm-builder.

Install on a raw block device

Ubuntu-vm-builder doesn't allow you to create the VM on a raw block device yet (like a standalone partition, or a iSCSI share). You can use ubuntu-vm-builder to create the qcow2 image and then move the VM to the block device with qemu-img though; if /dev/sdb is the disk device on which you want to move the virtual machine:

sudo qemu-img convert root.qcow2 -O raw /dev/sdb

Edit the XML definition file for the VM in /etc/libvirt/qemu/, and set the source file to be:

<source file='/dev/sdb'/>

Redefine the VM and start it; it is now running from /dev/sdb. Ubuntu-vm-builder is a very powerful tool - to get a more detailed list of its capabilities, use ubuntu-vm-builder --help.

Use virtio for Ubuntu Hardy guests

You may find the performances of the network relatively poor (approx. 100/120mbits on my servers, which are quite fast). If you are running Ubuntu Hardy, you can enable virtio. Go to the definition file of your VM, and add the virtio line to the definition of your network interface:

    <interface type='bridge'>
      <mac address='52:54:00:a0:41:92'/>
      <source bridge='br0'/>
      <model type='virtio'/>   <-- add this line, leave the rest
    </interface>

This improves the network performances by a lot (factor 10, nearly). But this works only with ubuntu hardy guests for the moment, which is why it is not by default.

Create VMs running other operating systems: virt-install

Virt-install is radically different in the way it works. Instead of creating automagically a new VM, it will allow you to boot on an iso, and therefore to install almost any operating system. For a list of supported operating system, consult [official webpage].

Example Windows install

模板:Http://waste.mandragor.org/windows-kvm.png Copy the ISO of the system you want to install to your working directory:

yhamon@paris:~$ ls *.iso
ubuntu-8.04-server-i386.iso  windowsxpsp2.iso

or create an ISO from a cd/dvd:

dd if=/dev/dvd of=dvd.iso

Install virt-install:

sudo apt-get install python-virtinst

Then, run virt-install (the install of windows XP doesn't work when accelerated with --accelerate, so run the install and then replace qemu by kvm in the XML file once installed):

sudo virt-install --connect qemu:///system -n xpsp2 -r 512 -f windows.qcow2 -s 12 -c windowsxpsp2.iso --vnc --noautoconsole --os-type windows --os-variant winxp

This will boot a new VM from the ISO. Connect to the new VM using virt-viewer:

virt-viewer -c qemu:///system xpsp2

Or if KVM is running on a different server:

virt-viewer -c qemu+ssh://ip/system xpsp2

You should now have a graphical interface to install your VM!

Example Ubuntu install

You can perform the following to install Ubuntu Hardy:
sudo virt-install --connect qemu:///system -n hardy -r 512 -f hardy.qcow2 -s 12 -c hardy-server-amd64.iso --vnc --noautoconsole --os-type linux --os-variant ubuntuHardy --accelerate --network=network:default
The '--network' option sets up the machine to use the default libvirt network. You can see available libvirt networks with:
virsh net-list --all

Other Operating Systems

Other Operating Systems can be installed using the same method as above. See 'man virt-install' for more information on different options for your virtual machine and supported OS types and OS variants. Warning: this method fails with Fedora LiveCD installations and possibly others; see the bug here: https://bugs.launchpad.net/ubuntu/+source/kvm/+bug/220463

Cloning a virtual machine

You can clone an existing virtual machine using the virt-clone tool. This duplicates the disk image and sets up the virtual machine domain configuration. If you wish to clone a virtual machine named srchost to a new machine newhost, ensure that the virtual machine srchost is not running and execute the following command.

$ virt-clone --connect=qemu:///system -o srchost -n newhost -f /path/to/newhost.qcow2

Manage your virtual machines

From the shell

You can manage your VMs from the shell using [[6]]. You can get a list of the available commands if you type "help". Type "help command" to get additional infos for a particular command.

Define your new VM

Before you can manage your new VM with virsh, you must define it:

$ virsh --connect qemu:///system
Connecting to uri: qemu:///system
Welcome to virsh, the virtualization interactive terminal.

Type:  'help' for help with commands
       'quit' to quit

virsh # define /etc/libvirt/qemu/newvm.xml
Domain newvm defined from /etc/libvirt/qemu/newvm.xml

Note that to list newvm, you must use 'list --inactive' or 'list --all', since list without any options will only list currently running machines.

List your VMs

Virsh allows you to list the virtual machines available on the current host:

yhamon@paris:/etc/libvirt/qemu$ virsh --connect qemu:///system
Connecting to uri: qemu:///system
Welcome to virsh, the virtualization interactive terminal.

Type:  'help' for help with commands
       'quit' to quit

virsh # help list
  NAME
    list - list domains

  SYNOPSIS
    list [--inactive | --all]

  DESCRIPTION
    Returns list of domains.

  OPTIONS
    --inactive       list inactive domains
    --all            list inactive & active domains

virsh # list
 Id Name                 State
----------------------------------
 15 mirror               running
 16 vm2                  running

virsh # list --all
 Id Name                 State
----------------------------------
 15 mirror               running
 16 vm2                  running
  - test5                shut off

Define, undefine, start, shutdown, destroy VMs

The VMs you see with list --all are VMs that have been "defined" from an XML file. Every VM is configured via a XML file in /etc/libvirt/qemu. If you want to remove a VM from the list of VMs, you need to undefine it:

virsh # undefine test5   # WARNING: undefine will delete your XML file!
Domain test5 has been undefined

virsh # list --all
 Id Name                 State
----------------------------------
 15 mirror               running
 16 vm2                  running

To be able to undefine a virtual machine, it needs to be shutdown first:

virsh # shutdown mirror
Domain mirror is being shutdown

This command asks for a nice shutdown (like running shutdown in command line) - but you can also use "destroy", the more brutal way of shutting down a VM, equivalent of taking the power cable off:

virsh # destroy mirror
Domain mirror destroyed

If you have made a change to the XML configuration file, you need to tell KVM to reload it before restarting the VM:

virsh # define /etc/libvirt/qemu/mirror.xml
Domain mirror defined from /etc/libvirt/qemu/mirror.xml

Then, to restart the VM:

virsh # start mirror
Domain mirror started

Suspend and resume a Virtual Machine

Virsh allows you to easily suspend and resume a virtual machine.

virsh # suspend mirror
Domain mirror suspended

virsh # resume mirror
Domain mirror resumed

Using a graphical interface

There is also an easier way to manage your virtual machines. The tool virt-manager allows you to use a graphical interface to interact with KVM. Install virt-manager on your desktop:

sudo apt-get install virt-manager virt-viewer

And use it to connect to your server:

$ virt-manager -c qemu+ssh://10.10.10.10/system

10.10.10.10 being the IP address of your host running KVM. 模板:Http://waste.mandragor.org/virt-manager-screenshot.png If you are only managing machines on your own host you can use only:

$ virt-manager -c qemu:///system

Editing the attributes of a Virtual Machine

libvirt stores it's configuration as xml in '/etc/libvirt/qemu'. The xml is easy to understand, and is similar to VMware *.vmx files. While it is possible to edit these files in place and restart libvirt-bin for the changes to take affect, the recommended method for modifying the attributes of a virtual machine is via virsh (or virt-manager, if it supports changing the hardware you want to change). The concept is simple:

  1. export (aka 'dump') the xml of the virtual machine you want to edit
  2. edit the xml
  3. import (aka 'define') the xml
For example, to edit the machine named 'foo' (you can get a list of your machines with 'virsh list --all'), do:
$ virsh dumpxml foo > /tmp/foo.xml
(edit /tmp/foo.xml as needed)
$ virsh define /tmp/foo.xml

Adding CPUs

KVM allows you to create SMP guests. To allocate two CPUs to a VM, dump the xml as above, then edit your xml to have:
<domain type='kvm'>
  ...
  <vcpu>2</vcpu>
  ...
</domain>

Now define the VM as above.

Adding Memory

To change the memory allocation in a VM, dump the xml as above, then edit your xml to have:
<domain type='kvm'>
  ...
  <memory>262144</memory>
  <currentMemory>262144</currentMemory>
  ...
</domain>

Now define the VM as above. Keep in mind that the memory allocation is in kilobytes, so to allocate 512MB of memory, use 512 * 1024, or 524288.

Changing the Network Card Model

kvm and qemu currently default to using the rtl8139 NIC. Supported NICs in Ubuntu 8.04 LTS are i82551, i82557b, i82559er, ne2k_pci, pcnet, rtl8139, e1000, and virtio. To use an alternate NIC, dump the xml as above, then edit your xml to have:
<domain type='kvm'>
  ...
    <interface type='network'>
      ...
      <model type='e1000'/>
    </interface>
  ...
</domain>

Now define the VM as above.

Get new IDs

To get a new mac address to paste into your xml file, use this command: MACADDR="52:54:$(dd if=/dev/urandom count=1 2>/dev/null | md5sum | sed 's/^\(..\)\(..\)\(..\)\(..\).*$/\1:\2:\3:\4/')"; echo $MACADDR To get a new uuid for your xml file, use: uuidgen

KVM from the command line

KVM is very similar to qemu and it is possible to run machines from the command line. The basic syntax is :

kvm -m 512 -hda disk.img -cdrom ubuntu.iso -boot d -smp 2
  • -m = memory (in MB)
  • -hda = first hard drive
  • You can use a number of image file types including .img, .cow
  • You can also boot a hard drive. Be careful with this option as you do not want to boot the host root partition
  • Syntax -hda /dev/sda
  • This will call your grub menu from your MBR when you boot kvm.
  • -cdrom can be an iso image or a CD/DVD drive.
  • -boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)
  • -smp = number of CPU
  • -alt-grab change Ctrl-Alt mouse grab combination for Ctrl-Alt-Shift (very practical if you often use some control key combinations like Ctrl-Alt-Del or Windows-E)

There are a number of additional options and additional help is available with :

kvm --help

Bridged Networking

In order to run KVM using bridged networking as a user we need to perform some configuration. 1. First bridge your network card as above | Creating a network bridge on the host 2. Install uml-utilities

 sudo apt-get install uml-utilities
 

3. Set permissions on your tun device. Using any editor, edit /etc/udev/rules.d/40-permissions.rules, add this line at the bottom of the file :

 KERNEL=="tun", GROUP="kvm", MODE="0660"
 

4. Reboot (to bring up your bridge and tun device). 5. Edit /etc/kvm/kvm-ifup adding sudo in front of the ifconfig and brctl commands

 #!/bin/sh

 switch=$(ip route ls | awk '/^default / { for(i=0;i<NF;i++) { if ($(i) == "dev") print $(i+1) }}')
 '''sudo''' /sbin/ifconfig $1 0.0.0.0 up
 '''sudo''' /usr/sbin/brctl addif ${switch} $1
 exit 0
 

6. We need a wrapper script for launching kvm. I put this script in ~/bin and call it kvm-bridge. If ~/bin is on your path you can call the command directly with kvm-bridge. This script was modified from a number of sources

 #!/usr/bin/env bash
 # script to manage tap interface allocation
 # for linux kernels >= 2.6.18

 # modified by bodhi.zazen from :
 # http://calamari.reverse-dns.net:980/cgi-bin/moin.cgi/FrequentlyAskedQuestions#head-2511814cb92c14dbe1480089c04f83c281117a86
 # http://ubuntuforums.org/showthread.php?t=528046
 # http://www.howtoforge.com/using-kvm-on-ubuntu-gutsy-gibbon

 # set up a tap interface for qemu
 # USERID - uid qemu is being run under.
 USERID=`whoami`

 # generate a random mac address for the qemu nic
 # shell script borrowed from user pheldens @ qemu forum

 ranmac=$(echo -n DE:AD:BE:EF ; for i in `seq 1 2` ; \
 do echo -n `echo ":$RANDOM$RANDOM" | cut -n -c -3` ;done)

 # specify which NIC to use - see qemu.org for others
 # model=r8169
 # Set model based on this how-to
 # http://www.howtoforge.com/using-kvm-on-ubuntu-gutsy-gibbon

 model=rtl8139
 iface=`sudo tunctl -b -u $USERID`

 # start kvm with our parameters
 # echo "Bringing up interface $iface with mac address $ranmac"
 # nohup added to allow kvm to run independent of the terminal
 nohup kvm -net nic,vlan=0,macaddr=$ranmac -net tap,vlan=0,ifname=$iface $@

 # kvm has stopped - no longer using tap interface
 sudo tunctl -d $iface &> /dev/null
 

7. Set the executable bit on the new script you just created:

 chmod 0755 ~/bin/kvm-bridge
 

8. Modify sudoers to allow members of the kvm group to run the wrapper kvm-bridge and create a bridged network interface without running KVM as root.

 visudo
 

Add these line at the end of the file :

 # Allow members of the kvm group to configure a bridged virtual network interface
 %kvm ALL=(ALL) NOPASSWD: /sbin/ifconfig, /usr/sbin/brctl, /usr/sbin/tunctl
 

9. Now start kvm from the command line. You do not need to declare a network interface

 kvm-bridge -m 512 -hda disk.img -cdrom ubuntu.iso -boot -d -smp 2
 

iptables

Add these rules to iptables :

# allow incoming packets for kvm guest
IPTABLES -A FORWARD -d $IPADDR_FROM_GUEST_OS -j ACCEPT
# allow outgoing packets from kvm
IPTABLES -A FORWARD -s $IPADDR_FROM_GUEST_OS -j ACCEPT

Change "$IPADDR_FROM_GUEST_OS" to the actual ip address of the kvm guest (I advise you configure your guests to have a static IP address). If you use ufw, add these rules to /etc/ufw/before.rules

Troubleshooting/FAQ

Virtualbox and KVM

Installing kvm loads the module kvm (or kvm-intel in my case) which does not allow other virtualization software to run, e.g. virtualbox. See Removal|section to set this straight :)

How to boot Dapper, Edgy, Feisty or Gutsy ISO

  • Q: I'm on Intel hardware, and I'm trying to boot Dapper, Edgy, Feisty, or Gutsy, but kvm fails immediately.
  • A: Yes, this is rather unfortunate. The issue is a limitation in Intel's virtualisation extensions that don't interact very well with gfxboot. The evil, hacky workaround is to modify the ISO to disable gfxboot. The following has worked for me, but it might kill your cat or make your coffee go cold or make other unpleasantries happen to you. You've been warned!
$ sed -e 's/GFXBOOT bootlogo/#FXBOOT bootlogo/g' < ubuntu-7.10-server-amd64.iso > ubuntu-7.10-server-amd64-nogfxboot.iso

/!\ Don't change the above command! The length of the string mustn't change or you will have knackered the filesystem on the CD. A slightly safer way is to download gfxboot-disable from [[7]] and then run:

$ gfxboot-disable ubuntu-7.10-server-amd64.iso

Boot a VM into single mode

A VM has a complete BIOS, and also runs GRUB. Bad point is, it disappears after a couple of seconds, most of the time you won't even have time to connect using virt-viewer. There is a small trick here: shutdown the VM, run virt-viewer with the argument --wait (that way it will wait for the VM to start and pop up directly after that), and then start the VM; this should give you a good 2 seconds time to enter the bios or access grub. If you are running a VM built with ubuntu-vm-builder, there is a small bug that will prevent you from logging in; in grub, select the recovery line and press "e"; select the line beginning with kernel, press "e" again. At the end of the line, add "init=/bin/sh" (without the quotes). Confirm with enter, and press b to boot the kernel with these settings.

How to convert VMware machines to virt-manager

kvm has the ability to use VMware's vmdk disk files directly, as long as the disk is wholly contained in the vmdk (ie VMware allows splitting a disk into smaller, usually 2GB, vmdk files. kvm can't use these). Point kvm at the vmdk with the appropriate options (see man kvm-qemu ), and it should work. To use the VMware machine from within virt-manager, the .vmx file must be converted to libvirt's .xml. vmware2libvirt was created to help with this, and it can be used like so:

$ vmware2libvirt -f ./file.vmx > file.xml
$ virsh -c qemu:///system define file.xml

The first command converts the VMware 'file.vmx' file to the libvirt compatible 'file.xml'. See man vmware2libvirt for details. Note: until vmware2libvirt is shipped with the libvirt packages, you can download it from [[8]]. The second command imports file.xml into libvirt. The imported .xml files are stored in /etc/libvirt/qemu. IMPORTANT: keep in mind that while the .vmx file is converted to .xml, the disks are used as is. Please make backups, especially if you want to use the virtual machine in VMware later.

Caveats

While vmware2libvirt works well on simple virtual machines, there are limitations because .vmx files don't always contain enough information, and also because vmware2libvirt tries not to make too many assumptions about what it finds. A couple of things to look out for:

  1. While vmware2libvirt attempts to detect a 64-bit guest, be sure that your 64-bit guest has in its .xml file:
    <os>
     <type arch='x86_64' machine='pc'>hvm</type>
     ...
    </os>
    
  2. vmware2libvirt only detects and uses the first ethernet interface found. Additional interfaces can be added from within virt-manager.
  3. Currently the first scsi disk is used if found, otherwise the first ide disk. Additional disks can be added from within virt-manager.
  4. The converted virtual machine is hard-coded to use 1 cpu. This can be changed with:
    <vcpu>2</vcpu>
    
  5. vmware2libvirt does not (and cannot) convert anything that was VMware-specific within the guest. See 'Guest Notes' below for more details.

Guest notes

  1. If converting from vmware to libvirt, be sure to remove vmware-tools if you have it installed (otherwise it will overwrite xorg.conf on reboot)
  2. Guests should not use ntp to synchronize the clock, so be sure to remove/disable ntpd
  3. Linux guests with Xorg should be using the 'cirrus' video driver. To use, adjust /etc/X11/xorg.conf to have:
    Section "Device"
            Identifier      "Configured Video Device"
            Driver          "cirrus"
    EndSection
    
    then be sure that your Screen section uses 'Configured Video Device' for its Device.
  4. Linux guests with Xorg should be using the 'vmmouse' driver (not available on Ubuntu Dapper). To use, perform within the guest:
    aptitude install xserver-xorg-input-vmmouse
    
    then adjust /etc/X11/xorg.conf to have (the Identifier line should not change, and you should have only an Identifier line and Driver line for the mouse):

    Section "InputDevice"

           Identifier      "Configured Mouse"
           Driver          "vmmouse"
    

    EndSection

  5. Linux guests with Xorg need to adjust the resolution for Xorg in /etc/X11/xorg.conf. Look for the Screen section, and make sure each of the 'Modes' lines has a reasonable resolution for your system (due to [#193456] the resolution in the guest's resolution needs to be smaller than the host). Eg:
    Section "Screen"
            ...
            SubSection "Display"
                    Depth           16
                    Modes           "800x600" "640x480"
            EndSubSection
            SubSection "Display"
                    Depth           24
                    Modes           "800x600" "640x480"
            EndSubSection
    EndSection
    
  6. Windows (other than Vista) virtual machines should substitute in the .xml file:
    <features>
      <acpi/>
    </features>
    
    with:

    <features/>

  7. Windows Vista virtual machines should add this to the xml file:
    <domain type='kvm'>
    ...
      <features>
        <acpi/>
      </features>
    </domain>
    
  8. Debian Sarge (oldstable) may write /boot/grub/menu.lst incorrectly, resulting in the following on boot:
    pivot_root: no such file or directory
    /sbin/init: 432: cannot open dev/console: no such file
    Kernel panic: Attempted to kill init!
    
    The fix is at the grub menu, press 'e' and adjust root=/dev/hdb1 to be root=/dev/hda1. After a successful boot, you will need to update /boot/grub/menu.lst to have:
    1. kopt=root=/dev/hda1 ro
    and run:
    1. update-grub
  9. OpenBSD 4.1 (and probably others) when using the rtl8139 network driver may realize poor network performance and see this message on the console:
    re0: watchdog timeout
    
    The fix is to use another NIC (e1000 appears to work well). See 'Changing the Network Card Model' above.

Removing KVM

Removing kvm is pretty easy:
# sudo apt-get remove --purge kvm
But kvm-intel or kvm module will still be loaded, to remove it completely and stop kvm modules from loading automatically on each boot:
# sudo rm -rf /etc/kvm/ /etc/udev/rules.d/45-kvm.rules /etc/init.d/kvm