Virsh command – Redes de Computadoras para las PYMES

Índice general de la serie: Redes de Computadoras para las PYMES: Introducción

¡Hola amigos!

Si Ustedes han seguido con nosotros la lectura de los artículos publicados hasta ahora, se habrán dado cuenta de que estamos recorriendo un camino bastante lógico, con la finalidad de obtener una estación de trabajo o de laboratorio en casa, con el soporte necesario para hacer las máquinas o servidores virtuales en los que implementaremos los servicios mínimos para una LANLocal Area Network Empresarial.

Suponemos que Ustedes leyeron:

Los enlaces anteriores, así como los enlaces externos a diferentes páginas y sitios que contienen una rica información, incluidos en cada artículo, los ofrecemos con el propósito de que Ustedes alcancen un conocimiento básico sobre los diferentes temas tratados.

Este post es la continuación lógica del camino elegido. Su lectura y estudio les permitirá tener una idea del vasto mundo que es la Virtualización mediante Qemu-KVM y su principal librería libvirt.

Virsh – Interfaz principal de usuario para la gestión de Dominios Virtuales

Conocemos de lecturas anteriores que la Virtualización en Linux significa la capacidad de ejecutar múltiples instancias de diferentes sistemas operativos concurrentes, sobre una misma plataforma de hardware. Libvirt es un juego de herramientas escrito en el lenguaje C, que nos permite interactuar con las capacidades de virtualización de las versiones de Linux más recientes, y también con las de otros sistemas operativos.

Podemos utilizar a el programa virsh para crear, pausar, apagar, listar, y muchas operaciones más sobre los dominios virtuales y hipervisores que los alojan. El nombre del programa sugiere que es la abreviatura de «Virtualization Shell» o Procesador de Comandos de Virtualización.

De forma genérica lo podemos invocar como:

virsh [OPCIÓN].... <comando> <dominio> [ARGUMENTOS]...
  • comando: puede ser uno de los 215 comandos listados mas adelante
  • dominio: nombre del dominio o máquina virtual, o identificador numérico ID del domino, o identificador UUID del dominio.
  • argumentos: opciones específicas de cada comando

Existen varias excepciones de la regla anterior, como en los casos que el comando actúe sobre todos los dominios, una máquina, o directamente sobre un Hipervisor Xen – Xen Hypervisor. Tales excepciones se aclaran para cada comando.

Nota: Aunque es válido identificar a una máquina virtual por su ID numérico, ese valor numérico se interpretará siempre como el ID del dominio, y no como su nombre.

Las OPCIONES del comando virsh son:

  • -c, –connect URI: Se conecta con la URI «Identificador Uniforme de Recursos» – Uniform Resource Identifier, en vez de la URI por defecto que es la del hipervisor local.
  • d, –debug LEVEL: Habilita los mensajes de depuración – debug, hasta el valor entero LEVEL, argumento numérico que puede tomar los valores entre 0 hasta 4. Precisamente 4 es el valor por defecto.
  • -e, –escape string: Establece una secuencia de caracteres alternativa para cuando presionamos la tecla «Esc«. La secuencia por defecto es ^]. Los caracteres permitidos son: cualquier carácter alfabético, @, [, ], \, ^, _. Sugerimos no modificar la secuencia de caracteres por defecto.
  • -h, –help: Ignora cualquier otro argumento y se comporta como si se ejecutar el comando help.
  • -k, –keepalive-interval INTERVAL: Establece un intervalo en segundos para enviar mensajes tipo keepalive, para comprobar si la conexión con el servidor se mantiene viva aun. Si el valor de INTERVAL se establece a 0, entonces se deshabilita éste mecanismo de comprobación.
  • -K, –keepalive-count COUNT: Establece la cantidad de veces que se puede enviar un mensaje keepalive sin obtener respuesta desde el servidor, y sin marcar la conexión como muerta. No tendrá efecto alguno sobre ésta opción, si el valor INTERVAL de la opción anterior se estableció a 0.
  • -l, –log FILE: Dirige la salida del registro de operaciones al archivo FILE.
  • -q, –quiet: Evita la información extra de los mensajes. Modo silencioso.
  • -r, –readonly: La conexión inicial se establece en modo de Solo Lectura. Igual a cuando utilizamos la opción –readonly en el comando connect.
  • -t, –timing: Muestra el tiempo consumido por cada comando.
  • -v, –version=short: Ignora cualquier otro argumento, y muestra solamente la versión de la librería libvirt de la que proviene el programa virsh.
  • -V, –version=long: Ignora cualquier otro argumento y muestra la versión de la librería libvirt de la que proviene el programa virsh y además, los diferentes hipervisores, controladores – drivers, tipos de redes, etcétera que la compilación soporta.

Notas:

  • La mayoría de las operaciones del comando virsh, supone que la librería libvirt sea capaz de conectarse con un servicio libvirtd en ejecución.
  • La mayoría de los comandos requieren que se ejecuten con privilegios del usuario root debido a los canales de comunicación que utiliza para comunicarse con el Hipervisor. De ejecutarse con los privilegios de un usuario normal, retornará un error.
  • La mayoría de los comandos actúan de forma sincrónica. Posibles excepciones son shutdown, setvcpus y setmem. En esos casos, el hecho de que virsh retorne el prompt de comando, puede que no signifique que la acción se completó satisfactoriamente. Se debe consultar periódicamente para detectar que se completó la operación en el Invitado – Guest.

Para mas información de contenido, consulte man virsh.

Sugerencias sobre cómo abordar el aprendizaje de virsh

Para facilitar la obtención de ayuda sobre el uso de los mas de 200 comandos, virsh los agrupa por palabras claves – help keyword, las cuales son:

  • domain
  • monitor
  • host
  • interface
  • filter
  • network
  • nodedev
  • secret
  • snapshot
  • pool
  • volume
  • virsh
buzz@sysadmin:~$ virsh help domain
 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
    blockcommit                    Start a block commit operation.
    blockcopy                      Start a block copy operation.
    blockjob                       Manage active block operations
    blockpull                      Populate a disk from its backing image.
    blockresize                    Resize block device of domain.
    change-media                   Change media of CD or floppy drive
    console                        connect to the guest console
    cpu-baseline                   compute baseline CPU
    cpu-compare                    compare host CPU with a CPU described by an XML file
    cpu-stats                      show domain cpu statistics
    create                         create a domain from an XML file
    define                         define (but don't start) a domain from an XML file
    desc                           show or set domain's description or title
    destroy                        destroy (stop) a domain
    detach-device                  detach device from an XML file
    detach-disk                    detach disk device
    detach-interface               detach network interface
    domdisplay                     domain display connection URI
    domfsfreeze                    Freeze domain's mounted filesystems.
    domfsthaw                      Thaw domain's mounted filesystems.
    domfstrim                      Invoke fstrim on domain's mounted filesystems.
    domhostname                    print the domain's hostname
    domid                          convert a domain name or UUID to domain id
    domif-setlink                  set link state of a virtual interface
    domiftune                      get/set parameters of a virtual interface
    domjobabort                    abort active domain job
    domjobinfo                     domain job information
    domname                        convert a domain id or UUID to domain name
    dompmsuspend                   suspend a domain gracefully using power management functions
    dompmwakeup                    wakeup a domain from pmsuspended state
    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
    event                          Domain Events
    inject-nmi                     Inject NMI to the guest
    send-key                       Send keycodes to the guest
    send-process-signal            Send signals to processes
    lxc-enter-namespace            LXC Guest Enter Namespace
    managedsave                    managed save of a domain state
    managedsave-remove             Remove managed save of a domain
    memtune                        Get or set memory parameters
    metadata                       show or set domain's custom XML metadata
    migrate                        migrate domain to another host
    migrate-setmaxdowntime         set maximum tolerable downtime
    migrate-compcache              get/set compression cache size
    migrate-setspeed               Set the maximum migration bandwidth
    migrate-getspeed               Get the maximum migration bandwidth
    numatune                       Get or set numa parameters
    qemu-attach                    QEMU Attach
    qemu-monitor-command           QEMU Monitor Command
    qemu-monitor-event             QEMU Monitor Events
    qemu-agent-command             QEMU Guest Agent Command
    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
    emulatorpin                    control or query domain emulator affinity
    vncdisplay                     vnc display

buzz@sysadmin:~$ virsh help monitor
 Domain Monitoring (help keyword 'monitor'):
    domblkerror                    Show errors on block devices
    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
    domiflist                      list all domain virtual interfaces
    domifstat                      get network interface stats for a domain
    dominfo                        domain information
    dommemstat                     get memory statistics for a domain
    domstate                       domain state
    domstats                       get statistics about one or multiple domains
    domtime                        domain time
    list                           list domains

buzz@sysadmin:~$ virsh help monitor
 Domain Monitoring (help keyword 'monitor'):
    domblkerror                    Show errors on block devices
    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
    domiflist                      list all domain virtual interfaces
    domifstat                      get network interface stats for a domain
    dominfo                        domain information
    dommemstat                     get memory statistics for a domain
    domstate                       domain state
    domstats                       get statistics about one or multiple domains
    domtime                        domain time
    list                           list domains

buzz@sysadmin:~$ virsh help host
 Host and Hypervisor (help keyword 'host'):
    allocpages                     Manipulate pages pool size
    capabilities                   capabilities
    cpu-models                     CPU models
    domcapabilities                domain capabilities
    freecell                       NUMA free memory
    freepages                      NUMA free pages
    hostname                       print the hypervisor hostname
    maxvcpus                       connection vcpu maximum
    node-memory-tune               Get or set node memory parameters
    nodecpumap                     node cpu map
    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
    sysinfo                        print the hypervisor sysinfo
    uri                            print the hypervisor canonical URI
    version                        show version

buzz@sysadmin:~$ virsh help interface
 Interface (help keyword 'interface'):
    iface-begin                    create a snapshot of current interfaces settings, which can be later committed (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)

buzz@sysadmin:~$ virsh help filter
 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

buzz@sysadmin:~$ virsh help network
 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-dhcp-leases                print lease info for a given network
    net-dumpxml                    network information in XML
    net-edit                       edit XML configuration for a network
    net-event                      Network Events
    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 a persistent network
    net-update                     update parts of an existing network's configuration
    net-uuid                       convert a network name to network UUID

buzz@sysadmin:~$ virsh help nodedev
 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-detach                 detach 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

buzz@sysadmin:~$ virsh help secret
 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

buzz@sysadmin:~$ virsh help snapshot
 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-info                  snapshot information
    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
buzz@sysadmin:~$ virsh help pool
 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

buzz@sysadmin:~$ virsh help volume
 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 volume contents 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-resize                     resize a vol
    vol-upload                     upload file contents to a volume
    vol-wipe                       wipe a vol

buzz@sysadmin:~$ virsh help virsh
 Virsh itself (help keyword 'virsh'):
    cd                             change the current directory
    connect                        (re)connect to hypervisor
    echo                           echo arguments
    exit                           quit this interactive terminal
    help                           print help
    pwd                            print the current directory
    quit                           quit this interactive terminal

Para obtener ayuda específica sobre cualquiera de los comandos listados

Debemos ejecutar virsh help <comando>. Ejemplos:

buzz@sysadmin:~$ virsh help list
  NAME
    list - list domains

  SYNOPSIS
    list [--inactive] [--all] [--transient] [--persistent] [--with-snapshot] [--without-snapshot] [--state-running] [--state-paused] [--state-shutoff] [--state-other] [--autostart] [--no-autostart] [--with-managed-save] [--without-managed-save] [--uuid] [--name] [--table] [--managed-save] [--title]

  DESCRIPTION
    Returns list of domains.

  OPTIONS
    --inactive       list inactive domains
    --all            list inactive & active domains
    --transient      list transient domains
    --persistent     list persistent domains
    --with-snapshot  list domains with existing snapshot
    --without-snapshot  list domains without a snapshot
    --state-running  list domains in running state
    --state-paused   list domains in paused state
    --state-shutoff  list domains in shutoff state
    --state-other    list domains in other states
    --autostart      list domains with autostart enabled
    --no-autostart   list domains with autostart disabled
    --with-managed-save  list domains with managed save state
    --without-managed-save  list domains without managed save
    --uuid           list uuid's only
    --name           list domain names only
    --table          list table (default)
    --managed-save   mark inactive domains with managed save state
    --title          show domain title

buzz@sysadmin:~$ virsh help shutdown
  NAME
    shutdown - gracefully shutdown a domain

  SYNOPSIS
    shutdown <domain> [--mode <string>]

  DESCRIPTION
    Run shutdown in the target domain.

  OPTIONS
    [--domain] <string>  domain name, id or uuid
    --mode <string>  shutdown mode: acpi|agent|initctl|signal|paravirt

Ejemplos de uso del comando virsh

Versión del virsh

buzz@sysadmin:~$ virsh -v
1.2.9

buzz@sysadmin:~$ virsh -V
Virsh command line tool of libvirt 1.2.9
See web site at http://libvirt.org/

Compiled with support for:
 Hypervisors: QEMU/KVM LXC UML Xen LibXL OpenVZ VMWare VirtualBox Test
 Networking: Remote Network Bridging Interface netcf Nwfilter VirtualPort
 Storage: Dir Disk Filesystem SCSI Multipath iSCSI LVM RBD Sheepdog
 Miscellaneous: Daemon Nodedev AppArmor SELinux Secrets Debug DTrace Readline Modular

Entrar a la consola virsh

buzz@sysadmin:~$ sudo virsh
[sudo] password for buzz: 
Welcome to virsh, the virtualization interactive terminal.

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

Listar todos los dominios

virsh # list --all
 Id    Name                           State
----------------------------------------------------
 -     dns                            shut off
 -     miweb                          shut off
 -     sysadmin-centos                shut off

Iniciar el dominio dns

virsh # start dns
Domain dns started

virsh # domdisplay dns
spice://127.0.0.1:5900

Listar volúmenes de almacenamiento

virsh # pool-list
 Name                 State      Autostart 
-------------------------------------------
 default              active     no        
 vms-images           active     yes       

virsh # pool-info default
Name:           default
UUID:           3d158e62-6237-464f-9d8f-07ac98be56dc
State:          running
Persistent:     yes
Autostart:      no
Capacity:       14.64 GiB
Allocation:     5.18 GiB
Available:      9.46 GiB

virsh # pool-info vms-images
Name:           vms-images
UUID:           72e1b63d-3d90-4f02-bfde-197fd00f3b94
State:          running
Persistent:     yes
Autostart:      yes
Capacity:       916.77 GiB
Allocation:     464.22 GiB
Available:      452.55 GiB

Listar las imágenes contenidas en un volumen

virsh # vol-list vms-images
 Name                 Path                                    
------------------------------------------------------------------------------
 CentOS-7-x86_64-Everything-1511.iso /tera/vms/CentOS-7-x86_64-Everything-1511.iso
 dns.qcow2            /tera/vms/dns.qcow2                     
 miweb.qcow2          /tera/vms/miweb.qcow2                   
 openSUSE-13.2-DVD-x86_64.iso /tera/vms/openSUSE-13.2-DVD-x86_64.iso  
 sysadmin-centos.qcow2 /tera/vms/sysadmin-centos.qcow2         
 sysadmin.qcow2       /tera/vms/sysadmin.qcow2                

virsh # vol-info dns.qcow2 --pool vms-images
Name:           dns.qcow2
Type:           file
Capacity:       10.00 GiB
Allocation:     1.56 GiB

Crear una imagen de disco en un volumen

virsh # vol-create-as --pool vms-images --name dns2.raw --capacity 20G
Vol dns2.raw created

virsh # vol-list vms-images
 Name                 Path                                    
------------------------------------------------------------------------------
 CentOS-7-x86_64-Everything-1511.iso /tera/vms/CentOS-7-x86_64-Everything-1511.iso
 dns.qcow2            /tera/vms/dns.qcow2                     
 dns2.raw           /tera/vms/dns2.raw                    
 miweb.qcow2          /tera/vms/miweb.qcow2                   
 openSUSE-13.2-DVD-x86_64.iso /tera/vms/openSUSE-13.2-DVD-x86_64.iso  
 sysadmin-centos.qcow2 /tera/vms/sysadmin-centos.qcow2         
 sysadmin.qcow2       /tera/vms/sysadmin.qcow2

Unir la imagen recién creada a un dominio en ejecución

virsh # domstate dns
running

virsh # dominfo dns
Id:             4
Name:           dns
UUID:           9e69ebc6-213e-42f7-99bf-83b333e93958
OS Type:        hvm
State:          running
CPU(s):         1
CPU time:       25.2s
Max memory:     262144 KiB
Used memory:    262144 KiB
Persistent:     yes
Autostart:      disable
Managed save:   no
Security model: none
Security DOI:   0

virsh # domblklist dns
Target     Source
------------------------------------------------
vda        /tera/vms/dns.qcow2
hda        -

virsh # attach-disk dns /tera/vms/dns2.raw vdb --persistent --live
Disk attached successfully

virsh # domblklist dns
Target     Source
------------------------------------------------
vda        /tera/vms/dns.qcow2
vdb        /tera/vms/dns2.raw
hda        -

virsh # domblkstat dns vda
vda rd_req 5438
vda rd_bytes 67512320
vda wr_req 405
vda wr_bytes 2854912
vda flush_operations 14
vda rd_total_times 20533958076
vda wr_total_times 423498369
vda flush_total_times 232141607

virsh # domblkstat dns vdb
vdb rd_req 117
vdb rd_bytes 479232
vdb wr_req 0
vdb wr_bytes 0
vdb flush_operations 0
vdb rd_total_times 28976780
vdb wr_total_times 0
vdb flush_total_times 0

Particionamos, formateamos y montamos el nuevo disco

virsh # quit
buzz@sysadmin:~$ ssh buzz@192.168.10.5
buzz@192.168.10.5's password:

buzz@dns:~$ sudo fdisk /dev/vdb
[sudo] password for buzz:

Welcome to fdisk (util-linux 2.25.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (1-4, default 1): 
First sector (2048-41949951, default 2048): 
Last sector, +sectors or +size{K,M,G,T,P} (2048-41949951, default 41949951): 

Created a new partition 1 of type 'Linux' and of size 20 GiB.

Command (m for help): p
Disk /dev/vdb: 20 GiB, 21478375424 bytes, 41949952 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x12e1497e

Device     Boot Start      End  Sectors Size Id Type
/dev/vdb1        2048 41943039 41940992  20G 83 Linux


Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Syncing disks.

buzz@dns:~$ sudo mkfs.ext4 /dev/vdb1

buzz@dns:~$ sudo fdisk -l

Disk /dev/vda: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xb1e40216

Device     Boot    Start      End  Sectors  Size Id Type
/dev/vda1  *        2048 20013055 20011008  9.6G 83 Linux
/dev/vda2       20015102 20969471   954370  466M  5 Extended
/dev/vda5       20015104 20969471   954368  466M 82 Linux swap / Solaris

Disk /dev/vdb: 20 GiB, 21478375424 bytes, 41949952 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x12e1497e

Device     Boot Start      End  Sectors Size Id Type
/dev/vdc1        2048 41943039 41940992  20G 83 Linux

buzz@dns:~$ sudo mkdir /almacen
buzz@dns:~$ sudo nano /etc/fstab 
/dev/vdb1       /almacen        ext4    defaults        0       0

buzz@dns:~$ sudo mount -a
buzz@dns:~$ ls -l /almacen
total 16
drwx------ 2 root root 16384 dic 10 17:34 lost+found

Regresamos a la consola virsh

buzz@sysadmin:~$ sudo virsh
Welcome to virsh, the virtualization interactive terminal.

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

virsh # 

Apagamos

virsh # domstate dns
running

virsh # shutdown dns
Domain dns is being shutdown

Resumen

Hasta aquí hemos navegado por las orillas del mar Virsh. 😉  Para más información, ejecutar el comando man virsh. No obstante, dejamos un archivo en texto plano denominado virsh-help.txt que confeccionamos para facilitarle la vida a quienes se aventuren con éste Súper Comando para la administración y gestión de Hipervisores y sus Máquinas Virtuales.

Recomendamos encarecidamente que prueben los comandos fuera del ambiente de producción.


7 comentarios, deja el tuyo

Deja tu comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

*

*

  1. Responsable de los datos: Miguel Ángel Gatón
  2. Finalidad de los datos: Controlar el SPAM, gestión de comentarios.
  3. Legitimación: Tu consentimiento
  4. Comunicación de los datos: No se comunicarán los datos a terceros salvo por obligación legal.
  5. Almacenamiento de los datos: Base de datos alojada en Occentus Networks (UE)
  6. Derechos: En cualquier momento puedes limitar, recuperar y borrar tu información.

  1.   dhunter dijo

    Me gustaría usar Virsh para más cosas, actualmente solo lo básico, start, stop, todo lo demás uso virt-manager, me gusta que puedes tener N servers corriendo libvirt y manejarlos desde tu workstation con virt-manager.

  2.   federico dijo

    Hola amigo Dhunter!!! Ya estoy en mi trabajo. Descarga el archivo virsh-help.txt que te va a ayudar mucho. Lo confeccioné a partir de la propia consola del virsh, y después hice un script para llenarlo. Pienso que, al estar organizado por las palabras claves de la ayuda, sea más potable. En el próximo artículo toco mas temas de este comando.

  3.   Zodia Carburus dijo

    Saludos Federico. He seguido tus interesantes artículos sobre las PYMES. Decididamente es mas fácil el uso de la consola para la administración rápida y eficiente. También consumen menos recursos. Espero por tus próximas entregas.

  4.   crespo88 dijo

    Bueno Federico, ya cumpliste conmigo. Gracias por este regalo que nos has hecho. Excelente post, estuve esperando por este artículo sobre el virsh. Gracias hermano, todos sabremos darle el uso apropiado.

  5.   fico dijo

    De nada Crespo88. Para ese estamos en DesdeLinux.

  6.   Ismael Alvarez Wong dijo

    hola fico, me he quedado asombrado con la potencialidad del comando virsh, vaya que no encuentro palabras para describir lo que pienso al respecto, increible, y eso que lo expones en el post es solo una pincelada, usando tus propias palabras «Hasta aquí hemos navegado por las orillas del mar Virsh.»
    muy util cuando expones como investigar la ayuda del virsh utilizando sus palabras clave.
    genial el ejemplo desarrollado de Crear una imagen de disco en un volumen y Unirla (adicionarla) a un dominio (o MV) en ejecución, todo con virsh; para despues desde nuestra WK sysadmin conectarnos por SSH al dominio y dentro de el mismo, crear la particion y su filesystem ext4 para finalmente montarla desde el fstab.
    Nada que ha seguir con los sgtes posts de la serie de virt qemu-kvm y muchas gracias por compartir todo esto.

    1.    federico dijo

      Has captado la esencia del mensaje, amigo Wong. Si solo con la introducción al comando Virsh, se pueden hacer maravillas, ¿por qué no continuar con su estudio y uso?. Virsh es, por definición, la interfaz del Qemu-KVM, concebida por sus creadores en Red Hat, Inc y patrocinados por esa grande compañía. Aunque sabemos que existen otras interfaces como el Virt-Manager y el oVirt, Virsh sigue siendo la más completa para manejar la librería libvirt. Gracias amigo Wong por tus valiosos comentarios.