KVM virtualization using command line on Ubuntu 15.10
KVM virtualization using command line on Ubuntu 15.10

Recently, I have tested the KVM hypervisor on a server running Ubuntu 15.10. The challenge, for me, was to install, configure and use the KVM host and guest only with the command line.

First check, your server have to support hardware virtualization extensions:
$ egrep ‘(vmx|svm)’ –color /proc/cpuinfo

vmx

Next step, install KVM:
$ sudo apt-get install qemu-kvm libvirt-bin uuid python-guestfs libguestfs-tools

I have removed the default virtual network and create my own following these steps:

generate an uuid for the new network

$ uuid
86aeb5d6-df81-11e5-8229-4c72b9d2cfea

 

create the xml file mybr.xml

<network>
  <name>mybr</name>
  <uuid>86aeb5d6-df81-11e5-8229-4c72b9d2cfea</uuid>
  <forward mode="nat" />
  <ip address="10.0.0.1" netmask="255.255.255.0" />
  <bridge name='mybr'/>
</network>

 

delete the default network and create the mybr network

$ virsh
virsh # net-destroy default
virsh # net-undefine default
virsh # net-define mybr.xml
virsh # net-autostart mybr
virsh # net-start mybr

 

I have found a useful python script to generate virtual machine easily: ubuntu-vm-builder
You can launch it as follow to create your first guest vm:

ubuntu-vm-builder kvm trusty \
        --destdir /opt/kvm/testvm \
        --user user --name user --pass password \
        --addpkg acpid --addpkg openssh-server --addpkg linux-image-generic \
        --mirror http://gb.archive.ubuntu.com/ubuntu/ --components main,universe,restricted \
        --arch amd64 --hostname testvm \
        --ip 10.0.0.10 \
        --mask 255.255.255.0 \
        --net 10.0.0.0 \
        --bcast 10.0.0.255 \
        --gw 10.0.0.1 \
        --dns 10.0.0.1 \
        --libvirt qemu:///system \
        --mem 1024 --cpus 1 ;

 

For me, I don’t know why yet, the script fails with the following error :

2016-02-28 22:55:43,460 ERROR   : Process (['mkfs.ext4', '-F', '/dev/mapper/loop0p1']) returned 1. stdout: , stderr: mke2fs 1.42.12 (29-Aug-2014)
The file /dev/mapper/loop0p1 does not exist and no size was specified.

Traceback (most recent call last):
  File "/usr/bin/ubuntu-vm-builder", line 24, in <module>
    uvb.main()
  File "/usr/lib/python2.7/dist-packages/VMBuilder/contrib/cli.py", line 228, in main
    hypervisor.install_os()
  File "/usr/lib/python2.7/dist-packages/VMBuilder/hypervisor.py", line 65, in install_os
    self.call_hooks('mount_partitions', self.chroot_dir)
  File "/usr/lib/python2.7/dist-packages/VMBuilder/distro.py", line 67, in call_hooks
    call_hooks(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/VMBuilder/util.py", line 170, in call_hooks
    getattr(context, func)(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/VMBuilder/hypervisor.py", line 91, in mount_partitions
    disk.mkfs()
  File "/usr/lib/python2.7/dist-packages/VMBuilder/disk.py", line 152, in mkfs
    part.mkfs()
  File "/usr/lib/python2.7/dist-packages/VMBuilder/disk.py", line 307, in mkfs
    self.fs.mkfs()
  File "/usr/lib/python2.7/dist-packages/VMBuilder/disk.py", line 375, in mkfs
    run_cmd(*cmd)
  File "/usr/lib/python2.7/dist-packages/VMBuilder/util.py", line 120, in run_cmd
    raise VMBuilderException, "Process (%s) returned %d. stdout: %s, stderr: %s" % (args.__repr__(), status, mystdout.buf, mystderr.buf)
VMBuilder.exception.VMBuilderException: Process (['mkfs.ext4', '-F', '/dev/mapper/loop0p1']) returned 1. stdout: , stderr: mke2fs 1.42.12 (29-Aug-2014)
The file /dev/mapper/loop0p1 does not exist and no size was specified.

 

I have found a solution: add this line at the end of the function map_partitions of the script file /usr/lib/python2.7/dist-packages/VMBuilder/disk.py

run_cmd('udevadm', 'settle')

 

When the script ends, your virtual machine is almost ready. Check the vm is shut off:

$ virsh
virsh # shutdown testvm
virsh # list --all
 Id    Name                           State
----------------------------------------------------
 -     testvm		              shut off

virsh # quit

 

To get access to the vm console, some other steps are required. We have to edit the vm disk file using guestfish:

$ guestfish
><fs> add /opt/kvm/testvm/tmpGRTbnK.qcow2
><fs> run
><fs> list-filesystems
/dev/sda1: ext4
/dev/sda2: swap
><fs> mount /dev/sda1 /
><fs> write /etc/init/ttyS0.conf "start on stopped rc RUNLEVEL=[2345] \nstop on runlevel [!2345] \nrespawn \nexec /sbin/getty -L 38400 ttyS0 vt102"
><fs> vi /boot/grub/menu.lst

 

I have updated the line 135 as follow:
kernel /boot/vmlinuz-3.13.0-79-generic root=UUID=ef1fb3c8-1765-46ee-ad03-643789032648 ro quiet splash console=ttyS0,115200

><fs> umount /dev/sda1
><fs> quit

 

Now you can edit the vm configuration:

<domain type='kvm'>
  <name>testvm</name>
  <uuid>df8c8524-4568-4a97-9632-a9512fdcab55</uuid>
  <memory unit='KiB'>1048576</memory>
  <currentMemory unit='KiB'>1048576</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-vivid'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/opt/kvm/testvm/tmpGRTbnK.qcow2'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <interface type='network'>
      <mac address='52:54:00:cd:24:a9'/>

vvvvvvvvvv UPDATE THIS LINE vvvvvvvvvvv
      <source network='mybr'/>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>

vvvvvvvvvv ADD THESE LINES vvvvvvvvvvv
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>

vvvvvvvvvv REMOVE THESE LINES vvvvvvvvvvv
    <graphics type='vnc' port='-1' autoport='yes' listen='127.0.0.1' passwd='password'>
      <listen type='address' address='127.0.0.1'/>
    </graphics>
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    <video>
      <model type='cirrus' vram='16384' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </memballoon>
  </devices>
</domain>

 

After editing, the xml file will look like this:

<domain type='kvm'>
  <name>testvm</name>
  <uuid>df8c8524-4568-4a97-9632-a9512fdcab55</uuid>
  <memory unit='KiB'>1048576</memory>
  <currentMemory unit='KiB'>1048576</currentMemory>
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-vivid'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
  </features>
  <clock offset='utc'/>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <devices>
    <emulator>/usr/bin/kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/opt/kvm/testvm/tmpGRTbnK.qcow2'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <interface type='network'>
      <mac address='52:54:00:cd:24:a9'/>
      <source network='mybr'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target port='0'/>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <video>
      <model type='cirrus' vram='16384' heads='1'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </memballoon>
  </devices>
</domain>

 

You can now start your vm and check you can login:

$ virsh start testvm --console
Domain testvm started
Connected to domain testvm 
Escape character is ^]
 * Starting Mount filesystems on boot                                    [ OK ]
 * Starting Populate and link to /run filesystem                         [ OK ]
 * Stopping Populate and link to /run filesystem                         [ OK ]
 * Starting Initialize or finalize resolvconf                            [ OK ]
 * Starting Signal sysvinit that the rootfs is mounted                   [ OK ]
 * Stopping Track if upstart is running in a container                   [ OK ]
 * Starting set console keymap                                           [ OK ]
 * Starting Signal sysvinit that virtual filesystems are mounted         [ OK ]
 * Starting Signal sysvinit that virtual filesystems are mounted         [ OK ]
 * Starting Bridge udev events into upstart                              [ OK ]
 * Starting device node and kernel event manager                         [ OK ]
 * Starting Signal sysvinit that remote filesystems are mounted          [ OK ]
 * Starting cold plug devices                                            [ OK ]
 * Starting log initial device creation                                  [ OK ]
 * Stopping Mount filesystems on boot                                    [ OK ]
 * Starting Signal sysvinit that local filesystems are mounted           [ OK ]
 * Starting flush early job output to logs                               [ OK ]
 * Stopping set console keymap                                           [ OK ]
 * Stopping flush early job output to logs                               [ OK ]
 * Starting system logging daemon                                        [ OK ]
 * Starting configure network device security                            [ OK ]
 * Starting Bridge file events into upstart                              [ OK ]
 * Starting Mount network filesystems                                    [ OK ]
 * Stopping Mount network filesystems                                    [ OK ]
 * Starting configure network device                                     [ OK ]
 * Starting configure network device security                            [ OK ]
 * Starting Mount network filesystems                                    [ OK ]
 * Starting Failsafe Boot Delay                                          [ OK ]
 * Stopping Mount network filesystems                                    [ OK ]
 * Stopping Failsafe Boot Delay                                          [ OK ]
 * Starting System V initialisation compatibility                        [ OK ]
 * Stopping cold plug devices                                            [ OK ]
 * Starting configure network device                                     [ OK ]
 * Stopping log initial device creation                                  [ OK ]
 * Stopping System V initialisation compatibility                        [ OK ]
 * Starting configure network device security                            [ OK ]
 * Starting System V runlevel compatibility                              [ OK ]
 * Starting Extensible, configurable radius daemon                       [ OK ]
 * Starting ACPI daemon                                                  [ OK ]
 * Starting save kernel messages                                         [ OK ]
 * Starting userspace bootsplash                                         [ OK ]
 * Starting OpenSSH server                                               [ OK ]
 * Starting regular background program processing daemon                 [ OK ]
 * Stopping save kernel messages                                         [ OK ]
 * Starting Send an event to indicate plymouth is up                     [ OK ]
 * Starting configure virtual network devices                            [ OK ]
 * Stopping userspace bootsplash                                         [ OK ]
 * Stopping Send an event to indicate plymouth is up                     [ OK ]
 * Starting Bridge socket events into upstart                            [ OK ]
 * Starting FreeRADIUS daemon freeradius                                 [ OK ] 
 * Stopping System V runlevel compatibility                              [ OK ]

Ubuntu 14.04.4 LTS testvm ttyS0

testvm login:

 

Update your iptables rules to allow ssh from the host to the guest:

iptables -I INPUT -i mybr -s 10.0.0.10 -d 10.0.0.1 -p tcp --sport 22 -j ACCEPT
iptables -I OUTPUT -o mybr -s 10.0.0.1 -d 10.0.0.10/32 -p tcp --dport 22 -j ACCEPT

 

Do not hesitate to contact me or leave a comment if you have a problem or a step is missing on this procedure.

<>

My Powershell script categories

KVM virtualization using command line on Ubuntu 15.10

Leave a Reply

Your email address will not be published.