Virsh command - Computer Networks for SMEs

General index of the series: Computer Networks for SMEs: Introduction

Hello friends!

If you have followed with us reading the articles published so far, you will have realized that we are following a quite logical path, in order to obtain a work station or laboratory at home, with the necessary support to do the virtual machines or servers in which we will implement the minimum services for a LAN - Local Area Network CORPORATE LAW .

We assume that you read:

The previous links, as well as the external links to different pages and sites that contain rich information, included in each article, are offered with the purpose that you achieve a basic knowledge about the different topics covered.

This post is the logical continuation of the chosen path. Your reading and study will allow you to have an idea of ​​the vast world that is Virtualization through Qemu-KVM and its main bookstore libvirt.

Virsh - Main user interface for managing Virtual Domains

We know from previous readings that Virtualization in Linux means the ability to run multiple instances of different concurrent operating systems, on the same hardware platform. libvirt is a toolkit written in the C language, which allows us to interact with the virtualization capabilities of the latest versions of Linux, and also with those of other operating systems.

We can use the program Virsh to create, pause, shutdown, list, and many more operations on the virtual domains and hypervisors that host them. The name of the program suggests that it is short for «Virtualization Shell»Or Virtualization Command Processor.

In a generic way we can invoke it as:

virsh [OPTION] .... [ARGUMENTS] ...
  • command: can be one of the 215 commands listed later
  • domain: name of the domain or virtual machine, or numeric identifier ID of the domain, or UUID of the domain.
  • arguments: options specific to each command

There are several exceptions to the previous rule, such as in cases where the command acts on all domains, a machine, or directly on a Xen Hypervisor - XenHypervisor. Such exceptions are cleared for each command.

Note: Although it is valid to identify a virtual machine by its numeric ID, this numeric value will always be interpreted as the domain ID, and not as its name.

All the Virsh command OPTIONS are:

  • -c, --connect URI: Connects to URI «Uniform Resource Identifier"- Uniform Resource Identifier, instead of the default URI which is that of the local hypervisor.
  • -d, --debug LEVEL: Enable debugging messages - debugging, up to the integer LEVEL value, a numeric argument that can take the values ​​between 0 and 4. Precisely 4 is the default value.
  • -e, --escape string: Sets an alternative character sequence for when we press the «keyI«. The default sequence is ^]. The allowed characters are: any alphabetic character, @, [,], \, ^, _. We suggest do not modify the default character sequence.
  • -h, --help: Ignores any other arguments and behaves as if the command were executed help.
  • -k, --keepalive-interval INTERVAL: Sets an interval in seconds to send messages type keep alive, to check if the connection to the server is still alive. If the value of INTERVAL is set to 0, then this checking mechanism is disabled.
  • -K, --keepalive-count COUNT: Sets the number of times a message can be sent keep alive without getting a response from the server, and without marking the connection as dead. It will have no effect on this option, if the INTERVAL value of the previous option was set to 0.
  • -l, --log FILE: Directs the operation log output to the file FILE.
  • -q, –quiet: Avoid extra information in messages. Silent mode.
  • -r, --readonly: The initial connection is established in Read only. Same as when we use the option –Readonly in command connect.
  • -t, --timing: Shows the time consumed by each command.
  • -v, –version = short: Ignore any other arguments, and show only the library version libvirt where the program comes from Virsh.
  • -V, –version = long: Ignore any other arguments and show the library version libvirt where the program comes from Virsh and furthermore, the different hypervisors, controllers - drivers, network types, etc. that the compilation supports.

Notes:

  • Most command operations Virsh, suppose that the bookstore libvirt be able to connect to a service libvirtd in action.
  • Most commands require that they be run with user privileges root due to the communication channels it uses to communicate with the Hypervisor. If run with the privileges of a normal user, it will return an error.
  • Most of the commands act synchronously. Possible exceptions are shutdown, setvcpus y setmem. In those cases, the fact that Virsh return the prompt command, it may not mean that the action completed successfully. It should be checked periodically to detect that the operation was completed on the Guest - Guest.

For more information on content, see man virus.

Suggestions on how to approach learning virsh

To make it easier to get help on using the more than 200 commands, Virsh groups them by keywords - help keyword, which are:

  • 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 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.


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 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 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 phy sical 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 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

For specific help on any of the listed commands

We must execute virsh help. Examples:

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 [--mode ] DESCRIPTION Run shutdown in the target domain. OPTIONS [--domain] domain name, id or uuid --mode shutdown mode: acpi | agent | initctl | signal | paravirt

Examples of using the virsh command

Virsh version

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

Enter the virsh console

buzz @ sysadmin: ~ $ sudo virsh
[sudo] password for buzz: Welcome to virsh, the virtualization interactive terminal. Type: 'help' for help with commands 'quit' to quit

List all domains

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

Start the dns domain

virsh# start dns
domain dns started

virsh# domdisplay dns
spice: //127.0.0.1: 5900

List storage volumes

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

List the images contained in a volume

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

Create a disk image on a volume

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

Join the newly created image to a running domain

virsh #domstate dns
running

virsh # domaininfo 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

We partition, format and mount the new disk

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: two 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 / store
buzz @ dns: ~ $ sudo nano / etc / fstab 
/ dev / vdb1 / store ext4 defaults 0 0

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

We return to the virsh console

buzz @ sysadmin: ~ $ sudo virsh Welcome to virsh, the virtualization interactive terminal. Type: 'help' for help with commands 'quit' to quit

virsh# 

We turn off

virsh #domstate dns
running

virsh #shutdown dns
Domain dns is shutdown

Summary

So far we have sailed along the shores of the Virsh Sea. 😉 For more information, execute the command man virus. However, we leave a plain text file called virsh-help.txt that we make to make life easier for those who venture with this Super Command for the administration and management of Hypervisors and their Virtual Machines.

We highly recommend test the commands outside the production environment.


7 comments, leave yours

Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   dhunter said

    I would like to use Virsh for more things, currently only the basics, start, stop, everything else I use virt-manager, I like that you can have N servers running libvirt and manage them from your workstation with virt-manager.

  2.   federico said

    Hello friend Dhunter !!! I'm already at work. Download the file virsh-help.txt which will help you a lot. I made it from the virsh console itself, and then I made a script to fill it. I think that, being organized by the keywords of the help, it is more drinkable. In the next article I touch on more topics of this command.

  3.   Carburus Zodiac said

    Greetings Federico. I have followed your interesting articles on SMEs. It is decidedly easier to use the console for quick and efficient administration. They also consume fewer resources. I wait for your next deliveries.

  4.   crespo88 said

    Well Federico, you already met me. Thank you for this gift that you have given us. Excellent post, I have been waiting for this article on virsh. Thank you brother, we will all know how to use it properly.

  5.   fico said

    You're welcome Crespo88. For that we are in DesdeLinux.

  6.   Ismael Alvarez Wong said

    hello, I was amazed with the potential of the virsh command, I can't find words to describe what I think about it, incredible, and what you expose in the post is just a brushstroke, using your own words «So far we have sailed along the shores of the Virsh Sea. "
    very useful when you explain how to research virsh help using your keywords.
    great developed example of Create a disk image on a volume and Join (add) it to a running domain (or MV), all with virsh; then from our WK sysadmin connect by SSH to the domain and within it, create the partition and its ext4 filesystem to finally mount it from the fstab.
    Nothing to follow with the next posts in the virt qemu-kvm series and thank you very much for sharing all this.

    1.    federico said

      You have gotten the gist of the message, friend Wong. If only with the introduction to the Virsh command, wonders can be done, why not continue with its study and use. virsh It is, by definition, the Qemu-KVM interface, conceived by its creators at Red Hat, Inc and sponsored by that great company. Although we know that there are other interfaces such as Virt-Manager and oVirt, Virsh is still the most complete to handle the library libvirt. Thank you friend Wong for your valuable comments.