[2024-feb-29] Sad news: Eric Layton aka Nocturnal Slacker aka vtel57 passed away on Feb 26th, shortly after hospitalization. He was one of our Wiki's most prominent admins. He will be missed.

Welcome to the Slackware Documentation Project

¡Esta es una revisión vieja del documento!


En proceso de traducción. Víctor

KVM y libvirt

Con la combinación de KVM y libvirt, tiene una manera fácil de crear y administrar máquinas virtuales.

Según la página oficial homepage, libvirt es: Un kit de herramientas para interactuar con las capacidades de virtualización de versiones recientes de Linux (y otros sistemas operativos). Proporciona gestión de máquinas virtuales, redes virtuales y almacenamiento; tanto locales como remotos. Dado que libvirt actúa como un intermediario entre un hipervisor y las aplicaciones cliente, debe tener instalado un hipervisor compatible. Algunos ejemplos son: KVM / QEMU, Virtualbox, Xen y VMware ESX.

Quote: KVM (para Máquina Virtual basada en Kernel) es una solución de virtualización completa para Linux en hardware x86 que contiene extensiones de virtualización (Intel VT o AMD) V). Consiste en un módulo de kernel que se puede cargar, kvm.ko, que proporciona la infraestructura de virtualización central y un módulo específico del procesador, kvm-intel.ko o kvm-amd.ko.

Instalación

Libvirt se puede instalar utilizando un script slackbuild de slackbuilds.org. Proporciona un demonio que interactúa entre aplicaciones y máquinas virtuales. También proporciona un shell de línea de comandos, virsh , que se puede usar para administrar máquinas virtuales y configurar el entorno libvirt. Virsh también se puede usar en shell scripts para iniciar y detener máquinas virtuales.

El kernel slackware tiene el módulo KVM habilitado. El script de inicio de libvirt verificará la CPU y modificará el controlador correcto. Las herramientas de espacio de usuario se suministran con QEMU, que está disponible en slackbuilds.org. Anteriormente, se utilizaba una QEMU modificada, qemu-kvm . Sin embargo, desde la versión 1.3, QEMU incorpora esos cambios y qemu-kvm está restringido.

Una herramienta de gestión de escritorio gráfica, virt-manager , también está disponible en slackbuilds.org. Esto proporciona una visión general de todas las máquinas virtuales y tiene un asistente agradable para crear nuevas máquinas virtuales de una manera fácil.

Configuration

Inicio automático

Si desea que el demonio libvirt se inicie automáticamente, agregue la siguiente sección a /etc/rc.d/rc.local :

# start libvirt
if [ -x /etc/rc.d/rc.libvirt ]; then
    /etc/rc.d/rc.libvirt start
fi 

Asegúrese de que /etc/rc.d/rc.libvirt sea ejecutable.

Gestión de grupos de almacenamiento

El almacenamiento en libvirt se maneja en términos de grupos de almacenamiento y volúmenes de almacenamiento . Un grupo es un contenedor genérico para varios objetos de almacenamiento. Puede ser un directorio local, una partición física o un recurso compartido de red. Un almacenamiento volumen es la representación virtual de un disco para un sistema invitado. En el invitado, este volumen se ve como un disco local. Una imagen iso de un cd o dvd de instalación también se considera un volumen.

Cuando se instala libvirt, se crea un grupo de almacenamiento predeterminado (denominado default ) con el directorio local / var / lib / libvirt / images . Cualquier volumen recién creado se crea en este directorio.

Cree un nuevo grupo de almacenamiento basado en directorio usando virsh

Los comandos de Virsh se pueden pasar como parámetros a virsh en la línea de comandos, o puede iniciar un shell de virsh interactivo llamando a virsh sin parámetros:

# virsh
Welcome to virsh, the virtualization interactive terminal.

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

virsh # 

Para crear un nuevo grupo de almacenamiento basado en directorio, primero asegúrese de que el directorio de destino existe. Luego use el comando pool-define-as . La sintaxis básica para este comando es: pool-define-as <pool-name> dir - - - - <directory-name> . Por ejemplo, para crear el grupo discos para el directorio / srv / virtualmachines / disks , use el siguiente comando:

# virsh pool-define-as disks dir - - - - /srv/virtualmachines/disks
Pool disks defined

Para obtener ejemplos más complejos de este comando, consulte la página del manual de virsh.

Verifique que la agrupación exista con el comando pool-list . La opción -all muestra grupos activos e inactivos:

# virsh pool-list --all
Name                 State      Autostart 
-----------------------------------------
default              active     yes       
disks                inactive   no        

Ahora, cree el grupo real con el comando pool-build :

# virsh pool-build disks
Pool disks built

Cuando se construye pool, se puede iniciar con el comando pool-start :

# virsh pool-start disks
Pool disks started

Ahora se puede utilizar pool. En este punto, el grupo siempre debe iniciarse manualmente. Para que libvirt inicie el grupo cuando se inicie el demonio, debe verificar el indicador de inicio automático con el comando grupo-inicio automático :

# virsh pool-autostart disks
Pool disks marked as autostarted

Muestra información sobre el grupo con el comando pool-info :

# virsh pool-info disks
Name:           disks
UUID:           4ae08c3d-4622-9f2a-cfa9-9dea4d1eb465
State:          running
Persistent:     yes
Autostart:      yes
Capacity:       697.92 GiB
Allocation:     250.89 GiB
Available:      447.04 GiB

Cree un nuevo grupo de almacenamiento basado en directorio usando virt-manager

En primer lugar, asegúrese de que el directorio de destino existe. Entonces empieza virt-manager .

virt-manager Main window

Seleccione la máquina host (el valor predeterminado es localhost ). Seleccione Editar, Detalles de conexión en el menú, o haga clic con el botón derecho en la máquina y seleccione Detalles , o haga doble clic en la máquina. Aparece la ventana Detalles de la conexión . Seleccione la pestaña Almacenamiento .

virt-manager Connection Details

Presione el botón + en la parte inferior izquierda. Aparece la ventana Agregar grupo de almacenamiento .

virt-manager Add Storage Pool

Ingrese el nombre del nuevo grupo. El tipo predeterminado es dir , que es el tipo correcto. Presione Forward e ingrese el directorio del sistema en el campo de entrada Target Path . Presione Finalizar para crear el grupo.

Creating a new virtual machine

Creando una nueva máquina virtual usando virt-manager

Seleccione el host en el que desea crear la nueva máquina virtual. Esto será localhost por defecto. Haga clic con el botón derecho en el host y seleccione Nuevo , o haga clic en el botón Crear para iniciar el asistente de creación.

Paso 1: Asigne un nombre a la nueva máquina, seleccione el método de instalación del sistema operativo y presione Forward.

Paso 2: Dependiendo del método de instalación, se le pedirá que ingrese más detalles, como el nombre de la imagen de DVD iso utilizada.

También elige el tipo de sistema operativo y la versión. Al elegir Linux , elija Mostrar todas las opciones de SO en el indicador de Versión para obtener más opciones. Al elegir kernel genérico 2.6.x , el asistente asumirá un disco duro tipo IDE. Puedes cambiar esto en el paso 5.

Si elige kernel genérico 2.6.25 o posterior con virtio, la nueva máquina utilizará el controlador del kernel de virtio para emular un controlador de disco duro. La imagen de instalación de Slackware se iniciará, pero debe crear un initrd con los controladores del kernel de Virtio incluidos, de lo contrario su nueva máquina no arrancará.

Paso 3: Seleccione la cantidad de RAM y CPUs.

Paso 4: Configurar el almacenamiento para la nueva máquina. Esta opción está seleccionada de forma predeterminada. Si deselecciona esta opción, tendrá una máquina sin disco que aún puede iniciar distribuciones en vivo.

Puede dejar que el asistente cree una nueva imagen de disco sobre la marcha. Ingrese el tamaño y se creará una nueva imagen de disco (tipo raw ) en el grupo de almacenamiento predeterminado. Si selecciona Asignar todo el disco ahora , el tamaño completo del nuevo disco se asigna de antemano. De lo contrario, se crea una imagen más pequeña que crecerá cuando los datos se escriban en el disco.

Como alternativa, puede seleccionar otra imagen de disco (volumen) de un grupo de almacenamiento. También puede usar esta opción para crear un nuevo volumen de almacenamiento. Este método le dará más flexibilidad, ya que tiene más opciones sobre el tipo de disco que puede crear. Por último, puede usar esta opción para explorar el sistema de archivos local y seleccionar una imagen de disco que creó anteriormente.

Paso 5: Esto le dará una visión general de la nueva máquina

Si marca Personalizar la configuración antes de instalar , aparecerá la página de configuración de hardware de virt-manager. Aquí puede hacer cambios en la máquina antes de instalar.

La opción de red predeterminada en el paso 5 es Red virtual 'default': NAT . Esta red virtual utilizará el dispositivo virbr0 bridge para conectarse al host local mediante NAT. Libvirt iniciará dnsmasq para proporcionar DHCP para esta red.

Finalmente, puede cambiar el tipo de máquina virtual (KVM o QEMU) y la arquitectura (x86_64, i686, arm, etc.). Presione Finalizar para crear la máquina virtual. Será creado y arrancará.

Networking

A virtual machine can be set up in one of two ways: connected to a virtual network or connected to a shared physical device (bridged).

Virtual networks

Virtual networks are implemented by libvirt in the form of virtual switches. A virtual machine will have it's network card plugged into this virtual switch. The virtual switch appears on the host as a network interface.

The virtual network can operate in 3 different configurations:

  1. NAT: the virtual switch is connected to the host LAN in NAT mode. The host can connect to the VM's but other machines on the host network cannot. This is the default configuration.
  2. Routed: the virtual switch is connected to the host LAN without NAT.
  3. Isolated: the virtual switch is not connected to the host. Virtual machines can see each other and the host, but network traffic does not pass outside the host.

Dnsmasq and iptables

DHCP and DNS on the virtual networks is handled by Dnsmasq. For every virtual network that is started, a separate instance of Dnsmasq is started by libvirt.

When starting a virtual network, libvirt will also add iptables rules to handle routing and NAT between the host and the virtual network. It will also enable ip_forward.

Default network

After installation, one network (appropriately called default) is already created. It is configured as type NAT and this is the default network that is linked to new virtual machines. The network is setup to start automatically when libvirt is started, so it is immediately available when libvirt is running.

The network is visible on the host as bridge virbr0.

Do not add physical interfaces to this bridge. It is handled by libvirt.

Creation and maintenance

Virtual networks are visible on the Virtual Networks tab of the Host Connection Details window in Virtual Machine Manager. The + key can be used to add a new virtual network. Enter the name, IPv4 network address, DHCP range and the type of network.

Once the virtual network is created, it can be used in the virtual machine maintenance screens.

Shared folders using VirtFS

It is possible to share folders between the guest and host system using VirtFS (Plan 9 folder sharing over Virtio). This is available from kernel version 2.6.36 onwards. VirtFS is a passthrough filesystem, which means that a directory on the host can be directly accessed from the guest through the virtualization layer.

Prepare host kernel

Make sure the following options are set in the host kernel:

CONFIG_NET_9P=y
CONFIG_NET_9P_VIRTIO=y
CONFIG_NET_9P_DEBUG=y (Optional)
CONFIG_9P_FS=y
CONFIG_9P_FS_POSIX_ACL=y

On the guest system, modules 9p, 9pnet and 9pnet_virtio are needed. These should be available in the standard Slackware kernel.

Guest configuration

In virt-manager, edit the guest virtual machine and add new hardware. Select Filesystem and fill the required fields as shown below.

  • Mode. Select one of the following:
    • Passthrough: the host share is accessed with the permissions of the guest user.
    • Mapped: the host share is accessed with the permissions of the hypervisor (QEMU process).
    • Squash: Similar to passthrough except that failure of privileged operations like chown are ignored. This makes a passthrough-like mode usable for people who run the hypervisor as non-root.
  • Driver: use Path.
  • Write Policy (only available for path driver): use Default.
  • Source path = directory on the host which is shared.
  • Target path = mount tag that is made available on the guest system. This doesn't have to be an existing path.

Option Export filesystem as readonly mount does what it suggests.

Mounting the share

To mount the filesystem with tag hostshare on the guest at /mnt/share, logon to the guest and use:

# mount -t 9p -o trans=virtio,version=9p2000.L hostshare /mnt/share

Now the /mnt/share folder is available and changes are visible on the host and the guest. When permission errors occur, try sharing the host directory with a different mode.

Remote access

Work in progress

Advanced topics

Mount qcow image using nbd

Raw disk images can be mounted outside the virtual machine using a loopback device. To mount other image types like qcow, the qemu-nbd command can be used, which comes with qemu-kvm. It relies on the nbd (network block device) kernel module.

Start by loading the kernel module. The only parameter is the maximum partitions to be accessed. If this parameter is omitted, the default value is 0, which means no partitions will be mapped.

# modprobe nbd max_part=8

This will create various new devices /dev/nbdxx. Now the disk image can be connected to one of them:

# qemu-nbd -c /dev/ndb0 slackware.img

This will create additional devices /dev/nbd0pxx for the partitions on the disk. Partitions are numbered sequentially starting with 1. You can use the nbd0 device to access the whole disk, or the nbd0pxx devices to access the partitions:

# fdisk /dev/nbd0
# mount /dev/nbd0p1 /mnt/hd
Make sure the virtual machine is not running when you mount the disk image. Mounting the disk of a running machine will damage it.

To remove the connection:

# qemu-nbd -d /dev/nbd0

Setup PXE boot in libvirt

To enable PXE booting for the guest machines, a PXE boot server and a TFTP server are needed. Libvirt can be configured to handle both internally. These configuration options are not available in virt-manager, so virsh must be used to set this up.

  1. Create a directory /tftpboot and fill with the required files for the tftp boot service. See the article PXE: Installing Slackware over the network by AlienBOB for more details.
  2. Stop the default network and edit the network definition:
    # virsh net-destroy default
    # virsh net-edit default
  3. This will open the network configuration in a vi session. Add the tftp and bootp parameters in the ip section and save the file:
      <ip address='192.168.122.1' netmask='255.255.255.0'>
        <tftp root='/tftpboot' />
        <dhcp>
          <range start='192.168.122.2' end='192.168.122.254' />
          <bootp file='pxelinux.0' />
        </dhcp>
      </ip>
  4. Now restart the network:
    # virsh net-start default

Now the libvirt DHCP server will allow guests to PXE boot.

Troubleshooting

Remove password prompt in virt-manager

When you start virt-manager as a regular user, you may still be asked for the root password, even when you have setup the correct unix socket permissions (notification: “system policy prevents management of local virtualized systems”). This is because older versions of libvirt were using PolicyKit by default. Disable the use of PolicyKit by editing /etc/libvirt/libvirtd.conf. Uncomment the following options and change them to none :

auth_unix_ro = "none"
auth_unix_rw = "none"

Improve mouse movement

In graphics mode, the mouse movement can be erratic and difficult to change in the settings of your VM. To solve this, add a virtual tablet.

In virt-manager, open the VM by double-clicking on the machine and select the hardware info screen (the blue i button). Now, press +Add Hardware and select Input. Select Type EvTouch USB Graphics Tablet and press Finish. The next time the VM is started, the mouse movement is synchronized with your desktop cursor.

Change screen resolution to higher than 1024x768

The default emulated video card is of type Cirrus. This has a maximum resolution of 1024×768. The vga type can achieve a higher resolution, but for that to work, the X configuration in the guest OS needs to be changed as well.

To change this, open the VM and select the hardware info screen. Select the Video card and change the type to vga.

Start the VM. If a file /etc/X11/xorg.conf exists, change that. Otherwise create a new text file in /etc/X11/xorg.conf.d with extension conf, for example /etc/X11/xorg.conf.d/monitor.conf.

Add or change the following sections:

Section "Monitor"
        Identifier "Monitor0"
        HorizSync   30 - 80
        VertRefresh 40 - 90
EndSection

Section "Device"
        Identifier "Card0"
        Driver     "vesa"
Endsection

Section "Screen"
        Identifier "Screen0"
        Device     "Card0"
        Monitor    "Monitor0"
        SubSection "Display"
                Viewport 0 0
                Modes "1440x900"
        EndSubSection
EndSection

You can change the screen resolution (the Modes line) depending on your needs.

Resources

Sources

 es:howtos:general_admin:kvm_libvirt ()