xen

XenAPI方式:

#!/usr/bin/python
from  xen . xm . XenAPI  import  Session

session = Session ( 'httpu:///var/run/xend/xen-api.sock' )
try :
    session . login_with_password ( '' ,  '' )
    xenapi = session . xenapi
     #print xenapi.VM.get_all_records()
     #print xenapi.VM_metrics.get_all_records()
     print  xenapi . VM . get_all ()
     print  xenapi . host . get_all ()
    vm = xenapi . VM . get_by_name_label ( 'vmu' )[ 0 ]
    xenapi . VM . start ( vm , False )
    
finally :
    session . xenapi . session . logout ()

xmlrpc方式:


import xmlrpclib

server = xmlrpclib.ServerProxy("http://localhost:9363")
#server.xend.domains_with_state(True, 'all', 0)
session = server.session.login_with_password("","")['Value']
print 'All hosts:'
print server.host.get_all(session)['Value']
print server.system.listMethods()

server.VM.start(session,'265f5563-8881-232a-8ecf-7ff49ab6bc93',False)
 
从其他机器访问会得到connection refused错误。
 
参考:

Table of Contents

4.1. Anatomy of a typical application
4.1.1. Choosing a low-level transport
4.1.2. Authentication and session handling
4.1.3. Finding references to useful objects
4.1.4. Invoking synchronous operations on objects
4.1.5. Using Tasks to manage asynchronous operations
4.1.6. Subscribing to and listening for events
4.1.7. C
4.1.8. C#
4.1.9. Python
4.1.10. Command Line Interface (CLI)
4.2. Complete application examples
4.2.1. Simultaneously migrating VMs using XenMotion
4.2.2. Cloning a VM via the XE CLI

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.

4.1. Anatomy of a typical application

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.

4.1.1. Choosing a low-level transport

API calls can be issued over two transports:

  • SSL-encrypted TCP on port 443 (https) over an IP network
  • plaintext over a local Unix domain socket: /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.

Note

As a special-case, all messages sent through the Unix domain socket are transparently forwarded to the correct node.

4.1.2. Authentication and session handling

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.

Note

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:

  • Remember to log out of active sessions to avoid leaking them; and
  • Be prepared to log in again to the server if a 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()
          

4.1.3. Finding references to useful objects

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:

  • get_by_name_label: return a list of all objects of a particular class with a particular label;
  • get_by_uuid: return a single object named by its UUID;
  • get_all: return a set of references to all objects of a particular class; and
  • get_all_records: return a map of reference to records for each object of a particular class.

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')
          

Note

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)
          

4.1.4. Invoking synchronous operations on objects

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.

Note

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

4.1.5. Using Tasks to manage asynchronous operations

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:

  • whether it is pending; has succeeded or failed;
  • progress in the range 0-1; and
  • the result or error code returned by the operation.

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

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.

4.1.6. Subscribing to and listening for events

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; and
  • mod: 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.

Note

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"
          

1. Language bindings

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.

4.1.7. C

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:
  • XML-RPC library (libxml2.so on GNU Linux)

  • Curl library (libcurl2.so)

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.

4.1.8. C#

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:

  • VM-Lifecycle: logs into a XenServer Host host, lists all the VM records, filters out the templates, clones a VM from one template, configures the VM's name and description before finally power-cycling the VM; and
  • Monitor: logs into a XenServer Host host, queries properties of a host, lists all Storage Repositories, lists all VMs and prints various attributes.

4.1.9. Python

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:

  • fixpbds.py: reconfigures the settings used to access shared storage;
  • install.py: installs a Debian VM, connects it to a network, starts it up and waits for it to report its IP address;
  • license.py: uploads a fresh license to a XenServer Host;
  • permute.py: selects a set of VMs and uses XenMotion to move them simultaneously between hosts;
  • powercycle.py: selects a set of VMs and powercycles them;
  • shell.py: a simple interactive shell for testing;
  • vm_start_async.py: demonstrates how to invoke operations asynchronously; and
  • watch-all-events.py: registers for all events and prints details when they occur.

4.1.10. Command Line Interface (CLI)

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:

  • install-debian: installs a Debian Etch 4.0 VM, adds a network interface, starts it booting and waits for the IP address to be reported;
  • clone-vms: shuts down a VM if it is running, clones it and starts it up again; and
  • suspend-resume: suspends a running VM and then resumes it.

Note

When running the CLI from a XenServer Host host console, tab-completion of both command names and arguments is available.

你可能感兴趣的:(虚拟化)