Table of Contents
This chapter describes how to use the Xen Enterprise Management API from real programs to manage XenServer hosts and VMs. The chapter begins with a walk-through of a typical client application and demonstrates how the API can be used to perform common tasks. Example code fragments are given in python syntax but equivalent code in C and C# would look very similar. The language bindings themselves are discussed afterwards and the chapter finishes with walk-throughs of two complete examples included in the SDK.
This section describes the structure of a typical application using the Xen Enterprise Management API. Most client applications begin by connecting to a XenServer host and authenticating (e.g. with a username and password). Assuming the authentication succeeds, the server will create a "session" object and return a reference to the client. This reference will be passed as an argument to all future API calls. Once authenticated, the client may search for references to other useful objects (e.g. XenServer hosts, VMs etc) and invoke operations on them. Operations may be invoked either synchronously or asynchronously; special task objects represent the state and progress of asynchronous operations. These application elements are all described in detail in the following sections.
API calls can be issued over two transports:
/var/xapi/xapi
The SSL-encrypted TCP transport is used for all off-host traffic while the Unix domain socket can be used from services running directly on the XenServer server itself. In the SSL-encrypted TCP transport, all API calls should be directed at the Resource Pool master; failure to do so will result in the error HOST_IS_SLAVE
, which includes the IP address of the master as an error parameter.
As a special-case, all messages sent through the Unix domain socket are transparently forwarded to the correct node.
The vast majority of API calls take a session reference as their first parameter; failure to supply a valid reference will result in a SESSION_INVALID
error being returned. A session reference is acquired by supplying a username and password to the login_with_password function.
As a special-case, if this call is executed over the local Unix domain socket then the username and password are ignored and the call always succeeds.
Every session has an associated "last active" timestamp which is updated on every API call. The server software currently has a built-in limit of 200 active sessions and will remove those with the oldest "last active" field if this limit is exceeded. In addition all sessions whose "last active" field is older than 24 hours are also removed. Therefore it is important to:
SESSION_INVALID
error is caught.In the following fragment a connection via the Unix domain socket is established and a session created:
import XenAPI session = XenAPI.xapi_local() try: session.xenapi.login_with_password("root", "") ... finally: session.xenapi.session.logout()
Once an application has authenticated the next step is to acquire references to objects in order to query their state or invoke operations on them. All objects have a set of "implicit" messages which include the following:
For example, to list all hosts:
hosts = session.xenapi.host.get_all()
To find all VMs with the name "my first VM":
vms = session.xenapi.VM.get_by_name_label('my first VM')
Object name_label
fields are not guaranteed to be unique and so the get_by_name_label API call returns a set of references rather than a single reference.
In addition to the methods of finding objects described above, most objects also contain references to other objects within fields. For example it is possible to find the set of VMs running on a particular host by calling:
vms = session.xenapi.host.get_resident_VMs(host)
Once object references have been acquired, operations may be invoked on them. For example to start a VM:
session.xenapi.VM.start(vm, False, False)
All API calls are by default synchronous and will not return until the operation has completed or failed. For example in the case of VM.start the call does not return until the VM has started booting.
When the VM.start call returns the VM will be booting. To determine when the booting has finished, wait for the in-guest agent to report internal statistics through the VM_guest_metrics object
To simplify managing operations which take quite a long time (e.g. VM.clone and VM.copy) functions are available in two forms: synchronous (the default) and asynchronous. Each asynchronous function returns a reference to a task object which contains information about the in-progress operation including:
An application which wanted to track the progress of a VM.clone operation and display a progress bar would have code like the following:
vm = session.xenapi.VM.get_by_name_label('my vm') task = session.xenapi.Async.VM.clone(vm) while session.xenapi.Task.get_status(task) == "pending": progress = session.xenapi.Task.get_progress(task) update_progress_bar(progress) time.sleep(1) session.xenapi.Task.destroy(task)
Note that a well-behaved client should remember to delete tasks created by asynchronous operations when it has finished reading the result or error. If the number of tasks exceeds a built-in threshold then the server will delete the oldest of the completed tasks.
With the exception of the task and metrics classes, whenever an object is modified the server generates an event. Clients can subscribe to this event stream on a per-class basis and receive updates rather than resorting to frequent polling. Events come in three types:
add
: generated when an object has been created;del
: generated immediately before an object is destroyed; andmod
: generated when an object's field has changed.Events also contain a monotonically increasing ID, the name of the class of object and a snapshot of the object state equivalent to the result of a get_record().
Clients register for events by calling event.register() with a list of class names or the special string "*". Clients receive events by executing event.next() which blocks until events are available and returns the new events.
Since the queue of generated events on the server is of finite length a very slow client might fail to read the events fast enough; if this happens an EVENTS_LOST
error is returned. Clients should be prepared to handle this by re-registering for events and checking that the condition they are waiting for hasn't become true while they were unregistered.
The following python code fragment demonstrates how to print a summary of every event generated by a system: (similar code exists in /SDK/client-examples/python/watch-all-events.py
)
fmt = "%8s %20s %5s %s" session.xenapi.event.register(["*"]) while True: try: for event in session.xenapi.event.next(): name = "(unknown)" if "snapshot" in event.keys(): snapshot = event["snapshot"] if "name_label" in snapshot.keys(): name = snapshot["name_label"] print fmt % (event['id'], event['class'], event['operation'], name) except XenAPI.Failure, e: if e.details == [ "EVENTS_LOST" ]: print "Caught EVENTS_LOST; should reregister"
Although it is possible to write applications which use the Xen Enterprise Management API directly through raw XML-RPC calls, the task of developing third-party applications is greatly simplified through the use of a language binding which exposes the individual API calls as first-class functions in the target language. The SDK includes language bindings and example code for the C, C# and python programming languages and for both Linux and Windows clients.
The SDK includes the source to the C language binding in the directory /SDK/client-examples/c
together with a Makefile which compiles the binding into a library. Every API object is associated with a header file which contains declarations for all that object's API functions; for example the type definitions and functions required to invoke VM operations are all contained with xen_vm.h
.
Table 4.1. C binding dependencies
Platform supported: | Linux |
Library: | The language binding is generated as a "libxen.a" that is linked by C programs. |
Dependencies: |
|
One simple example is included within the SDK called test_vm_ops. The example demonstrates how to query the capabilities of a host, create a VM, attach a fresh blank disk image to the VM and then perform various powercycle operations.
The C# bindings are contained within the directory /SDK/client-examples/csharp/XenSdk.net
and include project files suitable for building under Microsoft Visual Studio. Every API object is associated with one C# file; for example the functions implementing the VM operations are contained within the file VM.cs
.
Table 4.2. C# binding dependencies
Platform supported: | Windows with .NET version 2.0 |
Library: | The language binding is generated as a Dynamic Link Library Xenapi.dll that is linked by C# programs |
Dependencies: | CookComputing.XMLRpcV2.dll is needed for the xenapi.dll to be able to communicate with the xml-rpc server. |
Two simple examples are included with the C# bindings in the directory /SDK/client-examples/csharp/XenSdk.net
:
The python bindings are contained within a single file: /SDK/client-examples/python/XenAPI.py
.
Table 4.3. Python binding dependencies
Platform supported: | Linux |
Library: | XenAPI.py |
Dependencies: | None |
The SDK includes 7 python examples:
Rather than using raw XML-RPC or one of the supplied language bindings, third-party software developers may instead integrate with XenServer Host hosts by using the XE CLI xe.exe.
Table 4.4. CLI dependencies
Platform supported: | Linux and Windows |
Library: | None |
Binary: | xe[.exe] |
Dependencies: | None |
The CLI allows almost every API call to be directly invoked from a script or other program, silently taking care of the required session management. The XE CLI syntax and capabilities are described in detail in Chapter 5 of the XenServer Administrator's Guide. The SDK contains 3 example bash shell scripts which demonstrate CLI usage. These are:
When running the CLI from a XenServer Host host console, tab-completion of both command names and arguments is available.