Product SiteDocumentation Site

Chapter 3. Connections

3.1. Overview
3.1.1. open
3.1.2. openReadOnly
3.1.3. openAuth
3.1.4. close
3.2. URI formats
3.2.1. Local URIs
3.2.2. Remote URIs
3.3. Capability Information Methods
3.4. Host information
3.4.1. getHostname
3.4.2. getMaxVcpus
3.4.3. getInfo
3.4.4. getCellsFreeMemory
3.4.5. getType
3.4.6. Get Library and Driver Versions
3.4.7. getURI
3.4.8. isEncrypted
3.4.9. isSecure
3.4.10. isAlive
3.4.11. compareCPU
3.4.12. getFreeMemory
3.4.13. getFreePages
3.4.14. getMemoryParameters
3.4.15. getMemoryStats
3.4.16. getSecurityModel
3.4.17. getSysinfo
3.4.18. getCPUMap
3.4.19. getCPUStats
3.4.20. getCPUModelNames
In libvirt, a connection is the underpinning of every action and object in the system. Every entity that wants to interact with libvirt, be it virsh, virt-manager, or a program using the libvirt library, needs to first obtain a connection to the libvirt daemon on the host it is interested in interacting with. A connection describes not only the type of virtualization technology that the agent wants to interact with (qemu, xen, uml, etc), but also describes any authentication methods necessary to connect to that resource.

3.1. Overview

The very first thing a libvirt agent must do is call the virInitialize function, or one of the Python libvirt connection functions to obtain an instance of the virConnect class. This instance will be used in subsequent operations. The Python libvirt module provides 3 different functions for connecting to a resource:
conn = libvirt.open(name)
conn = libvirt.openAuth(uri, auth, flags)
conn = libvirt.openReadOnly(name)
In all three cases there is a name parameter which in fact refers to the URI of the hypervisor to connect to. The previous sections Section 2.2, “Driver model” and Section 3.2.2, “Remote URIs” provide full details on the various URI formats that are acceptable. If the URI is None then libvirt will apply some heuristics and probe for a suitable hypervisor driver. While this may be convenient for developers doing adhoc testing, it is strongly recommended that applications do not rely on probing logic since it may change at any time. Applications should always explicitly request which hypervisor connection is desired by providing a URI.
The difference between the three methods outlined above is the way in which they authenticate and the resulting authorization level they provide.

3.1.1. open

The open function will attempt to open a connection for full read-write access. It does not have any scope for authentication callbacks to be provided, so it will only succeed for connections where authentication can be done based on the credentials of the application.

Example 3.1. Using open

# Example-1.py
#!/usr/bin/env python3
import sys
import libvirt

conn = None
try:
    conn = libvirt.open("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)
conn.close()
exit(0)
The above example opens up a read-write connection to the system qemu hypervisor driver, checks to make sure it was successful, and if so closes the connection. For more information on libvirt URIs, refer to Section 3.2, “URI formats”.

3.1.2. openReadOnly

The openReadOnly function will attempt to open a connection for read-only access. Such a connection has a restricted set of method calls that are allowed, and is typically useful for monitoring applications that should not be allowed to make changes. As with open, this method has no scope for authentication callbacks, so it relies on credentials.

Example 3.2. Using openReadOnly

# Example-2.py
#!/usr/bin/env python3
import sys
import libvirt

conn = None
try:
    conn = libvirt.openReadOnly("qemu:///system")
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)
conn.close()
exit(0)
The above example opens up a read-only connection to the system qemu hypervisor driver, checks to make sure it was successful, and if so closes the connection. For more information on libvirt URIs, refer to Section 3.2, “URI formats”.

3.1.3. openAuth

The openAuth function is the most flexible, and effectively obsoletes the previous two functions. It takes an extra parameter providing an Python list which contains the authentication credentials from the client app. The flags parameter allows the application to request a read-only connection with the VIR_CONNECT_RO flag if desired. A simple example Python program that uses openAuth with username and password credentials follows. As with open, this method has no scope for authentication callbacks, so it relies on credentials.

Example 3.3. Using openAuth

# Example-3.py
#!/usr/bin/env python3
import sys
import libvirt

SASL_USER = "my-super-user"
SASL_PASS = "my-super-pass"

def request_cred(credentials, user_data):
    for credential in credentials:
        if credential[0] == libvirt.VIR_CRED_AUTHNAME:
            credential[4] = SASL_USER
        elif credential[0] == libvirt.VIR_CRED_PASSPHRASE:
            credential[4] = SASL_PASS
    return 0

auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_PASSPHRASE], request_cred, None]

conn = None
try:
    conn = libvirt.openAuth('qemu+tcp://localhost/system', auth, 0)
except libvirt.libvirtError as e:
    print(repr(e), file=sys.stderr)
    exit(1)
conn.close()
exit(0)
To test the above program, the following configuration must be present:
  1. /etc/libvirt/libvirtd.conf
    listen_tls = 0
    listen_tcp = 1
    auth_tcp = "sasl"
  2. /etc/sasl2/libvirt.conf
    mech_list: digest-md5
  3. A virt user has been added to the SASL database:
    $ saslpasswd2 -a libvirt virt
    Password:
    Again (for verification):
  4. libvirtd has been started with --listen
Once the above is configured, Example 3.3, “Using openAuth” can utilize the configured username and password and allow read-write access to libvirtd.
Unlike the libvirt C interface, Python does not provide for custom callbacks to gather credentials.

3.1.4. close

A connection must be released by calling the close method of the virConnection class when no longer required. Connections are reference counted objects, so there should be a corresponding call to the close method for each open function call.
Connections are reference counted; the count is explicitly increased by the initial (open, openAuth, and the like); it is also temporarily increased by other methods that depend on the connection remaining alive. The open function call should have a matching close, and all other references will be released after the corresponding operation completes.
In Python reference counts can be automatically decreased when an class instance goes out of scope or when the program ends.

Example 3.4. Using close with additional references

# Example-5.py
#!/usr/bin/env python3
import sys
import libvirt

conn1 = libvirt.open('qemu:///system')
if conn1 == None:
    print('Failed to open connection to qemu:///system', file=sys.stderr)
    exit(1)
conn2 = libvirt.open('qemu:///system')
if conn2 == None:
    print('Failed to open connection to qemu:///system', file=sys.stderr)
    exit(1)
conn1.close()
conn2.close()
exit(0)
Also note that every other class instance associated with a connection (virDomain, virNetwork, etc) will also hold a reference on the connection.