Управление виртуализацией на основе libvirt

virsh править

Virsh - основной CLI для управления гостевыми доменами.

  • Подключение к libvirtd
virsh --connect qemu:///system 

или

export VIRSH_DEFAULT_CONNECT_URI= qemu:///system 
virsh --connect
  • Список всех функций
virsh# help
  • Справка по отдельно взятой функции
virsh# help snapshot-current
  NAME
    snapshot-current - Get or set the current snapshot

  SYNOPSIS
    snapshot-current <domain> [--name] [--security-info] [<snapshotname>]

  DESCRIPTION
    Get or set the current snapshot

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --name           list the name, rather than the full xml
    --security-info  include security sensitive information in XML dump
    [--snapshotname] <string>  name of existing snapshot to make current

Удаленный доступ и аутентификация править

TCP + TLS + SASL править

Настройка сервера править

Файл libvirtd.conf:

unix_sock_group = "kvm"
unix_sock_ro_perms = "0777"
unix_sock_rw_perms = "0770"
unix_sock_dir = "/var/run/libvirt"
auth_unix_ro = "sasl"
auth_tcp = "sasl"
auth_tls = "sasl"

Скрипт для создания ключей и сертификатов:

#! /bin/bash

# CA name
CA_NAME="ca"
CA_NAME_INFO="cn = AYT
ca 
cert_signing_key"

if [ ! -f "$CA_NAME".info ] ; then
	echo -e  "$CA_NAME_INFO" > "$CA_NAME".info
	certtool --generate-privkey > "$CA_NAME"key.pem 
	certtool --generate-self-signed --load-privkey "$CA_NAME"key.pem \
	  --template "$CA_NAME".info --outfile "$CA_NAME"cert.pem
fi

SERVER_NAME="server"
SERVER_NAME_INFO="organization = AYT
cn = FQDN of server
tls_www_server
encryption_key
signing_key
"

if [ ! -f "$SERVER_NAME".info ] ; then
	echo -e  "$SERVER_NAME_INFO" > "$SERVER_NAME".info
	certtool --generate-privkey > "$SERVER_NAME"key.pem 
	certtool --generate-certificate --load-privkey "$SERVER_NAME"key.pem \
	  --load-ca-certificate "$CA_NAME"cert.pem --load-ca-privkey "$CA_NAME"key.pem \
	    --template "$SERVER_NAME".info --outfile "$SERVER_NAME"cert.pem
fi

CLIENT_NAME="client"
CLIENT_NAME_INFO="country = RU
state = Moscow
locality = Moscow
organization = RH
cn = libvirt1cli
tls_www_client
encryption_key
signing_key
"
if [ ! -f "$CLIENT_NAME".info ] ; then
	echo -e  "$CLIENT_NAME_INFO" > "$CLIENT_NAME".info
	certtool --generate-privkey > "$CLIENT_NAME"key.pem
	certtool --generate-certificate --load-privkey "$CLIENT_NAME"key.pem \
	  --load-ca-certificate "$CA_NAME"cert.pem --load-ca-privkey "$CA_NAME"key.pem \
	    --template "$CLIENT_NAME".info --outfile "$CLIENT_NAME"cert.pem
fi

Расположение сертификатов на сервере:

/etc/pki/
|-- CA
|   `-- cacert.pem
`-- libvirt
    |-- clientcert.pem
    |-- private
    |   `-- serverkey.pem
    `-- servercert.pem

Проверка сертификатов и их расположения:

# virt-pki-validate

Found /usr/bin/certtool
Found CA certificate /etc/pki/CA/cacert.pem for AYT
The CA certificate and the client certificate do not match
CA organization: AYT
Client organization: RH
Found client certificate /etc/pki/libvirt/clientcert.pem for libvirt
Missing client private key /etc/pki/libvirt/private/clientkey.pem
Found server certificate /etc/pki/libvirt/servercert.pem for FQDN.NAME
Found server private key /etc/pki/libvirt/private/serverkey.pem

Создание пользователя и пароля доступа:

# saslpasswd2 -f /etc/libvirt/passwd.db -a libvirt user
Настройка клиента править

Расположение сертификатов:

/home/user/.pki
|-- libvirt
   |-- cacert.pem
   |-- clientcert.pem
   `-- clientkey.pem

Файл /home/user/.libvirt/libvirt.conf

uri_aliases = [
  "servername=qemu+tcp://FQDN_of_server/system",
]

Соединение с сервером:

$ virsh -c servername

TCP + SASL править

Делается по аналогии с TLS + SASL (пропуская создание и распространение сертификатов), с добавлением в файл libvirtd.conf:

listen_tcp = 1

Если TLS использовать не планируется, то надо явно это указать:

listen_tls = 0

KVM править

Свойства гипервизора править

# virsh capabilities
<capabilities>

  <host>
    <uuid>34313833-3134-435a-4337-303431334339</uuid>
    <cpu>
      <arch>x86_64</arch>
      <model>kvm32</model>
      <vendor>Intel</vendor>
      <topology sockets='2' cores='2' threads='1'/>
      <feature name='lahf_lm'/>
      <feature name='lm'/>
      <feature name='syscall'/>
      <feature name='dca'/>
      <feature name='pdcm'/>
      <feature name='xtpr'/>
      <feature name='cx16'/>
      <feature name='ssse3'/>
      <feature name='tm2'/>
      <feature name='est'/>
      <feature name='vmx'/>
      <feature name='ds_cpl'/>
      <feature name='monitor'/>
      <feature name='dtes64'/>
      <feature name='pbe'/>
      <feature name='tm'/>
      <feature name='ht'/>
      <feature name='ss'/>
      <feature name='acpi'/>
      <feature name='ds'/>
      <feature name='vme'/>
    </cpu>
    <power_management>
      <suspend_disk/>
    </power_management>
    <migration_features>
      <live/>
      <uri_transports>
        <uri_transport>tcp</uri_transport>
      </uri_transports>
    </migration_features>
    <topology>
      <cells num='1'>
        <cell id='0'>
          <cpus num='4'>
            <cpu id='0'/>
            <cpu id='1'/>
            <cpu id='2'/>
            <cpu id='3'/>
          </cpus>
        </cell>
      </cells>
    </topology>
  </host>

  <guest>
    <os_type>hvm</os_type>
    <arch name='i686'>
      <wordsize>32</wordsize>
      <emulator>/usr/libexec/qemu-kvm</emulator>
      <machine>rhel6.3.0</machine>
      <machine canonical='rhel6.3.0'>pc</machine>
      <machine>rhel6.2.0</machine>
      <machine>rhel6.1.0</machine>
      <machine>rhel6.0.0</machine>
      <machine>rhel5.5.0</machine>
      <machine>rhel5.4.4</machine>
      <machine>rhel5.4.0</machine>
      <domain type='qemu'>
      </domain>
      <domain type='kvm'>
        <emulator>/usr/libexec/qemu-kvm</emulator>
      </domain>
    </arch>
    <features>
      <cpuselection/>
      <deviceboot/>
      <pae/>
      <nonpae/>
      <acpi default='on' toggle='yes'/>
      <apic default='on' toggle='yes'/>
    </features>
  </guest>

  <guest>
    <os_type>hvm</os_type>
    <arch name='x86_64'>
      <wordsize>64</wordsize>
      <emulator>/usr/libexec/qemu-kvm</emulator>
      <machine>rhel6.3.0</machine>
      <machine canonical='rhel6.3.0'>pc</machine>
      <machine>rhel6.2.0</machine>
      <machine>rhel6.1.0</machine>
      <machine>rhel6.0.0</machine>
      <machine>rhel5.5.0</machine>
      <machine>rhel5.4.4</machine>
      <machine>rhel5.4.0</machine>
      <domain type='qemu'>
      </domain>
      <domain type='kvm'>
        <emulator>/usr/libexec/qemu-kvm</emulator>
      </domain>
    </arch>
    <features>
      <cpuselection/>
      <deviceboot/>
      <acpi default='on' toggle='yes'/>
      <apic default='on' toggle='yes'/>
    </features>
  </guest>

</capabilities>

Управление доменами править

Создание домена править
#!/bin/bash

NAME=ubuntu1204
CDROM='/home/user/Distributives/precise-alternate-amd64.iso'

virt-install --connect qemu:///system \
-n "$NAME" \
-r 1024 \
--arch=x86_64 \
--vcpus=1 \
--os-type=linux \
--os-variant=virtio26 \
--cdrom "$CDROM" \
--disk "/var/lib/libvirt/images/$NAME.img",bus=virtio,size=6,format=raw,cache=writeback \
--network network=default \
--hvm \
--accelerate \
--graphics vnc,password=password,listen=0.0.0.0,port=5903 &

Выбор параметров --os-type и --os-variant

virt-install --os-variant list

Опция --network network=default подключает интерфейс гостя к виртуальной сети с именем default, доступ из мира к которой реализуется через NAT на HN.

<interface type='network'>
  <mac address='52:54:00:9c:1f:e3'/>
  <syntaxhighlight network='default'/>
  <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

Без опции сетевой интерфейс подключится к мосту HN:

<interface type='bridge'>
  <mac address='52:54:00:3c:70:86'/>
  <syntaxhighlight bridge='br1'/>
  <model type='virtio'/>
  <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
</interface>

Мост можно указать явно: --network bridge=br1

Редактирование параметров домена править
virsh# edit <domain>
Клонирование домена править
virt-clone --connect qemu:///system --original GF1 --name GP1 --file "/var/lib/libvirt/images/GP1.img"

GP1 - имя нового домена. MAC адреса NIC в новом домене сгенерируются заново. Пароль на VNC сбросится. Во избежание неправильной обработки расширения имени файла, рекомендуется использовать кавычки в параметре --file.

Переименование домена править
virsh --connect qemu:///system dumpxml myvm > foo.xml
<edit foo.xml, change the domain name>
virsh undefine myvm
virsh define foo.xml
Удаление домена править

Удаление конфигурации

 virsh # undefine PXE-server
 Domain PXE-server has been undefined

Удаление виртуального диска

 rm /var/lib/libvirt/images/PXE-server.img

Управление дисками править

CDROM править
  • Подключение cdrom
virsh# attach-disk win2008 /mnt/Latest_virtio/virtio-win-0.1-15.iso  hdc --type cdrom  --mode readonly
  • Подсключение через файл описания устройства
 <disk type='file' device='cdrom'>
    <driver name='qemu' type='raw'/>
    <syntaxhighlight file='/mnt/photo-host-nfs/systemrescuecd-x86-2.8.0.iso'/>
    <target dev='hdc' bus='ide'/>
    <readonly/>
  </disk>
virsh# attach-device win2008 /root/cdrom.xml
Управление пулами править
  • Просмотр доступных пулов
virsh # pool-list 
Name                 State      Autostart 
-----------------------------------------
default              active     yes       
netapp               active     yes

default pool - это дисковая система HN, на которой расположен пул /var/lib/libvirt/images

virsh # pool-info default
Name:           default
UUID:           791f9733-c37f-e86c-c8ce-008051e1b8a5
State:          running
Persistent:     yes
Autostart:      yes
Capacity:       245.11 GB
Allocation:     188.68 GB
Available:      56.43 GB
  • Список томов в пуле
virsh # vol-list default --details 
Name               Path                                       Type  Capacity  Allocation
----------------------------------------------------------------------------------------
gx32.img           /var/lib/libvirt/images/gx32.img           file  10.00 GB     2.41 GB
PXE-server.img     /var/lib/libvirt/images/PXE-server.img     file  10.00 GB     7.37 GB
WindowsXP.img      /var/lib/libvirt/images/WindowsXP.img      file  15.00 GB     8.25 GB
iSCSI пул править
  • Описание пула
<pool type="iscsi">
	<name>netapp</name>
	<syntaxhighlight>
		<host name="10.0.110.94"/>
		<device path="iqn.2012-05:net.mydomain.storage:test"/>
	</syntaxhighlight>
	<target>
		<path>/dev/disk/by-path</path>
	</target>
</pool>
  • Подключение
virsh # pool-define /root/iscsi-pool.xml
virsh # pool-autostart netapp
virsh # pool-start netapp
  • Проверка
virsh # pool-refresh netapp
virsh # pool-list --details --all
Name     State    Autostart  Persistent   Capacity  Allocation  Available
-------------------------------------------------------------------------
default  running  yes        yes         245.11 GB   188.68 GB   56.43 GB
netapp   running  yes        yes          10.00 GB    10.00 GB      0.00
virsh # vol-list netapp --details 
Name        Path                                                                                   Type   Capacity  Allocation
------------------------------------------------------------------------------------------------------------------------------
unit:0:0:1  /dev/disk/by-path/ip-10.0.110.94:3260-iscsi-iqn.2012-05:net.mydomain.storage:test-lun-1  block  10.00 GB    10.00 GB
Подключение iSCSI диска в гостевую систему править
  • Описание iSCSI диска
<disk type='block' device='disk'>
	<driver name='qemu' type='raw' cache='none'/>
        <syntaxhighlight dev='/dev/disk/by-path/ip-10.0.110.94:3260-iscsi-iqn.2012-05:net.mydomain.storage:test-lun-1'/>
        <target dev='vdc'  bus='virtio'/>
	<shareable/>
</disk>
  • Подключение
virsh # attach-device PXEserv /root/hdd-iscsi.xml 
Device attached successfully
  • Отключение
virsh # detach-device PXEserv /root/hdd-iscsi.xml 
Device detached successfully
  • Повторное подключение
virsh # attach-device PXEserv /root/hdd-iscsi.xml
error: Failed to attach device from /root/hdd-iscsi.xml
error: internal error unable to execute QEMU command '__com.redhat_drive_add': Duplicate ID 'drive-virtio-disk2' for drive

При этой ошибке необходимо изменить значение dev='vdc' в описание iSCSI диска. Например, на dev='vdd'.

Подключение диска в виде файла в гостевую систему править
 virsh # attach-disk dntest --source /home/sanches/hddtemp.img --target vdb

При возникновении ошибки

error: Failed to attach disk
error: internal error unable to execute QEMU command '__com.redhat_drive_add': Device 'drive-virtio-disk1' could not be initialized

надо убедиться, что диск зарегистрирован в пуле default.

В гостевой системе

 echo 1 > /sys/bus/pci/rescan
 dmesg
virtio-pci 0000:00:06.0: enabling device (0000 -> 0003)
ACPI: PCI Interrupt Link [LNKB] enabled at IRQ 11
virtio-pci 0000:00:06.0: PCI INT A -> Link[LNKB] -> GSI 11 (level, high) -> IRQ 11
virtio-pci 0000:00:06.0: setting latency timer to 64
virtio-pci 0000:00:06.0: irq 45 for MSI/MSI-X
virtio-pci 0000:00:06.0: irq 46 for MSI/MSI-X
vdb: unknown partition table

Управление RAM править

setmem править
virsh # setmem 3 --live 1097152 
virsh # setmem 3 --config 1097152
memtune править

Управление сетью править

Связь NIC на HN с NIC на гостевой системе править

Схема подключения

 eth2(HN) <--> br_eth2(HN) <--> eth0(KVM)

br_eth2 - мост на HN, созданный с учетом настроек ОС на HN. На выходе получается

 # brctl show
bridge name     bridge id               STP enabled     interfaces
br_eth2         8000.0019bbce87dc       no              eth2

Дабавление нового NIC в гостевую

 virsh# edit <domin.xml>

и добавить запись новую запись поля <interface type='bridge'>

  
    <interface type='network'>
      <mac address='52:54:00:a4:c9:b0'/>
      <syntaxhighlight network='default'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <interface type='bridge'>
      <mac address='52:54:00:a2:29:b0'/>
      <syntaxhighlight bridge='br_eth2'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </interface>

Поле <address type='pci' ... вносить не надо, оно будет автоматичски сгенерировано системой libvirt после сохранения файла. После запуска гостевой, в мост br_eth2 будет добавлен интерфейс vnetX гостевой системы

bridge name     bridge id               STP enabled     interfaces
br_eth2         8000.0019bbce87dc       no              eth2
                                                        vnet3
Проброс NIC в гостя править

В /etc/libvirt/qemu.conf активируем

 relaxed_acs_check = 1

Получение нужной информации о NIC

# lspci -vn 
...
0e:00.0 0200: 14e4:1659 (rev 21)
        Subsystem: 103c:7031
        Physical Slot: 3
        Flags: fast devsel, IRQ 17
        Memory at fdff0000 (64-bit, non-prefetchable) [size=64K]
        [virtual] Expansion ROM at d0100000 [disabled] [size=64K]
        Capabilities: [48] Power Management version 2
        Capabilities: [50] Vital Product Data
        Capabilities: [58] MSI: Enable- Count=1/8 Maskable- 64bit+
        Capabilities: [d0] Express Endpoint, MSI 00
        Capabilities: [100] Advanced Error Reporting
        Capabilities: [13c] Virtual Channel <?>
        Capabilities: [160] Device Serial Number 00-19-bb-ff-fe-ce-87-dc
        Capabilities: [16c] Power Budgeting <?>
        Kernel modules: tg3

# lspci -t
-[0000:00]-+-00.0
           +-02.0-[09-12]--+-00.0-[0a-11]--+-00.0-[0b-0d]----00.0-[0c]----08.0
           |               |               +-01.0-[0e-10]----00.0
           |               |               \-02.0-[11]--
           |               \-00.3-[12]--
           +-03.0-[06-08]----00.0
           +-04.0-[13-15]--
           +-05.0-[16]--
           +-06.0-[17-19]--
           +-07.0-[1a]--
           +-10.0
           +-10.1
           +-10.2
           +-11.0
           +-13.0
           +-15.0
           +-16.0
           +-1c.0-[02-03]----00.0-[03]----00.0
           +-1c.1-[04-05]----00.0-[05]----00.0
           +-1d.0
           +-1d.1
           +-1d.2
           +-1d.3
           +-1d.7
           +-1e.0-[01]--+-03.0
           |            +-04.0
           |            +-04.2
           |            +-04.4
           |            \-04.6
           +-1f.0
           \-1f.1

Отвязываем устройство от HN

 # echo 0000:0e:00.0 > /sys/bus/pci/drivers/tg3/unbind

В xml домена добавляем

<hostdev mode='subsystem' type='pci' managed='yes'>
  <syntaxhighlight>
    <address domain='0x0000' bus='0x0e' slot='0x00' function='0x0'/>
  </syntaxhighlight>
</hostdev>

и запускаем домен

virsh # start PXE-server
error: Failed to start domain PXE-server
error: internal error Process exited while reading console log output: char device redirected to /dev/pts/4
No IOMMU found.  Unable to assign device "hostdev0"
qemu-kvm: -device pci-assign,host=0e:00.0,id=hostdev0,configfd=30,bus=pci.0,addr=0x5: Device 'pci-assign' could not be initialized

No IOMMU found говорит о том, что аппаратная платформа не поддерживает виртуализацию ввода/вывода.

gPXE править

Ошибка после загрузки initramfs

 udhcpc siocgifindex no such device

означает отсутствие модуля сетевой карты. Как правило, надо заменить model=virtio на model=e1000.

VNC править

Глобальный пароль для доступа по VNC:

vnc_password = "XYZ12345"

в /etc/libvirt/qemu.conf.

Различные ошибки править

  • error: no connection driver available for No connection for URI qemu:///system
  • error: failed to connect to the hypervisor

- libvirt собран/установлен без поддержки QEMU.

  • Error restoring domain: Unable to read from monitor: Connection reset by peer

- virsh managedsave-remove NameOfDomain

LXC править

Подключение

virsh -c lxc:///

OpenVZ править

XEN править