设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1349|回复: 2

Virtualization With KVM On Ubuntu 12.04 LTS

[复制链接]
发表于 2014-3-23 20:29:25 | 显示全部楼层 |阅读模式
本帖最后由 John 于 2014-3-24 12:45 编辑

This guide explains how you can install and use KVM for creating and running virtual machines on an Ubuntu 12.04 LTS server. I will show how to create image-based virtual machines and also virtual machines that use a logical volume (LVM). KVM is short for Kernel-based Virtual Machine and makes use of hardware virtualization, i.e., you need a CPU that supports hardware virtualization, e.g. Intel VT or AMD-V.
I do not issue any guarantee that this will work for you!

1 Preliminary Note
I'm using a machine with the hostname server1.example.com and the IP address 192.168.0.100 here as my KVM host.
Because we will run all the steps from this tutorial with root privileges, we can either prepend all commands in this tutorial with the string sudo, or we become root right now by typing
sudo su

2 Installing KVM And vmbuilder
First check if your CPU supports hardware virtualization - if this is the case, the command
egrep '(vmx|svm)' --color=always /proc/cpuinfo
should display something, e.g. like this:
root@server1:~# egrep '(vmx|svm)' --color=always /proc/cpuinfo
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush
mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl extd_apicid
pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch lbrv
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush
mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt rdtscp lm 3dnowext 3dnow rep_good nopl extd_apicid
pni cx16 lahf_lm cmp_legacy svm extapic cr8_legacy 3dnowprefetch lbrv
root@server1:~#
If nothing is displayed, then your processor doesn't support hardware virtualization, and you must stop here.
To install KVM and vmbuilder (a script to create Ubuntu-based virtual machines), we run
apt-get install ubuntu-virt-server python-vm-builder kvm-ipxe
Afterwards we must add the user as which we're currently logged in (root) to the group libvirtd:
adduser `id -un` libvirtd
adduser `id -un` kvm
You need to log out and log back in for the new group memberships to take effect.
To check if KVM has successfully been installed, run
virsh -c qemu:///system list
It should display something like this:
root@server1:~# virsh -c qemu:///system list
Id Name                 State
----------------------------------

root@server1:~#
If it displays an error instead, then something went wrong.
Next we need to set up a network bridge on our server so that our virtual machines can be accessed from other hosts as if they were physical systems in the network.
To do this, we install the package bridge-utils...
apt-get install bridge-utils
... and configure a bridge. Open /etc/network/interfaces:
vi /etc/network/interfaces
Before the modification, my file looks as follows:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet static
        address 192.168.0.100
        netmask 255.255.255.0255.255.255.0255.255.255.0
        network 192.168.0.0
        broadcast 192.168.0.255
        gateway 192.168.0.1
        dns-nameservers 8.8.8.8 8.8.4.4
I change it so that it looks like this:  
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback
# The primary network interface
auto eth0
iface eth0 inet manual
auto br0
iface br0 inet static
        address 192.168.0.100
        network 192.168.0.0
        netmask 255.255.255.0255.255.255.0255.255.2
        broadcast 192.168.0.255
        gateway 192.168.0.1
        dns-nameservers 8.8.8.8 8.8.4.4
        bridge_ports eth0
        bridge_fd 9
        bridge_hello 2
        bridge_maxage 12
        bridge_stp off
(Make sure you use the correct settings for your network!)
Restart the network...
  1. /etc/init.d/networking restart
复制代码

... and run
  1. ifconfig
复制代码

It should now show the network bridge (br0):
root@server1:~# ifconfig
br0       Link encap:Ethernet  HWaddr 00:1e:90:f3:f0:02
          inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0255.255.255.0255.255.255
          inet6 addr: fe80::21e:90ff:fef3:f002/64 Scopeink
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:29 errors:0 dropped:0 overruns:0 frame:0
          TX packets:29 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:1934 (1.9 KB)  TX bytes:2844 (2.8 KB)

eth0      Link encap:Ethernet  HWaddr 00:1e:90:f3:f0:02
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:44613 errors:0 dropped:0 overruns:0 frame:0
          TX packets:23445 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:63663064 (63.6 MB)  TX bytes:1792940 (1.7 MB)
          Interrupt:41 Base address:0xa000

lo        Link encapocal Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

virbr0    Link encap:Ethernet  HWaddr 2a:4a:49:13:de:8f
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0255.255.255.0255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

root@server1:~#



Before we start our first virtual machine, I recommend to reboot the system:
  1. reboot
复制代码

If you don't do this, you might get an error like open /dev/kvm: Permission denied in the virtual machine logs in the /var/log/libvirt/qemu/ directory.  

3 Creating An Image-Based VM
We can now create our first VM - an image-based VM (if you expect lots of traffic and many read- and write operations for that VM, use an LVM-based VM instead as shown in chapter 6 - image-based VMs are heavy on hard disk IO).
I want to create my virtual machines in the directory  /var/lib/libvirt/images/ (they cannot be created in the /root directory because the libvirt-qemu user doesn't have read permissions in that directory).
We will create a new directory for each VM that we want to create, e.g.  /var/lib/libvirt/images/vm1,  /var/lib/libvirt/images/vm2,  /var/lib/libvirt/images/vm3, and so on, because each VM will have a subdirectory called ubuntu-kvm, and obviously there can be just one such directory in /var/lib/libvirt/images/vm1, for example. If you try to create a second VM in /var/lib/libvirt/images/vm1, for example, you will get an error message saying ubuntu-kvm already exists (unless you run vmbuilder with the --dest=DESTDIR argument):
root@server1:/var/lib/libvirt/images/vm1# vmbuilder kvm ubuntu -c vm2.cfg
2009-05-07 16:32:44,185 INFO     Cleaning up
ubuntu-kvm already exists
root@server1:/var/lib/libvirt/images/vm1#

We will use the vmbuilder tool to create VMs. (You can learn more about vmbuilder here.) vmbuilder uses a template to create virtual machines - this template is located in the /etc/vmbuilder/libvirt/ directory. First we create a copy:
  1. mkdir -p /var/lib/libvirt/images/vm1/mytemplates/libvirt
  2. cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm1/mytemplates/libvirt/
复制代码

Now we come to the partitioning of our VM. We create a file called vmbuilder.partition...
  1. vi /var/lib/libvirt/images/vm1/vmbuilder.partition
复制代码

... and define the desired partitions as follows:
root 8000
swap 4000
---
/var 20000
This defines a root partition (/) with a size of 8000MB, a swap partition of 4000MB, and a /var partition of 20000MB. The --- line makes that the following partition (/var in this example) is on a separate disk image (i.e., this would create two disk images, one for root and swap and one for /var). Of course, you are free to define whatever partitions you like (as long as you also define root and swap), and of course, they can be in just one disk image - this is just an example.
I want to install openssh-server in the VM. To make sure that each VM gets a unique OpenSSH key, we cannot install openssh-server when we create the VM. Therefore we create a script called boot.sh that will be executed when the VM is booted for the first time. It will install openssh-server (with a unique key) and also force the user (I will use the default username administrator for my VMs together with the default password howtoforge) to change the password when he logs in for the first time:
  1. vi /var/lib/libvirt/images/vm1/boot.sh
复制代码

# This script will run the first time the virtual machine boots
# It is ran as root.
# Expire the user account
passwd -e administrator
# Install openssh-server
apt-get update
apt-get install -qqy --force-yes openssh-server
Make sure you replace the username administrator with your default login name.
(You can find more about this here: https://help.ubuntu.com/community/JeOSVMBuilder#First%20boot)
(You can also define a "first login" script as described here: https://help.ubuntu.com/community/JeOSVMBuilder#First%20login)
Now take a look at
  1. vmbuilder kvm ubuntu --help
复制代码

to learn about the available options.
To create our first VM, vm1, we go to the VM directory...
  1. cd /var/lib/libvirt/images/vm1/
复制代码

... and run vmbuilder, e.g. as follows:
  1. vmbuilder kvm ubuntu --suite=precise
  2. --flavour=virtual --arch=amd64
  3. --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system
  4. --ip=192.168.0.101 --gw=192.168.0.1 --part=vmbuilder.partition
  5. --templates=mytemplates --user=administrator --name=Administrator
  6. --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades
  7. --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm1/boot.sh --mem=256
  8. --hostname=vm1 --bridge=br0
复制代码

Most of the options are self-explanatory. --part specifies the file with the partitioning details, relative to our working directory (that's why we had to go to our VM directory before running vmbuilder), --templates specifies the directory that holds the template file (again relative to our working directory), and --firstboot specifies the firstboot script. --libvirt=qemu:///system tells KVM to add this VM to the list of available virtual machines. --addpkg allows you to specify Ubuntu packages that you want to have installed during the VM creation (see above why you shouldn't add openssh-server to that list and use the firstboot script instead). --bridge sets up a bridged network; as we have created the bridge br0 in chapter 2, we specify that bridge here.
In the --mirror line, you can specify an official Ubuntu repository in --mirror, e.g. http://de.archive.ubuntu.com/ubuntu. If you leave out --mirror, then the default Ubuntu repository (http://archive.ubuntu.com/ubuntu) will be used.
If you specify an IP address in the --ip switch, make sure that you also specify the correct gateway IP using the --gw switch (otherwise vmbuilder will assume that it is the first valid address in the network which might not be correct). Usually the gateway IP is the same that you use in /etc/network/interfaces (see chapter 2).
The build process can take a few minutes.
Afterwards, you can find an XML configuration file for the VM in /etc/libvirt/qemu/ (=> /etc/libvirt/qemu/vm1.xml):
  1. ls -l /etc/libvirt/qemu/
复制代码

root@server1:/var/lib/libvirt/images/vm1# ls -l /etc/libvirt/qemu/
total 8
drwxr-xr-x 3 root root 4096 May 21 13:00 networks
-rw------- 1 root root 2082 May 21 13:15 vm1.xml
root@server1:/var/lib/libvirt/images/vm1#

The disk images are located in the ubuntu-kvm/ subdirectory of our VM directory:
  1. ls -l /var/lib/libvirt/images/vm1/ubuntu-kvm/
复制代码

root@server1:/var/lib/libvirt/images/vm1# ls -l /var/lib/libvirt/images/vm1/ubuntu-kvm/
  total 604312
  -rw-r--r-- 1 root root 324337664 May 21 13:14 tmpE4IiRv.qcow2
  -rw-r--r-- 1 root root 294715392 May 21 13:15 tmpxvSVOT.qcow2
root@server1:/var/lib/libvirt/images/vm1#


Author: Falko Timme <ft [at] falkotimme [dot] com> 05/21/2012


Call
Send SMS
Add to Skype
You'll need Skype CreditFree via Skype

 楼主| 发表于 2014-3-23 20:51:39 | 显示全部楼层
本帖最后由 John 于 2014-3-24 12:53 编辑

4 Creating A Second VMIf you want to create a second VM (vm2), here's a short summary of the commands:
  1. mkdir -p /var/lib/libvirt/images/vm2/mytemplates/libvirt
  2. cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm2/mytemplates/libvirt/
复制代码
  1. vi /var/lib/libvirt/images/vm2/vmbuilder.partition
复制代码
  1. vi /var/lib/libvirt/images/vm2/boot.sh
复制代码
  1. cd /var/lib/libvirt/images/vm2/
  2. vmbuilder kvm ubuntu --suite=precise --flavour=virtual --arch=amd64 --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system --ip=192.168.0.102 --gw=192.168.0.1 --part=vmbuilder.partition --templates=mytemplates --user=administrator --name=Administrator --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm2/boot.sh --mem=256 --hostname=vm2 --bridge=br0
复制代码

(Please note that you don't have to create a new directory for the VM (/var/lib/libvirt/images/vm2) if you pass the -d DESTDIR argument to the vmbuilder command - it allows you to create a VM in a directory where you've already created another VM. In that case you don't have to create new vmbuilder.partition and boot.sh files and don't have to modify the template, but can simply use the existing files:
  1. cd /var/lib/libvirt/images/vm1/
  2. vmbuilder kvm ubuntu --suite=precise --flavour=virtual --arch=amd64 --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system --ip=192.168.0.102 --gw=192.168.0.1 --part=vmbuilder.partition --templates=mytemplates --user=administrator --name=Administrator --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm1/boot.sh --mem=256 --hostname=vm2 --bridge=br0 -d vm2-kvm
复制代码
)

5 Managing A VMVMs can be managed through virsh, the "virtual shell". To connect to the virtual shell, run
  1. virsh --connect qemu:///system
复制代码


This is how the virtual shell looks:
root@server1:~# virsh --connect qemu:///system
Welcome to virsh, the virtualization interactive terminal.

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

virsh #

You can now type in commands on the virtual shell to manage your VMs. Run
  1. help
复制代码


to get a list of available commands:
virsh # help
Grouped commands:

Domain Management (help keyword 'domain'):
    attach-device                  attach device from an XML file
    attach-disk                    attach disk device
    attach-interface               attach network interface
    autostart                      autostart a domain
    blkdeviotune                   Set or query a block device I/O tuning parameters.
    blkiotune                      Get or set blkio parameters
    blockpull                      Populate a disk from its backing image.
    blockjob                       Manage active block operations.
    blockresize                    Resize block device of domain.
    console                        connect to the guest console
    cpu-baseline                   compute baseline CPU
    cpu-compare                    compare host CPU with a CPU described by an XML file
    create                         create a domain from an XML file
    define                         define (but don't start) a domain from an XML file
    destroy                        destroy (stop) a domain
    detach-device                  detach device from an XML file
    detach-disk                    detach disk device
    detach-interface               detach network interface
    domid                          convert a domain name or UUID to domain id
    domif-setlink                  set link state of a virtual interface
    domjobabort                    abort active domain job
    domjobinfo                     domain job information
    domname                        convert a domain id or UUID to domain name
    domuuid                        convert a domain name or id to domain UUID
    domxml-from-native             Convert native config to domain XML
    domxml-to-native               Convert domain XML to native config
    dump                           dump the core of a domain to a file for analysis
    dumpxml                        domain information in XML
    edit                           edit XML configuration for a domain
    inject-nmi                     Inject NMI to the guest
    send-key                       Send keycodes to the guest
    managedsave                    managed save of a domain state
    managedsave-remove             Remove managed save of a domain
    maxvcpus                       connection vcpu maximum
    memtune                        Get or set memory parameters
    migrate                        migrate domain to another host
    migrate-setmaxdowntime         set maximum tolerable downtime
    migrate-setspeed               Set the maximum migration bandwidth
    migrate-getspeed               Get the maximum migration bandwidth
    reboot                         reboot a domain
    reset                          reset a domain
    restore                        restore a domain from a saved state in a file
    resume                         resume a domain
    save                           save a domain state to a file
    save-image-define              redefine the XML for a domain's saved state file
    save-image-dumpxml             saved state domain information in XML
    save-image-edit                edit XML for a domain's saved state file
    schedinfo                      show/set scheduler parameters
    screenshot                     take a screenshot of a current domain console and store it into a file
    setmaxmem                      change maximum memory limit
    setmem                         change memory allocation
    setvcpus                       change number of virtual CPUs
    shutdown                       gracefully shutdown a domain
    start                          start a (previously defined) inactive domain
    suspend                        suspend a domain
    ttyconsole                     tty console
    undefine                       undefine a domain
    update-device                  update device from an XML file
    vcpucount                      domain vcpu counts
    vcpuinfo                       detailed domain vcpu information
    vcpupin                        control or query domain vcpu affinity
    version                        show version
    vncdisplay                     vnc display

Domain Monitoring (help keyword 'monitor'):
    domblkinfo                     domain block device size information
    domblklist                     list all domain blocks
    domblkstat                     get device block stats for a domain
    domcontrol                     domain control interface state
    domif-getlink                  get link state of a virtual interface
    domifstat                      get network interface stats for a domain
    dominfo                        domain information
    dommemstat                     get memory statistics for a domain
    domstate                       domain state
    list                           list domains

Host and Hypervisor (help keyword 'host'):
    capabilities                   capabilities
    connect                        (re)connect to hypervisor
    freecell                       NUMA free memory
    hostname                       print the hypervisor hostname
    nodecpustats                   Prints cpu stats of the node.
    nodeinfo                       node information
    nodememstats                   Prints memory stats of the node.
    nodesuspend                    suspend the host node for a given time duration
    qemu-attach                    QEMU Attach
    qemu-monitor-command           QEMU Monitor Command
    sysinfo                        print the hypervisor sysinfo
    uri                            print the hypervisor canonical URI

Interface (help keyword 'interface'):
    iface-begin                    create a snapshot of current interfaces settings, which can be later commited (iface-commit) or restored (iface-rollback)
    iface-bridge                   create a bridge device and attach an existing network device to it
    iface-commit                   commit changes made since iface-begin and free restore point
    iface-define                   define (but don't start) a physical host interface from an XML file
    iface-destroy                  destroy a physical host interface (disable it / "if-down")
    iface-dumpxml                  interface information in XML
    iface-edit                     edit XML configuration for a physical host interface
    iface-list                     list physical host interfaces
    iface-mac                      convert an interface name to interface MAC address
    iface-name                     convert an interface MAC address to interface name
    iface-rollback                 rollback to previous saved configuration created via iface-begin
    iface-start                    start a physical host interface (enable it / "if-up")
    iface-unbridge                 undefine a bridge device after detaching its slave device
    iface-undefine                 undefine a physical host interface (remove it from configuration)

Network Filter (help keyword 'filter'):
    nwfilter-define                define or update a network filter from an XML file
    nwfilter-dumpxml               network filter information in XML
    nwfilter-edit                  edit XML configuration for a network filter
    nwfilter-list                  list network filters
    nwfilter-undefine              undefine a network filter

Networking (help keyword 'network'):
    net-autostart                  autostart a network
    net-create                     create a network from an XML file
    net-define                     define (but don't start) a network from an XML file
    net-destroy                    destroy (stop) a network
    net-dumpxml                    network information in XML
    net-edit                       edit XML configuration for a network
    net-info                       network information
    net-list                       list networks
    net-name                       convert a network UUID to network name
    net-start                      start a (previously defined) inactive network
    net-undefine                   undefine an inactive network
    net-uuid                       convert a network name to network UUID

Node Device (help keyword 'nodedev'):
    nodedev-create                 create a device defined by an XML file on the node
    nodedev-destroy                destroy (stop) a device on the node
    nodedev-dettach                dettach node device from its device driver
    nodedev-dumpxml                node device details in XML
    nodedev-list                   enumerate devices on this host
    nodedev-reattach               reattach node device to its device driver
    nodedev-reset                  reset node device

Secret (help keyword 'secret'):
    secret-define                  define or modify a secret from an XML file
    secret-dumpxml                 secret attributes in XML
    secret-get-value               Output a secret value
    secret-list                    list secrets
    secret-set-value               set a secret value
    secret-undefine                undefine a secret

Snapshot (help keyword 'snapshot'):
    snapshot-create                Create a snapshot from XML
    snapshot-create-as             Create a snapshot from a set of args
    snapshot-current               Get or set the current snapshot
    snapshot-delete                Delete a domain snapshot
    snapshot-dumpxml               Dump XML for a domain snapshot
    snapshot-edit                  edit XML for a snapshot
    snapshot-list                  List snapshots for a domain
    snapshot-parent                Get the name of the parent of a snapshot
    snapshot-revert                Revert a domain to a snapshot

Storage Pool (help keyword 'pool'):
    find-storage-pool-sources-as   find potential storage pool sources
    find-storage-pool-sources      discover potential storage pool sources
    pool-autostart                 autostart a pool
    pool-build                     build a pool
    pool-create-as                 create a pool from a set of args
    pool-create                    create a pool from an XML file
    pool-define-as                 define a pool from a set of args
    pool-define                    define (but don't start) a pool from an XML file
    pool-delete                    delete a pool
    pool-destroy                   destroy (stop) a pool
    pool-dumpxml                   pool information in XML
    pool-edit                      edit XML configuration for a storage pool
    pool-info                      storage pool information
    pool-list                      list pools
    pool-name                      convert a pool UUID to pool name
    pool-refresh                   refresh a pool
    pool-start                     start a (previously defined) inactive pool
    pool-undefine                  undefine an inactive pool
    pool-uuid                      convert a pool name to pool UUID

Storage Volume (help keyword 'volume'):
    vol-clone                      clone a volume.
    vol-create-as                  create a volume from a set of args
    vol-create                     create a vol from an XML file
    vol-create-from                create a vol, using another volume as input
    vol-delete                     delete a vol
    vol-download                   Download a volume to a file
    vol-dumpxml                    vol information in XML
    vol-info                       storage vol information
    vol-key                        returns the volume key for a given volume name or path
    vol-list                       list vols
    vol-name                       returns the volume name for a given volume key or path
    vol-path                       returns the volume path for a given volume name or key
    vol-pool                       returns the storage pool for a given volume key or path
    vol-upload                     upload a file into a volume
    vol-wipe                       wipe a vol

Virsh itself (help keyword 'virsh'):
    cd                             change the current directory
    echo                           echo arguments
    exit                           quit this interactive terminal
    help                           print help
    pwd                            print the current directory
    quit                           quit this interactive terminal


virsh #
  1. list
复制代码

shows all running VMs:
  1. list --all
复制代码

shows all VMs, running and inactive:
virsh # list --all
Id Name                 State
----------------------------------
  - vm1                  shut off
  - vm2                  shut off

virsh #


To stop a VM, run
  1. shutdown vm1
复制代码

To immediately stop it (i.e., pull the power plug), run
  1. destroy vm1
复制代码

Suspend a VM:
  1. suspend vm1
复制代码

Resume a VM:
  1. resume vm1
复制代码

These are the most important commands.
Type
  1. quit
复制代码

to leave the virtual shell.



 楼主| 发表于 2014-3-23 21:02:54 | 显示全部楼层
6 Creating An LVM-Based VMLVM-based VMs have some advantages over image-based VMs. They are not as heavy on hard disk IO, and they are easier to back up (using LVM snapshots).
To use LVM-based VMs, you need a volume group that has some free space that is not allocated to any logical volume. In this example, I use the volume group /dev/vg0 with a size of approx. 465GB...
  1. vgdisplay
复制代码
root@server1:~# vgdisplay
  --- Volume group ---
  VG Name               vg0
  System ID
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  3
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               465.29 GiB
  PE Size               4.00 MiB
  Total PE              119115
  Alloc PE / Size       24079 / 94.06 GiB
  Free  PE / Size       95036 / 371.23 GiB
  VG UUID               PRenhH-0MvN-wXCL-nl4i-IfsQ-J6fc-2raYLD

root@server1:~#

... that contains the logical volumes /dev/vg0/root with a size of approx. 100GB and /dev/vg0/swap_1 with a size of 1GB - the rest is not allocated and can be used for VMs:
  1. lvdisplay
复制代码
root@server1:~# lvdisplay
  --- Logical volume ---
  LV Name                /dev/vg0/root
  VG Name                vg0
  LV UUID                dwnORf-yG3U-x1ZC-Bet1-TOoc-q1Dd-KZnbtw
  LV Write Access        read/write
  LV Status              available
  # open                 1
  LV Size                93.13 GiB
  Current LE             23841
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0

  --- Logical volume ---
  LV Name                /dev/vg0/swap_1
  VG Name                vg0
  LV UUID                ZdPKO6-sZrr-tIRb-PPcl-aWBj-QAUU-fnYUuP
  LV Write Access        read/write
  LV Status              available
  # open                 2
  LV Size                952.00 MiB
  Current LE             238
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:1

root@server1:~#

I will now create the virtual machine vm5 as an LVM-based VM. We can use the vmbuilder command again. vmbuilder knows the --raw option which allows to write the VM to a block device (e.g. /dev/vg0/vm5) - I've tried this, and it gave back no errors, however, I was not able to boot the VM (start vm5 didn't show any errors either, but I've never been able to access the VM). Therefore, I will create vm5 as an image-based VM first and then convert it into an LVM-based VM.
  1. mkdir -p /var/lib/libvirt/images/vm5/mytemplates/libvirt
  2. cp /etc/vmbuilder/libvirt/* /var/lib/libvirt/images/vm5/mytemplates/libvirt/
复制代码

Make sure that you create all partitions in just one image file, so don't use --- in the vmbuilder.partition file:
  1. vi /var/lib/libvirt/images/vm5/vmbuilder.partition
复制代码
root 8000
swap 2000
/var 10000
  1. vi /var/lib/libvirt/images/vm5/boot.sh
复制代码
# This script will run the first time the virtual machine boots
# It is ran as root.

# Expire the user account
passwd -e administrator

# Install openssh-server
apt-get update
apt-get install -qqy --force-yes openssh-server
  1. cd /var/lib/libvirt/images/vm5/
  2. vmbuilder kvm ubuntu --suite=precise --flavour=virtual --arch=amd64 --mirror=http://de.archive.ubuntu.com/ubuntu -o --libvirt=qemu:///system --ip=192.168.0.105 --gw=192.168.0.1 --part=vmbuilder.partition --templates=mytemplates --user=administrator --name=Administrator --pass=howtoforge --addpkg=vim-nox --addpkg=unattended-upgrades --addpkg=acpid --firstboot=/var/lib/libvirt/images/vm5/boot.sh --mem=256 --hostname=vm5 --bridge=br0
复制代码
As you see from the vmbuilder.partition file, the VM will use a max. of 20GB, so we create a logical volume called /dev/vg0/vm5 with a size of 20GB now:
  1. lvcreate -L20G -n vm5 vg0
复制代码


Don't create a file system in the new logical volume!
We will use the qemu-img command to convert the image to an LVM-based VM.
Now we go to the VM's ubuntu-kvm/ directory...
  1. cd /var/lib/libvirt/images/vm5/ubuntu-kvm/
复制代码

... and find out how our image is named:
  1. ls -l
复制代码


root@server1:/var/lib/libvirt/images/vm5/ubuntu-kvm# ls -l
  total 592140
  -rw-r--r-- 1 root root 606470144 May 21 14:06 tmpesHsUI.qcow2
root@server1:/var/lib/libvirt/images/vm5/ubuntu-kvm#

Now that we know the name of our image (tmpN27tbO.qcow2), we can convert it as follows:

  1. qemu-img convert tmpesHsUI.qcow2 -O raw /dev/vg0/vm5
复制代码

Afterwards you can delete the disk image:
  1. rm -f tmpesHsUI.qcow2
复制代码

Now we must modify the VM's configuration...
  1. virsh edit vm5
复制代码

... and change the following section...
[...]
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='/var/lib/libvirt/images/vm5/ubuntu-kvm/tmpesHsUI.qcow2'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' unit='0'/>
    </disk>
[...]

... so that it looks as follows:
[...]
    <disk type='file' device='disk'>
      <driver name='qemu' type='raw'/>
      <source file='/dev/vg0/vm5'/>
      <target dev='hda' bus='ide'/>
      <address type='drive' controller='0' bus='0' unit='0'/>
    </disk>
[...]


You can now use virsh to manage the VM:
  1. virsh --connect qemu:///system
复制代码

Because we have modified the VM's XML file, we must run the define command first...
  1. define /etc/libvirt/qemu/vm5.xml
复制代码

... before we start the VM:
  1. start vm5
复制代码


7 Links



您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-26 13:45 , Processed in 0.019305 second(s), 20 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表