Monday, March 10, 2014

Extending the virt-xml command line

Edit May 2019: This tutorial is out of date. A modern version is on the virt-manager github wiki: https://github.com/virt-manager/virt-manager/wiki/Extending-the-command-line

As previously explained, virt-manager 1.0.0 shipped with a tool called virt-xml, which enables editing libvirt XML from the command line in one shot. This post will walk through an example of patching virt-xml to support a new libvirt XML value.

A bit of background: libvirt VM configuration is in XML format. It has quite an extensive XML schema. For QEMU/KVM guests, most of the XML attributes map to qemu command line values. QEMU is always adding new emulated hardware and new features, which in turn require the XML schema to be extended. Example: this recent libvirt change to allow turning off Spice drag + drop support with a <filetransfer enable='no'/> option.

For this example, we are going to expose a different property: defaultMode, also part of the graphics device. defaultMode can be used to tell qemu to open all spice channels in secure TLS mode. But for the purpose of this example, what defaultMode actually does and how it works isn't important. For virt-xml, the only important bit is getting the value for the command line, writing it correctly as XML, and unit testing the XML generation.

You can see the completed virt-xml git commit over here.



Step 0: Run the test suite

The virt-manager test suite aims to always 100% pass, but depending on your host libvirt version things can occasionally be broken. Run 'python setup.py test' and note if any tests fail. The important bit here is that after we make all the following changes, the test suite shouldn't regress at all.


Step 1: XML generation

 diff --git a/virtinst/devicegraphics.py b/virtinst/devicegraphics.py  
 index 37f268a..a87b71c 100644  
 --- a/virtinst/devicegraphics.py  
 +++ b/virtinst/devicegraphics.py  
 @@ -204,6 +204,7 @@ class VirtualGraphics(VirtualDevice):  
    passwdValidTo = XMLProperty("./@passwdValidTo")  
    socket = XMLProperty("./@socket")  
    connected = XMLProperty("./@connected")  
 +  defaultMode = XMLProperty("./@defaultMode")

    listens = XMLChildProperty(_GraphicsListen)  
    def remove_listen(self, obj):  

Starting with virt-manager git, first we extend the internal API to map a python class property to its associated XML value.

The virtinst/ directory contains the internal XML building API used by all the tools shipped with virt-manager. There's generally a single file and class per XML object, examples
  • devicegraphics.py: <graphics> device
  • cpu.py: <cpu> block
  • osxml.py: <os> block
  • And so on
If you aren't sure what file or class you need to alter, try grepping for a property you know that virt-install already supports. So, for example, using virt-install --graphics=? I see that there's a property named passwdValidTo. Doing 'git grep passwdValidTo' will point to virtinst/devicegraphics.py

'XMLProperty' is some custom glue that maps a python class property to an XML value, for both reading and writing. The value passed to XMLProperty is an XML xpath. If you don't know how xpaths work, google around, or try to find an existing example in the virtinst code.

Notice that this doesn't do much else, like validate that the value passed to defaultMode is actually valid. The general rule is to leave this up to libvirt to complain.


Step 2: Command line handling

 diff --git a/virtinst/cli.py b/virtinst/cli.py  
 index 826663a..41d6a8c 100644  
 --- a/virtinst/cli.py  
 +++ b/virtinst/cli.py  
 @@ -1810,6 +1810,7 @@ class ParserGraphics(VirtCLIParser):  
      self.set_param("passwd", "password")  
      self.set_param("passwdValidTo", "passwordvalidto")  
      self.set_param("connected", "connected")  
 +    self.set_param("defaultMode", "defaultMode")  
    
    def _parse(self, opts, inst):  
      if opts.fullopts == "none":  

The next step is to set up command line handling. In this case we are adding a sub option to the --graphics command. Open up virtinst/cli.py and search for '--graphics', you'll find a comment with a ParserGraphics class defined after it. That's where we plug in new sub options.

The 'self.set_param' registers the sub option: first argument is the name on the cli, second argument is the property name we defined above. In this case they are the same.

Some options do extra validation or need to do special handling. If you need extra functionality, look at examples that pass setter_cb to set_param.

After this bit is applied, you'll see defaultMode appear in the --graphics=? output, and everything will work as expected. But we need to add a unit test to validate the XML generation.

An easy way to test that this is working is with a command line like:

./virt-install --connect test:///default --name foo --ram 64 \
               --nodisks --boot network --print-xml \
               --graphics spice,defaultMode=secure

That will use libvirt's 'test' driver, which is made for unit testing, and doesn't affect the host at all. The --print-xml command will output the new XML. Verify that your new command line option works as expected before continuing. See the HACKING file for additional tips for using the test driver.


Step 3: Unit test XML generation

 diff --git a/tests/xmlparse.py b/tests/xmlparse.py  
 index a2448d2..397da45 100644  
 --- a/tests/xmlparse.py  
 +++ b/tests/xmlparse.py  
 @@ -559,6 +559,7 @@ class XMLParseTest(unittest.TestCase):  
      check("channel_cursor_mode", "any", "any")  
      check("channel_playback_mode", "any", "insecure")  
      check("passwdValidTo", "2010-04-09T15:51:00", "2011-01-07T19:08:00")  
 +    check("defaultMode", None, "secure")  
    
      self._alter_compare(guest.get_xml_config(), outfile)  

tests/xmlparse.py tests reading and writing, so it will test the change we made in virtinst/devicegraphics.py. Before you make any tests/, run 'python setup.py test --testfile xmlparse.py', you should see a new error: this is because xmlparse.py will emit a test failure if a new XML property in virtinst/ that isn't explicitly tested!

Similar to how you found what virtinst/ file to edit by grepping for a known graphics property like passwdValidTo, do the same in xmlparse.py to find the pre-existing graphics test function. The check() invocation is a small wrapper for setting and reading a value: the first argument is the python property name we are poking, the second argument is what the initial value should be, and the final argument is the new value we are setting.

The initial XML comes from tests/xmlparse-xml/*, and is initialized at the start of the function. But in our case, we don't need to manually alter that. So make the change, and rerun 'python setup.py test --testfile xmlparse.py' and...

Things broke! That's because the generated XML output changed, and contains our new defaultMode value. So we need to update the known-good XML files we compare against. The easiest way to do that is to run 'python setup.py test --testfile xmlparse.py --regenerate-output'. Run 'git diff' afterwards to ensure that only the graphics file was changed.

Finally, run 'python setup.py test' and ensure the rest of the test suite doesn't regress compared to the initial run you did in Step 0.

For cases where you added non-trivial command line handling, take a look at tests/clitest.py, where we run a battery of command line parsing tests. You likely want to extend this to verify your command line works as expected.

Also, if you want to add an entirely new command line option that maps to an XML block, this commit adding the --memtune option is a good reference.


Step 4) Documentation?

For each new option sub property, the general rule is we don't need to explicitly list it in the man page or virt-install/virt-xml --help output. The idea is that command line introspection and libvirt XML documentation should be sufficient. However, if your command line option has some special behavior, or is particularly important, consider extending man/virt-install.pod.


Step 5) Submit the patch!

So your patch is done! git commit -a && git send-email -1 --to virt-tools-list@redhat.com or simply drop it in a bug report. If you have any questions or need any assitance, drop us a line.

(update 2015-09-04: Point git links to github)

Tuesday, March 4, 2014

virt-xml: Edit libvirt XML from the command line

We shipped a new tool with virt-manager 1.0.0 called virt-xml. virt-xml uses virt-install's command line options to allow building and editing libvirt domain XML. A few basic examples:

Change the <description> of domain 'example':
# virt-xml example --edit --metadata description="my new description"  

Enable the boot device menu for domain 'example':
# virt-xml example --edit --boot bootmenu=on  

Hotplug host USB device 001.003 to running domain 'fedora19':
# virt-xml f19 --add-device --host-device 001.003 --update

The virt-xml man page also has a comprehensive set of examples.

While I doubt anyone would call it sexy, virt-xml fills a real need in the libvirt ecosystem. Prior to virt-xml, a question like 'how do I change the cache mode for my VM disk' had two possible answers:

1) Use 'virsh edit'

'virsh edit' drops you into $EDITOR and allows you to edit the XML manually. Now ignoring the fact that editing XML by hand is a pain, 'virsh edit' requires the user to know the exact XML attribute or property name, and where to put it. And if its in the wrong place or mis-named, in most cases libvirt will happily ignore it with no feedback (this is actually useful at the API level but not very friendly for direct user interaction).

But more than that, have you ever seen what happens when you drop a less than savvy user into vim for the first time? It doesn't end well :) And this happens more than you might expect.

2) Use virt-manager

The more newbie friendly option for sure, the UI is intuitive enough that people can usually find the XML bit they want to twiddle... provided it actually exists in virt-manager.

And that's the problem: over time these types of requests put pressure on virt-manager to expose many kind-of-obscure-but-not-so-obscure-that-virsh-edit-is-an-acceptable-answer XML properties in the UI. It was unclear where to draw the line on what should be in the UI and what shouldn't, and we ended up with various UI bits that very few people were actually interacting with.

Enter virt-xml

So here's virt-xml, that allows us to easily make these types of XML changes with a single command. This takes the pressure off virt-manager, and provides a friendly middle ground between the GUI and 'virsh edit'. It also greatly simplifies documentation and wiki pages (like fedora test day test cases).

The CLI API surface is huge compared to virt-manager's UI. There's no reason that virt-xml can't expand to support every XML property exposed by libvirt. And we've worked on making it trivially easy to to extend the tool to handle new XML options: in many cases, it's only 3 lines of code to add a new --disk/--network/... sub option, including unit testing, command line introspection, and virt-install support.

Thursday, February 27, 2014

virt-install command line introspection

A new feature shipped with virt-manager 1.0.0 is simple command line introspection for virt-install and virt-xml.

Basically, any of the compound options like --disk or --graphics that take sub arguments of the form opt1=val1,opt2=val2,... will print all their sub arguments if invoked like --disk=? or --graphics=help. Example:

 $ virt-install --disk=? --network=help  
 --disk options:  
  backing_store  
  boot_order  
  bus  
  cache  
  clearxml  
  device  
  driver_name  
  driver_type  
  error_policy  
  format  
  io  
  path  
  pool  
  read_bytes_sec  
  read_iops_sec  
  readonly  
  removable  
  serial  
  shareable  
  size  
  sparse  
  startup_policy  
  target  
  total_bytes_sec  
  total_iops_sec  
  vol  
  write_bytes_sec  
  write_iops_sec
  
 --network options:  
  boot_order  
  clearxml  
  driver_name  
  driver_queues  
  filterref  
  mac  
  model  
  source  
  source_mode  
  target  
  type  
  virtualport_instanceid  
  virtualport_managerid  
  virtualport_type  
  virtualport_typeid  
  virtualport_typeidversion  

We aim to document common bits in the virt-install man page, but for less commonly used options it's better to see the official libvirt XML documenation.

Friday, February 14, 2014

virt-manager 1.0.0 released!

I'm happy to announce the release of virt-manager 1.0.0!

Our version numbers were starting to get awkward, and this release was suitably featureful, so it felt like time to bump the major version. (And it's trendy these days, right?).

virt-manager is a desktop application for managing KVM, Xen, and LXC virtualization via libvirt.

The release can be downloaded from:

http://virt-manager.org/download/

The direct download links are:

http://virt-manager.org/download/sources/virt-manager/virt-manager-1.0.0.tar.gz

This release includes:

- virt-manager: Snapshot support
- New tool virt-xml: Edit libvirt XML in one shot from the command line:
http://www.redhat.com/archives/libvir-list/2014-January/msg01226.html
- Improved defaults: qcow2, USB2, host CPU model, guest agent channel, ...
- Introspect command line options like --disk=? or --network=help
- The virt-image tool will be removed before the next release, speak up
if you have a good reason not to remove it.
- virt-manager: Support arm vexpress VM creation
- virt-manager: Add guest memory usage graphs (Thorsten Behrens)
- virt-manager: UI for editing devices (Cédric Bosdonnat)
- Spice USB redirection support (Guannan Ren)
- tpm  UI and command line support (Stefan Berger)
- rng UI and command line support (Giuseppe Scrivano)
- panic UI and command line support (Chen Hanxiao)
- blkiotune command line support (Chen Hanxiao)
- virt-manager: support for glusterfs storage pools (Giuseppe Scrivano)
- cli: New options --memory, --features, --clock, --metadata, --pm
- Greatly improve app responsiveness when connecting to remote hosts
- Lots of UI cleanup and improvements 


Over the next few weeks I'll be on writing a bit more in depth about some of the above changes.

Tuesday, December 3, 2013

KVM migration from Fedora 17 to Fedora 21+ is not supported

With qemu 1.7.0 in rawhide/Fedora 21, we've dropped some non-upstream back compatibility patches that allow migration from Fedora 17 vintage qemu and earlier.

This affects not just live migration (which I doubt anyone cares about in this context), but also any qemu memory snapshots or libvirt 'save' data created on <= F17. Trying to restore this data on F21 will not work.

In reality I don't expect this to affect anybody really. If you have saved data or snapshots that are important, you can load/restore them on Fedora 20, fully poweroff the VM, virsh edit and change the machine= value to something newer like pc-1.6, start the VM, and recreate the data to the best of your ability. save data/memory snapshots created on F20 will load correctly on F21. I realize this isn't ideal but hopefully no one is affected and it doesn't matter in practice.

Some background: In Fedora 17 and earlier, we shipped a qemu package based on qemu-kvm.git, which was a fork of qemu.git containing KVM support and a few other bits. Over time the QEMU and KVM community worked to merge all the forked bits into mainline qemu, which was fully completed with the qemu 1.3 release. Fedora 18 was the first Fedora release to ship this merged codebase

Unfortunately, qemu-kvm.git had accumulated some unintentional incompatibilities with qemu.git: minor internal bits that affected migration but had little other functional impact. The end result was that a qemu-kvm-1.2 guest could not be migrated to the new merged qemu-1.3.

This sucked for Fedora where we had always shipped qemu-kvm.git: migration/saves/snapshots made on Fedora 17 would not work on Fedora 18, and there would be no easy upgrade path. So we decided to maintain this migration back compatibility with qemu-kvm.git. However this required non-upstream patches, which we obviously do not want to carry forever.

I think after 3 stable releases (F20 is out soon enough) this shouldn't have much practical impact, so bye bye non-upstream patches :)