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,如需转载请自行联系原作者


相关文章
|
4月前
|
安全 API 网络安全
OpenStack的 网络服务(Neutron)
【8月更文挑战第23天】
284 10
|
4月前
|
搜索推荐 API 语音技术
FunClip的基础功能问题之使用FunClip进行智能剪辑的问题如何解决
FunClip的基础功能问题之使用FunClip进行智能剪辑的问题如何解决
459 0
|
7月前
|
安全 网络安全 网络虚拟化
虚拟网络设备的网络隔离机制:原理、意义与应用场景深度分析
虚拟网络设备在现代网络架构中扮演着重要角色🌐,尤其是在实现网络隔离方面🛡️。网络隔离是网络安全🔒和多租户环境管理的关键组成部分,它能够确保不同网络流量的分离🚦,保护敏感数据💾,减少攻击面。虚拟网络设备通过在软件层面上模拟物理网络设备的行为,提供了一种灵活且成本效益高的方式来实现这些目标。本文将从多个维度深入分析虚拟网络设备是如何隔离网络的,这种隔离有什么实际意义,为什么需要虚拟网络设备来隔离网络,以及在什么场景下比较适合使用虚拟网络设备隔离网络。
|
7月前
|
存储 机器学习/深度学习 人工智能
RAG:AI大模型联合向量数据库和 Llama-index,助力检索增强生成技术
RAG:AI大模型联合向量数据库和 Llama-index,助力检索增强生成技术
RAG:AI大模型联合向量数据库和 Llama-index,助力检索增强生成技术
|
缓存 算法 网络协议
盘点腾讯后台开发各级工程师(T1-T9)需要具备哪些能力
盘点腾讯后台开发各级工程师(T1-T9)需要具备哪些能力
盘点腾讯后台开发各级工程师(T1-T9)需要具备哪些能力
|
7月前
|
网络安全
openstack云平台创建卷以及使用卷挂载
在阿里云上,创建一个名为test-lv的10GB卷,并与实例关联。通过SSH登录,检查磁盘,进行分区和格式化,挂载到/mnt并写入test文件。当卷空间不足时,先分离卷,然后扩展至15GB。重新连接实例,发现原有数据丢失,需重新分区和格式化。重启云主机后,新扩容的5GB显示为/vdb2。
211 1
openstack云平台创建卷以及使用卷挂载
|
人工智能
用ChatGPT/midjourney生成创意营销图片素材,产品图、虚拟主播、终端店铺图
第一步,先预设场景,询问应该包含的关键词范围 假设你是一位世界一流水平的设计师,你想要使用AI绘画工具midjourney帮忙设计一款XXX,列举该场景需要用到的关键词范畴与示例。 第二步,按照推荐的关键词填充内容来输入到midjourney中,生成对应的图片。 按照逗号区隔不同描述词,用谷歌助手翻译成英文描述词,输入到midjourney中。
678 0
|
监控 前端开发
阿里云 ARMS
阿里云 ARMS
340 1
|
人工智能 Serverless 异构计算
【有奖体验】AI 都这么厉害了,可以看图生成文字描述!
【有奖体验】AI 都这么厉害了,可以看图生成文字描述!
高频面试题之Flask框架的上下文
Flask框架中分为2种上下文: 请求上下文(request context)和应用上下文(app context) 一般面试的问点在于:两种上下文是什么? 有什么区别? 什么场景下使用?