Transcription

Citrix XenServer 7.1 Software Development Kit GuidePublished August 20171.0 Edition

Citrix XenServer 7.1 Software Development Kit GuideCopyright 2017 Citrix Systems. Inc. All Rights Reserved.Version: 7.1.1Citrix, Inc.851 West Cypress Creek RoadFort Lauderdale, FL 33309United States of AmericaDisclaimersThis document is furnished "AS IS." Citrix, Inc. disclaims all warranties regarding the contents of this document,including, but not limited to, implied warranties of merchantability and fitness for any particular purpose. Thisdocument may contain technical or other inaccuracies or typographical errors. Citrix, Inc. reserves the right torevise the information in this document at any time without notice. This document and the software describedin this document constitute confidential information of Citrix, Inc. and its licensors, and are furnished under alicense from Citrix, Inc.Citrix Systems, Inc., the Citrix logo, Citrix XenServer and Citrix XenCenter, are trademarks of Citrix Systems, Inc.and/or one or more of its subsidiaries, and may be registered in the United States Patent and Trademark Officeand in other countries. All other trademarks and registered trademarks are property of their respective owners.TrademarksCitrix XenServer XenCenter

Contents1. Introduction . 12. Getting Started . 22.1. System Requirements and Preparation . 22.2. Downloading . 22.3. SDK Languages . 22.3.1. C . 22.3.2. C# . 32.3.3. Java . 42.3.4. PowerShell . 42.3.5. Python . 52.4. Command Line Interface (CLI) . 63. Overview of the XenServer API . 73.1. Getting Started with the API . 73.1.1. Authentication: acquiring a session reference . 73.1.2. Acquiring a list of templates to base a new VM installation on . 83.1.3. Installing the VM based on a template . 83.1.4. Taking the VM through a start/suspend/resume/stop cycle . 83.1.5. Logging out . 83.1.6. Install and start example: summary . 93.2. Object Model Overview . 93.3. Working with VIFs and VBDs . 113.3.1. Creating disks and attaching them to VMs . 113.3.1.1. Creating a new blank disk image . 113.3.1.2. Attaching the disk image to a VM . 123.3.1.3. Hotplugging the VBD . 133.3.2. Creating and attaching Network Devices to VMs . 133.3.3. Host configuration for networking and storage . 133.3.3.1. Host storage configuration: PBDs . 133.3.3.2. Host networking configuration: PIFs . 14iii

3.4. Exporting and Importing VMs . 143.4.1. Xen Virtual Appliance (XVA) VM Import Format . 153.5. XML-RPC notes . 183.5.1. Datetimes . 183.6. Where to look next . 184. Using the API . 194.1. Anatomy of a typical application . 194.1.1. Choosing a low-level transport . 194.1.2. Authentication and session handling . 194.1.3. Finding references to useful objects . 204.1.4. Invoking synchronous operations on objects . 204.1.5. Using Tasks to manage asynchronous operations . 214.1.6. Subscribing to and listening for events . 214.2. Complete application examples . 224.2.1. Simultaneously migrating VMs using XenMotion . 224.2.2. Cloning a VM using the XE CLI . 245. Using HTTP to interact with XenServer . 265.1. VM Import and Export . 265.2. Getting XenServer Performance Statistics . 266. XenServer API extensions . 286.1. VM console forwarding . 286.1.1. Retrieving VNC consoles using the API . 286.1.2. Disabling VNC forwarding for Linux VM . 296.2. Paravirtual Linux installation . 306.2.1. Red Hat Enterprise Linux 4.1/4.4 . 306.2.2. Red Hat Enterprise Linux 4.5/5.0 . 306.2.3. SUSE Enterprise Linux 10 SP1 . 306.2.4. CentOS 4.5 / 5.0 . 306.3. Adding Xenstore entries to VMs . 306.4. Security enhancements . 31iv

6.5. Advanced settings for network interfaces . 316.5.1. ethtool settings . 316.5.2. Miscellaneous settings . 326.6. Internationalization for SR names . 336.7. Hiding objects from XenCenter . 337. XenCenter API Extensions . 347.1. Pool . 347.2. Host . 347.3. VM . 357.4. SR . 367.5. VDI . 367.6. VBD . 377.7. Network . 377.8. VM guest metrics . 377.9. Task . 37v

Chapter 1. IntroductionWelcome to the developer's guide for XenServer. Here you will find the information you need in order tounderstand and use the Software Development Kit (SDK) that XenServer provides. This information will provideyou with some of the architectural background and thinking that underpins the APIs, the tools that have beenprovided, and how to quickly get off the ground.1

Chapter 2. Getting StartedXenServer includes a XML-RPC based API providing programmatic access to the extensive set of XenServermanagement features and tools. The XenServer API can be called from a remote system as well as local to theXenServer host. Although it is possible to write applications which use the XenServer Management API directlythrough raw XML-RPC calls, the task of developing third-party applications is greatly simplified through theuse of a language binding which exposes the individual API calls as first-class functions in the target language.The XenServer SDK provides language bindings and example code for the C, C#, Java, Python and PowerShellprogramming languages.2.1. System Requirements and PreparationThe first step towards working with the SDK is to install XenServer. A free version, Citrix XenServer, is availablefor download at http://www.citrix.com/downloads/xenserver/. Please refer to the XenServer Installation Guidefor detailed instructions on how to set up your development host. When the installation is complete, please notethe host IP address and the host password.2.2. DownloadingThe SDK is packaged as a ZIP file and is available as a free download from http://www.citrix.com/downloads/xenserver/.2.3. SDK LanguagesThe extracted contents of the SDK ZIP file are in the XenServer-SDK directory. The following is an overviewof its structure. Where necessary, subdirectories have their own individual README files. It should be noted thatthe examples provided are not the same across all the language bindings, so, if you intend to use one binding, itis advisable to also browse the sample code available in the others.At the top level of the XenServer-SDK directory the XenServer API Reference document has been included, whichprovides a more detailed description of the API semantics as well as describing the format of XML/RPC messageson the wire.2.3.1. CThe XenServer-SDK directory contains the following folders that are relevant to C programmers: libxenserverThe XenServer SDK for C. libxenserver/binlibxenserver compiled binaries. libxenserver/srclibxenserver source code and examples and a Makefile to build them. Every API object is associated with aheader file which contains declarations for all that object's API functions; for example, the type definitionsand functions required to invoke VM operations are all contained in xen vm.h.C binding dependenciesPlatform supported:Linux and Windows (under cygwin)2

Library:The language binding is generated as a libxenserver.so that is linked byC programs.Dependencies: XML library (libxml2.so on GNU Linux) Curl library (libcurl3.so)The following simple examples are included with the C bindings: test vm async migrate: demonstrates how to use asynchronous API calls to migrate running VMs froma slave host to the pool master. test vm ops: demonstrates how to query the capabilities of a host, create a VM, attach a fresh blank diskimage to the VM and then perform various powercycle operations; test failures: demonstrates how to translate error strings into enum xen api failure, and vice versa; test event handling: demonstrates how to listen for events on a connection. test enumerate: demonstrates how to enumerate the various API objects. test get records: demonstrates how to obtain information on API objects such as hosts, VMs, andstorage repositories.2.3.2. C#The XenServer-SDK directory contains the following folders that are relevant to C# programmers: XenServer.NETThe XenServer SDK for C#.NET. XenServer.NET/binXenServer.NET ready compiled binaries. XenServer.NET/samplesXenServer.NET examples shipped as a Microsoft Visual studio solution. XenServer.NET/srcXenServer.NET source code shipped as a Microsoft Visual Studio project. Every API object is associated withone C# file; for example the functions implementing the VM operations are contained within the file VM.cs.C# binding dependenciesPlatform supported:Windows with .NET version 4.5Library:The language binding is generated as a Dynamic Link LibraryXenServer.dll that can be referenced by C# programs.Dependencies:CookComputing.XMLRpcV2.dll is needed for the XenServer.dll to beable to communicate with the xml-rpc server. We ship a patched 2.5 versionand recommend that you use this one, though others may work.Three examples are included with the C# bindings in the directory XenServer-SDK/XneServer.NET/samples as separate projects of the XenSdkSample.sln solution: GetVariousRecords: logs into a XenServer Host and displays information about hosts, storage and virtualmachines; GetVmRecords: logs into a XenServer Host and lists all the VM records;3

VmPowerStates: logs into a XenServer Host, finds a VM and takes it through the various power states.Requires a shut-down VM to be already installed.2.3.3. JavaThe XenServer-SDK directory contains the following folders that are relevant to C# programmers: XenServerJavaThe XenServer SDK for Java XenServerJava/binJava compiled binaries. XenServerJava/javadocJava documentation. XenServerJava/samplesJava examples. XenServerJava/srcJava source code and a Makefile to build the code and the examples. Every API object is associated with oneJava file; for example the functions implementing the VM operations are contained within the file VM.java.Java binding dependenciesPlatform supported:Linux and WindowsLibrary:The language binding is generated as a Javaxenserver-7.1.jar that is linked by Java programs.Dependencies:xmlrpc-client-3.1.jar, xmlrpc-common-3.1.jar and wscommons-util-1.0.2.jar are needed for the xenserver.jar to beable to communicate with the xml-rpc server. These jars are shipped alongsidethe xenserver.jar.ArchivefileRunning the main file XenServer-SDK/XenServerJava/samples/RunTests.java will run a seriesof examples included in the same directory: AddNetwork: Adds a new internal network not attached to any NICs; SessionReuse: Demonstrates how a Session object can be shared between multiple Connections; AsyncVMCreate: Makes asynchronously a new VM from a built-in template, starts and stops it; VdiAndSrOps: Performs various SR and VDI tests, including creating a dummy SR; CreateVM: Creates a VM on the default SR with a network and DVD drive; DeprecatedMethod: Tests a warning is displayed when a deprecated API method is called; GetAllRecordsOfAllTypes: Retrieves all the records for all types of objects; SharedStorage: Creates a shared NFS SR; StartAllVMs: Connects to a host and tries to start each VM on it.2.3.4. PowerShellThe XenServer-SDK directory contains the following folders that are relevant to PowerShell users:4

XenServerPowerShellThe XenServer SDK for PowerShell. XenServerPowerShell/XenServerPSModuleThe XenServer PowerShell module. XenServerPowerShell/samplesPowerShell example scripts. XenServerPowerShell/srcC# source code for the XenServer PowerShell cmdlets.Detailed installation instructions are provided within the README file accompanying the module. Once themodule is installed, an overview of the cmdlets can be obtained by typing:PS Get-Help about XenServerPowerShell binding dependenciesPlatform supported:Windows with .NET Framework 4.5 and PowerShell uting.XMLRpcV2.dll is needed to be able to communicatewith the xml-rpc server. We ship a patched 2.5 version and recommend thatyou use this one, though others may work.The following example scripts are included with the PowerShell bindings in the directory XenServer-SDK/XenServerPowerShell/samples: AutomatedTestCore.ps1: demonstrates how to log into a XenServer host, create a storage repositoryand a VM, and then perform various powercycle operations. HttpTest.ps1: demonstrates how to log into a XenServer host, create a VM, and then perform operationssuch as VM importing and exporting, patch upload, and retrieval of performance statistics.2.3.5. PythonThe XenServer-SDK directory contains the following folders that are relevant to Python developers: XenServerPythonThis directory contains the XenServer Python module XenAPI.py. XenServerPython/samplesXenServer API examples using Python.Python binding dependenciesPlatform supported:LinuxLibrary:XenAPI.pyDependencies:None5

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 IPaddress; 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; vm start async.py - demonstrates how to invoke operations asynchronously; watch-all-events.py - registers for all events and prints details when they occur.2.4. Command Line Interface (CLI)Besides using raw XML-RPC or one of the supplied language bindings, third-party software developers mayintegrate with XenServer Hosts by using the XE command line interface xe. The xe CLI is installed by default onXenServer hosts; a stand-alone remote CLI is also available for Linux. On Windows, the xe.exe CLI executableis installed along with XenCenter.CLI dependenciesPlatform supported:Linux and WindowsLibrary:NoneBinary:xe (xe.exe on Windows)Dependencies:NoneThe CLI allows almost every API call to be directly invoked from a script or other program, silently taking careof the required session management. The XE CLI syntax and capabilities are described in detail in the XenServerAdministrator's Guide. For additional resources and examples, visit the Citrix Knowledge Center.Note:When running the CLI from a XenServer Host console, tab-completion of both commandnames and arguments is available.6

Chapter 3. Overview of the XenServer APIThis chapter introduces the XenServer API (subsequently referred to as the "API") and its associated object model.The API has the following key features: Management of all aspects of the XenServer HostThe API allows you to manage VMs, storage, networking, host configuration and pools. Performance and statusmetrics can also be queried from the API. Persistent Object ModelThe results of all side-effecting operations (e.g. object creation, deletion and parameter modifications) arepersisted in a server-side database that is managed by the XenServer installation. An event mechanismThrough the API, clients can register to be notified when persistent (server-side) objects are modified. Thisenables applications to keep track of datamodel modifications performed by concurrently executing clients. Synchronous and asynchronous invocationAll API calls can be invoked synchronously (that is, block until completion); any API call that may be long-runningcan also be invoked asynchronously. Asynchronous calls return immediately with a reference to a task object.This task object can be queried (through the API) for progress and status information. When an asynchronouslyinvoked operation completes, the result (or error code) is available from the task object. Remotable and Cross-PlatformThe client issuing the API calls does not have to be resident on the host being managed; nor does it have tobe connected to the host over ssh in order to execute the API. API calls make use of the XML-RPC protocol totransmit requests and responses over the network. Secure and Authenticated AccessThe XML-RPC API server executing on the host accepts secure socket connections. This allows a client to executethe APIs over the https protocol. Further, all the API calls execute in the context of a login session generatedthrough username and password validation at the server. This provides secure and authenticated access tothe XenServer installation.3.1. Getting Started with the APIWe will start our tour of the API by describing the calls required to create a new VM on a XenServer installation,and take it through a start/suspend/resume/stop cycle. This is done without reference to code in any specificlanguage; at this stage we just describe the informal sequence of RPC invocations that accomplish our "installand start" task.Note:We recommend strongly against using the VM.create call, which may be removed or changedin a future version of the API. Read on to learn other ways to make a new VM.3.1.1. Authentication: acquiring a session referenceThe first step is to call Session.login with password( username , password , client API version , originator ) . The API is session based, so before you can make other calls you will need to authenticate withthe server. Assuming the username and password are authenticated correctly, the result of this call is a sessionreference. Subsequent API calls take the session reference as a parameter. In this way we ensure that only APIusers who are suitably authorized can perform operations on a XenServer installation. You can continue to usethe same session for any number of API calls. When you have finished the session, Citrix recommends that youcall Session.logout(session) to clean up: see later.7

3.1.2. Acquiring a list of templates to base a new VM installation onThe next step is to query the list of "templates" on the host. Templates are specially-marked VM objects thatspecify suitable default parameters for a variety of supported guest types. (If you want to see a quick enumerationof the templates on a XenServer installation for yourself then you can execute the xe template-list CLI command.)To get a list of templates from the API, we need to find the VM objects on the server that have their is a templatefield set to true. One way to do this by calling VM.get all records(session) where the session parameter is thereference we acquired from our Session.login with password call earlier. This call queries the server, returninga snapshot (taken at the time of the call) containing all the VM object references and their field values.(Remember that at this stage we are not concerned about the particular mechanisms by which the returnedobject references and field values can be manipulated in any particular client language: that detail is dealt withby our language-specific API bindings and described concretely in the following chapter. For now it suffices just toassume the existence of an abstract mechanism for reading and manipulating objects and field values returnedby API calls.)Now that we have a snapshot of all the VM objects' field values in the memory of our client application we cansimply iterate through them and find the ones that have their "is a template" set to true. At this stage let'sassume that our example application further iterates through the template objects and remembers the referencecorresponding to the one that has its "name label" set to "Debian Etch 4.0" (one of the default Linux templatessupplied with XenServer).3.1.3. Installing the VM based on a templateContinuing through our example, we must now install a new VM based on the template we selected. Theinstallation process requires 2 API calls: First we must now invoke the API call VM.clone(session, t ref, "my first VM"). This tells the server to clonethe VM object referenced by t ref in order to make a new VM object. The return value of this call is the VMreference corresponding to the newly-created VM. Let's call this new vm ref. At this stage the object referred to by new vm ref is still a template (just like the VM object referred to byt ref, from which it was cloned). To make new vm ref into a VM object we need to call VM.provision(session,new vm ref). When this call returns the new vm ref object will have had its is a template field set to false,indicating that new vm ref now refers to a regular VM ready for starting.Note:The provision operation may take a few minutes, as it is as during this call that the template'sdisk images are created. In the case of the Debian template, the newly created disks are alsoat this stage populated with a Debian root filesystem.3.1.4. Taking the VM through a start/suspend/resume/stop cycleNow we have an object reference representing our newly-installed VM, it is trivial to take it through a few lifecycleoperations: To start our VM we can just call VM.start(session, new vm ref) After it's running, we can suspend it by calling VM.suspend(session, new vm ref), and then resume it by calling VM.resume(session, new vm ref). We can call VM.shutdown(session, new vm ref) to shutdown the VM cleanly.3.1.5. Logging outOnce an application is finished interacting with a XenServer Host it is good practice to call Session.logout(session).This invalidates the session reference (so it cannot be used in subsequent API calls) and simultaneouslydeallocates server-side memory used to store the session object.8

Although inactive sessions will eventually timeout, the server has a hardcoded limit of 500 concurrent sessionsfor each username or originator. Once this limit has been reached fresh logins will evict the session objectsthat have been used least recently, causing their associated session references to become invalid. For successfulinteroperability with other applications, concurrently accessing the server, the best policy is: Choose a string that identifies your application and its version. Create a single session at start-of-day, using that identifying string for the originatorSession.login with password.parameter to Use this session throughout the application (note that sessions can be used across multiple separate clientserver network connections) and then explicitly logout when possible.If a poorly written client leaks sessions or otherwise exceeds the limit, then as long as the client uses anappropriate originator argument, it will be easily identifiable from the XenServer logs and XenServer willdestroy the longest-idle sessions of the rogue client only; this may cause problems for that client but not for otherclients. If the misbehaving client did not specify an originator, it would be harder to identify and wouldcause the premature destruction of sessions of any clients that also did not specify an originator3.1.6. Install and start example: summaryWe have seen how the API can be used to install a VM from a XenServer template and perform a number oflifecycle operations on it. You will note that the number of calls we had to make in order to affect these operationswas small: One call to acquire a session: Session.login with password() One call to query the VM (and template) objects present on the XenServer installation: VM.get all records().Recall that we used the information returned from this call to select a suitable template to install from. Two calls to install a VM from our chosen template: VM.clone(), followed by VM.provision(). One call to start the resultant VM: VM.start() (and similarly other single calls to suspend, resume and shutdownaccordingly) And then one call to logout Session.logout()The take-home message here is that, although the API as a whole is complex and fully featured, common tasks(such as creating and performing lifecycle operations on VMs) are very straightforward to perform, requiring onlya small number of simple API calls. Keep this in mind while you study the next section which may, on first reading,appear a little daunting!3.2. Object Model OverviewThis section gives a high-level overview of the object model of the API. A more detailed description of theparameters and methods of each class outlined here can be found in the XenServer API Reference document.We start by giving a brief outline of some of the core cl

At the top level of the XenServer-SDK directory the XenServer API Reference document has been included, which provides a more detailed description of the API semantics as well as describing the format of XML/RPC messages on the wire. 2.3.1. C The XenServer-SDK directory contains the