Libvirt Compute Driver Documentation

Note

Libvirt driver in current version of Libcloud is still experimental and doesn’t support advanced functionality like creating a node and so on.

libvirt is an open source toolkit for managing different hypervisors. It ca be used to manage Xen, KVM, Vmware ESX, QEMU and many other hypervisors.

../../_images/libvirt.png

For full list of the supported hypervisors, please see the Hypervisor drivers page.

Requirements

To be able to use this driver you need to install libvirt client and libvirt-python Python package.

Libvirt client is available in standard package repositories of most popular Linux distributions which means you can install it using your distribution’s package manager.

Example #1 - Ubuntu, Debian, etc. (apt-get):

sudo apt-get install libvirt-client

Example #2 - Fedora, RHEL, etc. (yum):

sudo yum install libvirt-client

Python package can be installed using pip:

pip install libvirt-python

Connecting to a hypervisor

To instantiate the driver and connect to a hypervisor, you need to pass uri argument to the driver constructor.

This argument tells the driver which libvirt driver (qemu, xen, virtualbox, etc.) this connection refers to. For a full list of supported URIs, please refer to the Connection URIs <http://libvirt.org/uri.html> page.

Example 1 - Connecting to QEMU and KVM hypervisor

This example shows how to connect to a local QEMU or KVM instance.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

cls = get_driver(Provider.LIBVIRT)
driver = cls(uri='qemu:///system')

For more details and information on how to connect to a remote instance, please see Connections to QEMU driver page.

Example 2 - Connecting to Virtualbox hypervisor

This example shows how to connect to a local Virtualbox instance.

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

cls = get_driver(Provider.LIBVIRT)
driver = cls(uri='vbox:///session')

For more details and information on how to connect to a remote instance, please see VirtualBox hypervisor driver page.

Enabling libvirt debug mode

To enable libvirt debug mode, simply set LIBVIRT_DEBUG environment variable.

For example:

LIBVIRT_DEBUG=1 python my_script.py

When debug mode is enabled, libvirt client will print all kind of debugging information to the standard error.

API Docs

class libcloud.compute.drivers.libvirt_driver.LibvirtNodeDriver(uri)[source]

Libvirt (http://libvirt.org/) node driver.

To enable debug mode, set LIBVIR_DEBUG environment variable.

Parameters:uri (str) – Hypervisor URI (e.g. vbox:///session, qemu:///system, etc.).
attach_volume(node, volume, device=None)

Attaches volume to node.

Parameters:
  • node (Node) – Node to attach volume to.
  • volume (StorageVolume) – Volume to attach.
  • device (str) – Where the device is exposed, e.g. ‘/dev/sdb’
Rytpe:

bool

connectionCls

alias of ConnectionKey

copy_image(source_region, node_image, name, description=None)

Copies an image from a source region to the current region.

Parameters:
  • source_region (str) – Region to copy the node from.
  • node_image (NodeImage:) – NodeImage to copy.
  • name (str) – name for new image.
  • description – description for new image.
Return type:

NodeImage:

Returns:

NodeImage instance on success.

create_image(node, name, description=None)

Creates an image from a node object.

Parameters:
  • node (Node) – Node to run the task on.
  • name (description) – name for new image.
  • description – description for new image.
Return type:

NodeImage:

Returns:

NodeImage instance on success.

create_key_pair(name)

Create a new key pair object.

Parameters:name (str) – Key pair name.
create_node(**kwargs)

Create a new node instance. This instance will be started automatically.

Not all hosting API’s are created equal and to allow libcloud to support as many as possible there are some standard supported variations of create_node. These are declared using a features API. You can inspect driver.features['create_node'] to see what variation of the API you are dealing with:

ssh_key
You can inject a public key into a new node allows key based SSH authentication.
password
You can inject a password into a new node for SSH authentication. If no password is provided libcloud will generated a password. The password will be available as return_value.extra['password'].
generates_password
The hosting provider will generate a password. It will be returned to you via return_value.extra['password'].

Some drivers allow you to set how you will authenticate with the instance that is created. You can inject this initial authentication information via the auth parameter.

If a driver supports the ssh_key feature flag for created_node you can upload a public key into the new instance:

>>> from libcloud.compute.drivers.dummy import DummyNodeDriver
>>> driver = DummyNodeDriver(0)
>>> auth = NodeAuthSSHKey('pubkey data here')
>>> node = driver.create_node("test_node", auth=auth)

If a driver supports the password feature flag for create_node you can set a password:

>>> driver = DummyNodeDriver(0)
>>> auth = NodeAuthPassword('mysecretpassword')
>>> node = driver.create_node("test_node", auth=auth)

If a driver supports the password feature and you don’t provide the auth argument libcloud will assign a password:

>>> driver = DummyNodeDriver(0)
>>> node = driver.create_node("test_node")
>>> password = node.extra['password']

A password will also be returned in this way for drivers that declare the generates_password feature, though in that case the password is actually provided to the driver API by the hosting provider rather than generated by libcloud.

You can only pass a NodeAuthPassword or NodeAuthSSHKey to create_node via the auth parameter if has the corresponding feature flag.

Parameters:
  • name (str) – String with a name for this new node (required)
  • size (NodeSize) – The size of resources allocated to this node. (required)
  • image (NodeImage) – OS Image to boot on node. (required)
  • location (NodeLocation) – Which data center to create a node in. If empty, undefined behavior will be selected. (optional)
  • auth (NodeAuthSSHKey or NodeAuthPassword) – Initial authentication information for the node (optional)
Returns:

The newly created node.

Return type:

Node

create_volume(size, name, location=None, snapshot=None)

Create a new volume.

Parameters:
  • size (int) – Size of volume in gigabytes (required)
  • name (str) – Name of the volume to be created
  • location (NodeLocation) – Which data center to create a volume in. If empty, undefined behavior will be selected. (optional)
  • snapshot (str) – Name of snapshot from which to create the new volume. (optional)
Returns:

The newly created volume.

Return type:

StorageVolume

create_volume_snapshot(volume, name)

Creates a snapshot of the storage volume.

Return type:VolumeSnapshot
delete_image(node_image)

Deletes a node image from a provider.

Parameters:node_image (NodeImage) – Node image object.
Returns:True if delete_image was successful, False otherwise.
Return type:bool
delete_key_pair(key_pair)

Delete an existing key pair.

Parameters:key_pair (KeyPair) – Key pair object.
deploy_node(**kwargs)

Create a new node, and start deployment.

In order to be able to SSH into a created node access credentials are required.

A user can pass either a NodeAuthPassword or NodeAuthSSHKey to the auth argument. If the create_node implementation supports that kind if credential (as declared in self.features['create_node']) then it is passed on to create_node. Otherwise it is not passed on to create_node and it is only used for authentication.

If the auth parameter is not supplied but the driver declares it supports generates_password then the password returned by create_node will be used to SSH into the server.

Finally, if the ssh_key_file is supplied that key will be used to SSH into the server.

This function may raise a DeploymentException, if a create_node call was successful, but there is a later error (like SSH failing or timing out). This exception includes a Node object which you may want to destroy if incomplete deployments are not desirable.

>>> from libcloud.compute.drivers.dummy import DummyNodeDriver
>>> from libcloud.compute.deployment import ScriptDeployment
>>> from libcloud.compute.deployment import MultiStepDeployment
>>> from libcloud.compute.base import NodeAuthSSHKey
>>> driver = DummyNodeDriver(0)
>>> key = NodeAuthSSHKey('...') # read from file
>>> script = ScriptDeployment("yum -y install emacs strace tcpdump")
>>> msd = MultiStepDeployment([key, script])
>>> def d():
...     try:
...         driver.deploy_node(deploy=msd)
...     except NotImplementedError:
...         print ("not implemented for dummy driver")
>>> d()
not implemented for dummy driver

Deploy node is typically not overridden in subclasses. The existing implementation should be able to handle most such.

Parameters:
  • deploy (Deployment) – Deployment to run once machine is online and available to SSH.
  • ssh_username (str) – Optional name of the account which is used when connecting to SSH server (default is root)
  • ssh_alternate_usernames (list) – Optional list of ssh usernames to try to connect with if using the default one fails
  • ssh_port (int) – Optional SSH server port (default is 22)
  • ssh_timeout (float) – Optional SSH connection timeout in seconds (default is 10)
  • auth (NodeAuthSSHKey or NodeAuthPassword) – Initial authentication information for the node (optional)
  • ssh_key (str or list of str) – A path (or paths) to an SSH private key with which to attempt to authenticate. (optional)
  • timeout (int) – How many seconds to wait before timing out. (default is 600)
  • max_tries (int) – How many times to retry if a deployment fails before giving up (default is 3)
  • ssh_interface (str) – The interface to wait for. Default is ‘public_ips’, other option is ‘private_ips’.
destroy_volume(volume)

Destroys a storage volume.

Parameters:volume (StorageVolume) – Volume to be destroyed
Return type:bool
destroy_volume_snapshot(snapshot)

Destroys a snapshot.

Return type:bool
detach_volume(volume)

Detaches a volume from a node.

Parameters:volume (StorageVolume) – Volume to be detached
Return type:bool
ex_get_hypervisor_hostname()[source]

Return a system hostname on which the hypervisor is running.

ex_get_hypervisor_sysinfo()[source]

Retrieve hypervisor system information.

Return type:dict
ex_resume_node(node)[source]

Resume a suspended node.

Parameters:node (Node) – Node which should be used
Return type:bool
ex_shutdown_node(node)[source]

Shutdown a running node.

Note: Usually this will result in sending an ACPI event to the node.

Parameters:node (Node) – Node which should be used
Return type:bool
ex_start_node(node)[source]

Start a stopped node.

Parameters:node (Node) – Node which should be used
Return type:bool
ex_suspend_node(node)[source]

Suspend a running node.

Parameters:node (Node) – Node which should be used
Return type:bool
ex_take_node_screenshot(node, directory, screen=0)[source]

Take a screenshot of a monitoring of a running instance.

Parameters:
  • node (libcloud.compute.base.Node) – Node to take the screenshot of.
  • directory (str) – Path where the screenshot will be saved.
  • screen (int) – ID of the monitor to take the screenshot of.
Returns:

Full path where the screenshot has been saved.

Return type:

str

get_image(image_id)

Returns a single node image from a provider.

Parameters:image_id (str) – Node to run the task on.

:rtype NodeImage: :return: NodeImage instance on success.

get_key_pair(name)

Retrieve a single key pair.

Parameters:name (str) – Name of the key pair to retrieve.
Return type:KeyPair
import_key_pair_from_file(name, key_file_path)

Import a new public key from string.

Parameters:
  • name (str) – Key pair name.
  • key_file_path (str) – Path to the public key file.
Return type:

KeyPair object

import_key_pair_from_string(name, key_material)

Import a new public key from string.

Parameters:
  • name (str) – Key pair name.
  • key_material (str) – Public key material.
Return type:

KeyPair object

list_images(location=None)

List images on a provider.

Parameters:location (NodeLocation) – The location at which to list images.
Returns:list of node image objects.
Return type:list of NodeImage
list_key_pairs()

List all the available key pair objects.

Return type:list of KeyPair objects
list_locations()

List data centers for a provider

Returns:list of node location objects
Return type:list of NodeLocation
list_sizes(location=None)

List sizes on a provider

Parameters:location (NodeLocation) – The location at which to list sizes
Returns:list of node size objects
Return type:list of NodeSize
list_volume_snapshots(volume)

List snapshots for a storage volume.

Return type:list of VolumeSnapshot
list_volumes()

List storage volumes.

Return type:list of StorageVolume
wait_until_running(nodes, wait_period=3, timeout=600, ssh_interface='public_ips', force_ipv4=True)

Block until the provided nodes are considered running.

Node is considered running when it’s state is “running” and when it has at least one IP address assigned.

Parameters:
  • nodes (list of Node) – List of nodes to wait for.
  • wait_period (int) – How many seconds to wait between each loop iteration. (default is 3)
  • timeout (int) – How many seconds to wait before giving up. (default is 600)
  • ssh_interface (str) – Which attribute on the node to use to obtain an IP address. Valid options: public_ips, private_ips. Default is public_ips.
  • force_ipv4 (bool) – Ignore IPv6 addresses (default is True).
Returns:

[(Node, ip_addresses)] list of tuple of Node instance and list of ip_address on success.

Return type:

list of tuple