XenAPI

简介:

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错误。
 
参考:

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.


本文转自feisky博客园博客,原文链接:http://www.cnblogs.com/feisky/archive/2011/11/23/2260872.html,如需转载请自行联系原作者


相关文章
|
6月前
|
算法 C语言
[C语言]字节跳动2019春招研发部分编程题
[C语言]字节跳动2019春招研发部分编程题
101 0
|
6月前
|
移动开发 安全 数据安全/隐私保护
ios安全加固 ios 加固方案
4.1字符串加密字符串会暴露APP的很多关键信息,攻击者可以根据界面显示的字符串,快速找到相关逻辑的处理函数,从而进行分析破解。加密字符串可以增加攻击者阅读代码的难度以及根据字符串静态搜索的难度。
|
7月前
|
JSON 小程序 前端开发
微信小程序进阶——Flex弹性布局&轮播图&会议OA项目(首页)
微信小程序进阶——Flex弹性布局&轮播图&会议OA项目(首页)
83 0
|
6月前
|
SQL 存储 OLAP
适用于即席查询(Ad-Hoc)的OLAP引擎
即席查询(Ad Hoc)是用户根据自己的需求,灵活的选择查询条件,OLAP系统根据用户输入的查询条件实时返回查询结果。OLAP的即席查询与普通查询的不同之处就是很难对前者进行预先的优化,因为即席查询所响应的大都是随机性很强的查询请求。一个OLAP系统的即席查询能力越强,其应对不同用户的随机性和探索性分析的能力就越强。
233 0
适用于即席查询(Ad-Hoc)的OLAP引擎
|
编解码 前端开发 测试技术
这可能是市面上最好用的iOS云真机
最好用的iOS云真机,是怎么实现的呢?快来了解下吧!
2931 0
这可能是市面上最好用的iOS云真机
|
9月前
|
机器学习/深度学习 安全 算法
「机密计算-隐私计算」科普
「机密计算-隐私计算」科普
354 0
|
10月前
|
机器学习/深度学习 算法 C语言
C语言笔记第02章:三大基本结构(三)
C语言笔记第02章:三大基本结构
85 1
|
11月前
|
存储 编译器 数据库
进阶C语言:文件操作
C语言关于文件操作的详细知识点
162 0
|
6月前
|
算法 索引
【霍罗维兹数据结构】线索二叉树 | HEAP | 二叉搜索树 | 不相交集合的表示
【霍罗维兹数据结构】线索二叉树 | HEAP | 二叉搜索树 | 不相交集合的表示
44 0
|
11月前
|
机器学习/深度学习 存储 算法
数据结构:二叉树的链式结构
链式二叉树创建非常详细的过程:包含如何前序遍历创建二叉树、对二叉树的前、中、后序遍历、二叉树节点个数、二叉树叶子节点个数、二叉树的高度、第k层节点个数、查找节点、层序遍历、判断二叉树是否为完全二叉树、二叉树的销毁.....附带完整代码以及图解
163 0