Programming Guide 201
Programming Guide 201
3
ManagedEntity Inventory ______________________________________35
ComputeResource and ClusterComputeResource ___________________37
ResourcePool ________________________________________________37
Commonly Used VMware Infrastructure SDK Operations _________________43
RetrieveServiceContent ________________________________________43
RetrieveProperties ____________________________________________43
CreateFilter, CheckForUpdates, and WaitForUpdates __________________43
ReconfigVM_Task _____________________________________________44
Operations That Return a Task _____________________________________45
Client-Web Service Interactions ____________________________________46
Returning Escaped Characters ___________________________________46
Inventory Management __________________________________________47
Folders _____________________________________________________47
Datacenter __________________________________________________47
The childType Property ________________________________________48
Events, Tasks, and Alarms _________________________________________49
Events _____________________________________________________49
Tasks _______________________________________________________49
Using a History Collector for Historical Task Information _______________50
Alarms _____________________________________________________50
Networks _____________________________________________________52
HostNetworkSystem and the Network Managed Objects ______________52
PhysicalNic and VirtualNic ______________________________________52
Port Groups and Virtual Switches _________________________________52
NIC Teaming ________________________________________________53
Datastores _____________________________________________________54
Local File System _____________________________________________54
Network Attached Storage (NAS) Volume __________________________54
VMware File System (VMFS) _____________________________________54
Datastore Path _______________________________________________54
iSCSI Support ________________________________________________55
Snapshots _____________________________________________________56
Performance Monitoring _________________________________________59
Perf Intervals ________________________________________________59
CounterIds and MetricIds _______________________________________60
Starting Time/Ending Time/Maximum Samples _____________________60
Logging On __________________________________________________ 61
www.vmware.com
4
Session Management ____________________________________________62
Instantiating an Instance and Opening a User Session ___________________63
Setting the Locale _______________________________________________64
5
Migrating a Powered-On Virtual Machine (VMotion) __________________82
Migrating a Powered-Off Virtual Machine __________________________82
Moving Files _________________________________________________83
Validating Migration ___________________________________________83
Managing Virtual Machine Snapshots _______________________________84
Creating Snapshots ___________________________________________84
Reverting to Snapshots ________________________________________85
Removing Snapshots __________________________________________87
Obtaining a VirtualMachineSnapshot Managed Object Reference _______88
Managing Clusters and Resource Pools ______________________________89
Creating a Cluster of Hosts ______________________________________89
Configuring or Reconfiguring a Cluster ____________________________89
Creating Resource Pools _______________________________________91
Reconfiguring Resource Pools ___________________________________91
Configuring Resource Pools with the ResourceConfigSpec _____________92
Destroying the Children of a Resource Pool _________________________95
Moving Resource Pools and Virtual Machines Into a Resource Pool ______95
Managing Hosts _______________________________________________ 100
Adding a Standalone Host _____________________________________ 100
Adding a Host to a Cluster _____________________________________ 101
Moving Hosts Into a Cluster ____________________________________ 101
Moving Existing Hosts into a Folder ______________________________ 102
Removing Hosts from a Cluster _________________________________ 103
Connecting and Disconnecting Hosts ____________________________ 103
Recommending Hosts for Virtual Machines ________________________ 104
Achieving A More Efficient Resource Usage for Clusters (DRS Only) _____ 104
Shutting Down or Restarting a Host _____________________________ 105
Configuring Networks for a Host __________________________________ 106
Configuring the Service Console TCP/IP __________________________ 106
Configuring TCP/IP on the VMkernel _____________________________ 106
Determining the Host’s Network Configuration ____________________ 107
Adding a Virtual Switch _______________________________________ 107
Adding a Port Group to a vSwitch _______________________________108
Updating the Host’s Network Configuration _______________________ 109
Defining the Host Network Policy _______________________________110
Obtaining the HostNetworkSystem Managed Object Reference ________ 111
Renaming Managed Entities ______________________________________ 112
Managing Datastores ___________________________________________ 113
www.vmware.com
6
Creating an NAS-Backed Datastore ______________________________113
Creating a VMFS-Backed Datastore ______________________________113
Extending a VMFS Datastore Across Multiple Disks __________________113
Determining Options for Extending a VMFS-Backed Datastore _________114
Searching for Available Disks for Extending VMFS Datastores __________114
Removing and Deleting Datastores ______________________________115
Configuring a VMFS-Backed Datastore ___________________________115
Determining Options for Creating a New VMFS Datastore ____________116
Defining the HostScsiDiskPartition _______________________________116
Defining the HostDiskPartitionInfoSpecification ____________________117
Configuring iSCSI Initiators ____________________________________117
Obtaining Managed Object References for Storage Operations ________121
7
Querying Statistics _____________________________________________ 148
Retrieving MetricIds __________________________________________ 148
Querying Statistics ___________________________________________ 148
Querying Information for an Entity and Its Children _________________ 148
Querying Performance Provider Information _______________________ 149
Querying Metadata Information ___________________________________ 150
www.vmware.com
8
Setting, Updating, or Resetting Entity Permissions __________________186
Removing Entity Permissions ___________________________________187
Querying for Permissions ________________________________________188
Querying for All Permissions ___________________________________188
Querying for the Permissions on a Specific Entity ___________________188
Querying for the Permissions that Use a Particular Role ______________188
Obtaining a Reference to the AuthorizationManager ___________________189
9
Taking a Snapshot of a Virtual Machine _____________________________ 242
Creating and Deleting Inventory Objects ____________________________ 243
Creating a Datacenter ________________________________________ 243
Deleting a Managed Entity ____________________________________ 243
Moving an Inventory Object ______________________________________ 244
Renaming an Object ____________________________________________ 245
Monitoring Events and Alarms ____________________________________ 246
Creating and Monitoring Events with a HistoryCollector ______________ 246
Creating and Monitoring Alarms ________________________________ 248
Task Scheduling and Monitoring __________________________________ 251
Creating Scheduled Tasks _____________________________________ 251
Monitoring Scheduled Tasks ___________________________________ 252
Monitoring Non-Scheduled Tasks _______________________________252
Ending a Task _______________________________________________ 253
Exception Handling and Faults ____________________________________ 256
www.vmware.com
10
Complete List of Performance Counters _____________________________292
CPU Usage (Group: cpu) ______________________________________292
CPU Utilization for Resources (Group: rescpu) ______________________293
Memory Performance (Group: mem) _____________________________294
Network Performance (Group: net) ______________________________297
Disk Performance (Group: disk) _________________________________297
System Performance (Group: sys) ________________________________298
Cluster Services Metrics (Group: clusterServices) ____________________298
11
www.vmware.com
12
Introducing the Programming Guide
CHAPTER 1
The purpose of this guide is to help you develop a client application that you can use to connect
to the Virtual Infrastructure Web Service. Developers who use this manual should be familiar with
the operation and management of VMware® VirtualCenter, VMware ESX Server, and other VMware
products.
13
VMware Infrastructure SDK Programming Guide
www.vmware.com
14
C H A P T E R 1 Introducing the Programming Guide
This information also includes finding inventory entities using a property value and getting
property updates.
• Monitoring Performance Data on page 145
This chapter describes the tasks involved in monitoring performance data.
• Managing Events, Tasks, and Alarms on page 151
This chapter describes the tasks involved in managing events, alarms, and tasks.
• Developing Client Applications on page 21
This chapter provides an overview of the steps you should consider when building your
client application. This chapter also describes the different development environments you
can use to develop your client application. In addition, the chapter provides a compilable,
simple client application.
The following chapters provide code sample snippets that illustrate some of the operations
described in the preceding chapters:
• Java Code Examples for Basic Operations on page 197
• Java Code Examples for Advanced Operations on page 217
Several chapters and appendices provide helpful programming information:
• Troubleshooting with the Managed Object Browser on page 259
• Glossary on page 265
• Privileges on page 301
15
VMware Infrastructure SDK Programming Guide
Intended Audience
This programming guide is written for programmers who are familiar with Web services concepts
and principles. Readers of this manual should be comfortable with developing system
administration and system monitoring programs and be familiar with general debugging
techniques. In addition, developers who use this manual should be familiar with the operation and
management of VMware VirtualCenter, VMware ESX Server, VMware GSX Server, and other
VMware products.
www.vmware.com
16
C H A P T E R 1 Introducing the Programming Guide
VMware VirtualCenter
VMware VirtualCenter is a software solution for deploying and managing virtual machines across
multiple server machines running ESX Server and GSX Server hosts. It enables customers to
manage a distributed, heterogeneous computing environment as a single pool of computing
resources. VirtualCenter includes a new technology called VMotion™ that enables the seamless
migration of running virtual machines across hosts with no service interruption.
VirtualCenter provides VMware Infrastructure services and functionality:
• Centralized management of large virtual machine environments through a single user
interface
• Automated virtual machine provisioning
• Virtual machine performance and workload analysis
• Virtual machine migration, including VMotion
• VMware DRS, enabling initial virtual machine placement and dynamic virtual machine
migration automatically, based on the resource allocation and policies specified by
administrators
• VMware HA, detecting failed virtual machines and automatically restarting them on alternate
ESX Server hosts.
• Secure access control that integrates into existing Microsoft® Windows® user management
systems
17
VMware Infrastructure SDK Programming Guide
Management VMware
VMware Host Agent
Server DB Proprietary
VMware Protocol ESX03.vmware.com
Proprietary
Protocol
ESX01.vmware.com
SOAP/HTTPS
Management VMware
Server DB Proprietary
Protocol VMware Host Agent
VMware VMware
Proprietary Proprietary
Protocol Protocol
VMware Host Agent
ESX Client GUI
www.vmware.com
18
C H A P T E R 1 Introducing the Programming Guide
19
VMware Infrastructure SDK Programming Guide
www.vmware.com
20
Developing Client Applications
CHAPTER 2
This chapter contains the following sections:
• Connecting to the VMware Infrastructure Web Service on page 22
• Selecting a Development Environment on page 23
• Setting up the VMware Infrastructure SDK Client on page 25
21
VMware Infrastructure SDK Programming Guide
Overview
At a high level, the client uses the VMware Infrastructure Web Service to connect to the Web
service as shown in the following diagram.
1. The client invokes a method on a stub (a proxy object) to perform a task. The stub acts as a
proxy for the Web service.
2. The development runtime environment (see Selecting a Development Environment on
page 23) converts the invocation into a SOAP message. This SOAP message is then
transmitted over HTTP/S to the Web service.
www.vmware.com
22
C H A P T E R 2 Developing Client Applications
Apache Axis
Apache Axis is a modular, flexible, and high performing SOAP implementation designed around a
streaming model. You can obtain Apache Axis at ws.apache.org/axis. This download package
contains the Web services tool kit.
23
VMware Infrastructure SDK Programming Guide
To develop a Web service client application using Microsoft Visual Studio.NET, you must first use a
WSDL proxy generator tool to generate proxy code based on the WSDL file. Essentially, the proxy
code exposes all Web service operations as methods of a C# or Visual Basic class. The file that
contains the proxy code is then added to the Microsoft Visual Studio.NET project, used to develop
the client application. This enables the client application code to invoke Web service operations
programatically by calling the methods of the proxy class.
www.vmware.com
24
C H A P T E R 2 Developing Client Applications
Requirements
VMware Infrastructure SDK supports JDSE 1.4 and 1.5. Also, the VMware Infrastructure SDK has
been tested with the following WSDEs:
• Microsoft Visual Studio .NET (2003 and 2005) and .NET Framework (version 1.1 and 2.0).
• Apache Axis 1.2.1 through 1.4
Note: The samples included with the VMware Infrastructure SDK have been compiled only with
Apache Axis 1.2.1.
Setup Procedure
Follow these steps to set up your SDK client so you can write applications:
1. Select and download a WSDE.
See Selecting a Development Environment on page 23 for a discussion of the supported
WSDEs.
2. Download the VMware Infrastructure SDK client.
Install the SDK into a directory with no spaces in the directory name.
3. Set the SDKHOME variable to the path to the directory that contains the VMware
Infrastructure SDK.
For example, C:\apps\SDK.
4. Generate and compile the stub files.
For information on generating and compiling, see one of the following sections depending
on your selected WSDE:
• Generating Stubs with Microsoft Visual Studio .NET and .NET Framework on page 26
• Generating Stubs with Apache Axis on page 26
5. Configure the appropriate protocol.
Before you can compile and run code, you must configure the protocol for accessing the
VMware Infrastructure SDK Web Service. The URL for accessing the VMware Infrastructure
SDK Web Service is:
25
VMware Infrastructure SDK Programming Guide
protocol://<server_name_or_ip_address>/sdk
The protocol you use depends on whether you are configured for SSL (https) or non-SSL
(http).
By default the VMware Infrastructure SDK Web Service only supports using the https
protocol. If you want to invoke operations using the https protocol, you must configure the
client. See Configuring for the https (SSL) Protocol on page 28.
To invoke operations using the http protocol, you must enable the appropriate server. See
Configuring for the http (non-SSL) Protocol on page 29.
Once you have completed these steps, you can write applications. See Creating a Simple Java
Client Application on page 191 for information on how to write a simple client application using
the VMware Infrastructure SDK.
Generating Stubs with Microsoft Visual Studio .NET and .NET Framework
Once you have downloaded the Microsoft VisualStudio Professional Edition (either 2003 or 2005)
from msdn.microsoft.com/downloads/, perform the following steps:
1. Open a Visual Studio .NET command prompt.
2. Change directory to the SDK\Samples_2_0\DotNet directory
3. Execute Build<version>.cmd.
The <version> is whatever version (2003 or 2005) of Microsoft Visual Studio .NET you are
using. The batch file includes a tool for generating proxy code from a WSDL file, called
wsdl.exe.
Once you have generated the proxy code, you must configure the protocol using the procedure
either in Configuring for the https (SSL) Protocol on page 28 or Configuring for the http (non-SSL)
Protocol on page 29.
www.vmware.com
26
C H A P T E R 2 Developing Client Applications
%AXISHOME%\lib\axis-ant.jar;
%AXISHOME%\lib\commons-logging-1.0.4.jar;
%AXISHOME%\lib\saaj.jar;
%AXISHOME%\lib\axis.jar;
%AXISHOME%\lib\jaxrpc.jar;
%AXISHOME%\lib\wsdl4j-1.5.1.jar;
%AXISHOME%\lib\commons-discovery-0.2.jar;
%AXISHOME%\lib\log4j-1.2.8.jar;
%SDKHOME%\samples_2_0\Axis\java\lib\activation.jar;
%SDKHOME%\samples_2_0\Axis\java\lib\mailapi.jar;
Once you have generated the stubs, you must configure the protocol using the procedure either
in Configuring for the https (SSL) Protocol on page 28 or Configuring for the http (non-SSL)
Protocol on page 29.
27
VMware Infrastructure SDK Programming Guide
For example:
keytool -import -file vc-server1.cer -alias vc-server1
-keystore vmware.keystore
www.vmware.com
28
C H A P T E R 2 Developing Client Applications
For example:
keytool -import -file vc-server1.cer
-alias vc-server1 -keystore vmware.keystore
29
VMware Infrastructure SDK Programming Guide
3. Restart the VMware VirtualCenter Server service. This can be done by using the Services
Control Panel Applet.
4. Restart the VMware Infrastructure SDK Management Service by invoking the following
command:
# service mgmt-vmware restart
www.vmware.com
30
VMware Infrastructure SDK Key
CHAPTER 3
Concepts
This chapter describes VMware concepts and their association with the VMware Infrastructure SDK.
Later chapters elaborate on these concepts as they relate to management operations.
• VMware Infrastructure SDK Terminology on page 32
• Commonly Used VMware Infrastructure SDK Operations on page 43
• Operations That Return a Task on page 45
• Client-Web Service Interactions on page 46
• Inventory Management on page 47
• Events, Tasks, and Alarms on page 49
• Networks on page 52
• Datastores on page 54
• Snapshots on page 56
• Performance Monitoring on page 59
31
VMware Infrastructure SDK Programming Guide
www.vmware.com
32
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
• Invoke an operation
Frequently, when you invoke an operation, the operation returns a managed object
reference. For example, when you need a reference to a ScheduledTask managed object, you
can invoke the RetrieveEntityScheduledTask operation. This operation takes a ManagedEntity
managed object reference as one of its parameters. The operation returns all the
ScheduledTask managed object references associated with that entity.
If you are seeking references to ManagedEntity managed objects, the SearchIndex managed
object provides operations that obtain a managed object reference using information about
the object as a parameter. See Finding Entities Using a Property Value on page 135.
• Use an accessor method
If a data object type contains a managed object reference among its properties, you can use
an accessor method to obtain the managed object reference. For example, when you need a
reference to a PropertyCollector managed object, you invoke the Java getPropertyCollector
accessor method (or the equivalent in C#) on the PropertyCollector property of the
ServiceContent data object type. The following code snippet illustrates this:
ManagedObjectReference sir = new ManagedObjectReference();
sir.setType("ServiceInstance");
sir.setValue("ServiceInstance");
// Call retrieveServiceContent()
ServiceContent sic = vimService.retrieveServiceContent(sir);
33
VMware Infrastructure SDK Programming Guide
managed object returns the ServiceContent data object type. This object contains the bulk of
the service instance properties.
• A property collector can be used by the client to retrieve or monitor the properties of a
managed object. For example, the serverClock property of the ServiceInstance can be
accessed only through the PropertyCollector. Using a property collector is described in more
detail in Getting Property Information on page 124.
ServiceInstance
The ServiceInstance managed object is the central access point for all management data in the
VMware Infrastructure SDK. When you create an application, during the login process, you must
construct a reference to a ServiceInstance managed object. This lets you get a reference to a
SessionManager managed object, one of the parameters for the Login operation.
The ServiceInstance does not have directly accessible properties because reading the properties of
a managed object requires the help of a PropertyCollector managed object reference, which is
itself is a property of the ServiceContent data object type. To access these properties, the
ServiceInstance provides the RetrieveServiceContent operation which returns the ServiceContent
data object type.
See Logging On on page 61 for the procedure for accessing the ServiceInstance managed object.
www.vmware.com
34
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
an element. Usually these values are string values, but they can be integer values, as in the case of
the key property of an Event array.
ManagedEntity Inventory
The VMware Infrastructure SDK manages virtual machines and host resources that are organized
into an inventory hierarchy and grouped into folders. VirtualCenter imposes one hierarchical
structure on the inventory. The host agent imposes a more limited version of the hierarchy, while
maintaining the same general structure. The following figure shows an example of a VirtualCenter
hierarchy.
35
VMware Infrastructure SDK Programming Guide
rootFolder
Datacenter
vmFolder hostFolder
ResourcePool ResourcePool
The host agent form of the inventory hierarchy is very similar, but imposes limits on the numbers of
some objects. For instance, the host agent can manage only a single host, so the number of Host
objects is limited to one. The following figure shows an example of a host agent inventory
hierarchy.
rootFolder
Folder
Datacenter
vmFolder hostFolder
ComputeResource
VirtualMachine VirtualMachine VirtualMachine VirtualMachine
ResourcePool Host
See Inventory Management on page 47 for a more complete description of the elements in the
inventory tree.
www.vmware.com
36
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
VMware HA
VMware HA detects failed virtual machines and automatically restarts them on alternate ESX Server
hosts. VMware HA selects a failover host that can honor the virtual machine’s resource allocations
so that service level guarantees remain intact.
VMware DRS
VMware DRS intelligently and continuously balances virtual machine workloads across your ESX
Server hosts. VMware DRS detects when virtual machine activity saturates an ESX Server host and
triggers automated VMotion live migrations, moving running virtual machines to other ESX Server
nodes so that all resource commitments are met.
ResourcePool
A resource pool represents the computing power available to a host or cluster of hosts. You must
associate a virtual machine with a resource pool before the virtual machine can run.
You configure resource pools with absolute values for minimum and maximum quantities of each
resource. To do this, you use three properties of the ResourceAllocationInfo data object:
expandableReservation, reservation, and limit. This enables a system administrator to guarantee
service levels for a set of virtual machines using that resource. You can also configure resource
37
VMware Infrastructure SDK Programming Guide
pools in terms of shares, which allow a system administrator to specify the relative importance of
virtual machines using a resource pool.
Root ResourcePool
A compute resource always has at least one resource pool associated with it. This “root” resource
pool represents all the CPU and memory resources available from the host or the aggregate of
hosts in the compute resource. For the root resource pool, the values of minimum and maximum
available resources are set by the system and are not configurable. The fields are set to the same
value, indicating the total amount of resources the system has available to run virtual machines.
This is computed as the collective CPU and memory resources provided by the currently available
hosts in the parent compute resource minus the overhead used by the virtualization layer.
Note: Virtual machines, as well as resource subdivisions, are known as “children” of a resource
pool.
Datacenter
vmFolder hostFolder
ComputeResource
Resource
Host
Pool
www.vmware.com
38
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
the HA-enabled ClusterComputeResource has a single root ResourcePool. All the hosts belonging
to the cluster share the single ResourcePool. As hosts are added to the cluster, their resource pools
are added to the root ResourcePool. No hierarchy of resource pools is created. In the example, two
virtual machines are associated with two different hosts in the ClusterComputeResource. At the
same time, these two virtual machines are associated with the single root ResourcePool.
Datacenter
vmFolder hostFolder
39
VMware Infrastructure SDK Programming Guide
Datacenter
vmFolder hostFolder
ResourcePool ResourcePool
2 GB 6 GB
Notice that the sum of the minimum available resources is less than the the parent resource pool.
ClusterComputeResource (DRS)
Host Host
ResourcePool
Resource Resource
Pool Pool Resource
Pool
www.vmware.com
40
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
ClusterComputeResource (DRS)
20 GB ResourcePool 30 GB
90 GB
Res ool
Poo urce
Res ool
Poo urce
ourc
10 GB
o
P
l
Res
ourc
o
P
l
Res
e
20 GB
e
10 GB
Resource Poo urce
Res ool
Pool
o
ourc
5 GB
l
Res
P
e
Resource Resource 15 GB
Pool Pool
15 GB 3 GB
The root resource pool has enough capacity to satisfy all the resources reserved by the
children. Before you reserve additional resources, whether by creating a new resource pool or
by powering on a virtual machine or by increasing the resources allocated to either, make
sure that:
• the tree remains consistent. The sum of the child minimum resources now does not
exceed the parent's configured minimum.
• there are enough available resources to reserve. Resource pools and virtual machines
reserve resources from the same pool.
• YELLOW – A more complex state. Because the resource pool configuration is absolute (in
MHz or MB), the configuration can become invalid when resources are removed. This can
happen if a host is removed from the cluster, if a host becomes unavailable, or if a host is
placed in maintenance mode.
For example, suppose a host (equal to 30 Gigabytes) is removed from the cluster shown in
the previous figure. In this case, the resource pool allocation changes as shown in the
following figure.
41
VMware Infrastructure SDK Programming Guide
ClusterComputeResource (DRS)
Host Host X
Host
20 GB ResourcePool 30 GB
60 GB
Res ool
Poo urce
Res ool
Poo urce
ourc
10 GB
o
P
l
Res
ourc
o
P
l
Res
e 20 GB
e
10 GB
Resource
Poo urce
Res ool
Pool
o
ourc
5 GB
l
Res
P
e
Resource Resource 15 GB
Pool Pool
15 GB 3 GB
In this case, the resource allocation in the root ResourcePool is reduced by 30 Gigabytes to
60 GB. Because the sum of the minimum available resources of the child resource pools is
70 GB and exceeds the root, the resource pool goes from a GREEN to a YELLOW state.
The tree is consistent internally, but doesn't have the capacity at the root to meet the needs
of its children. Note that the resource pool can go from GREEN -> YELLOW only if resources
are lost at the root.
• RED (broken) – An internal node in the tree has children whose minimum resources are
greater than its configured minimum. In addition, the node either cannot use the parent’s
resources (see Expanding the Minimum Resources on page 94) or the node can use the
parent’s resources but the child’s minimum resources are greater than its maximum
resources. In this state, all syncs from VirtualCenter to the hosts are suspended and VMware
DRS stops running. Also, the resources that such invalid nodes request from their parents are
limited to the configured min/max, in an attempt to isolate the problem to a small subtree.
For the rest of the tree, the system determines whether the cluster is undercommitted or
overcommitted according to the existing rules and performs admission control accordingly.
www.vmware.com
42
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
RetrieveServiceContent
The ServiceContent data object type contains all the information related to the ServiceInstance.
You invoke the RetrieveServiceContent operation (with a reference to the ServiceInstance
managed object as the parameter) to access the ServiceContent data object.
For example, you invoke this operation when you need a PropertyCollector managed object
reference. The operation returns the ServiceContent data object type. You use an accessor method
to get the PropertyCollector managed object reference.
RetrieveProperties
To get information about one or more managed objects, you construct a PropertyFilterSpec. The
PropertyFilterSpec data object type defines the managed object being selected, the properties of
the managed object, as well as the process for traversing a inventory or property hierarchy.
You invoke the RetrieveProperties operation with two parameters: the PropertyCollector managed
object reference and the PropertyFilterSpec data object type. The RetrieveProperties operation
returns ObjectContent data object types that contain the information collected by the
PropertyFilterSpec.
For more information, see Getting Information and Updates on page 123.
43
VMware Infrastructure SDK Programming Guide
ReconfigVM_Task
You use the ReconfigVM_Task operation to change the information about a specific virtual
machine This operation takes a managed object reference to the VirtualMachine managed object
you want to reconfigure as well as the VirtualMachineConfigSpec data object that contains the
information you want to change. The operation returns a reference to a Task managed object with
which to monitor the operation.
www.vmware.com
44
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
45
VMware Infrastructure SDK Programming Guide
www.vmware.com
46
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
Inventory Management
As described in ManagedEntity Inventory on page 35, the ManagedEntity objects are organized
into an inventory hierarchy. Four basic components make up inventory management in the
VMware Infrastructure SDK: Folder, Datacenter, VirtualMachine, and ComputeResource.
Folders
At the top of the inventory tree is a root Folder. This is a pre-defined Folder managed object
represented by the rootFolder property of the ServiceContent data object.
The Folder object is a managed object for storing inventory. Folders can contain two items: other
folders and one other type of object. The other type of object can be of type Datacenter,
VirtualMachine (which includes templates), or ComputeResource. The object allowed depends on
the value of the Folder object’s childType property. The childType property is an array of object
types a folder can contain. These values depend on whether the folder is located within a
Datacenter. Outside of a Datacenter, the value of the childType property lets you create folders and
datacenters. Folders with these childType values are called datacenter folders.
vmFolder hostFolder
ResourcePool ResourcePool
Datacenter
A Datacenter managed object is a container for hosts and virtual machines. At the first level below
the Datacenter object are two predefined Folder objects: a root virtual machine folder
(represented by the Datacenter object’s vmFolder property) and a root host Folder (represented by
47
VMware Infrastructure SDK Programming Guide
the hostFolder property). These folders are created automatically whenever a Datacenter is created
and cannot be destroyed, renamed, or moved.
www.vmware.com
48
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
Events
Events record significant state changes of managed entities. These events fall into four categories:
• info – information events, such as powering a virtual machine on or off. Any time an
operation is invoked, an info event is triggered.
• error – any time something goes wrong in an operation. For example, if a virtual machine fails
to power on, an error event is triggered.
• warning – any time something could possibly go wrong. For example, if a disk is getting too
full, a warning event is triggered.
• user – user events defined with the LogUserEvents operation. See Logging a User-Defined
Event on page 152.
Tasks
There are two types of tasks in the VMware Infrastructure SDK: scheduled tasks and active tasks.
49
VMware Infrastructure SDK Programming Guide
Active tasks are tasks in the process of performing some action. Some operations (for example,
PowerOnVM_Task) returns an active task called a Task managed object. A scheduled task (a
ScheduledTask managed object) becomes an active task once its scheduled action has been
triggered.
Alarms
Alarms let you trigger actions conditionally. The AlarmExpression data object type provides a way
for you to specify complex conditions for triggering alarms.
The actions that can be triggered by alarms are:
• Invoke an operation with the SDK.
• Run a shell script on the server.
• Send an email message.
• Send an SNMP trap.
www.vmware.com
50
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
51
VMware Infrastructure SDK Programming Guide
Networks
In the VMware Infrastructure SDK, each host is configured to communicate with other hosts for a
variety of purposes. For example, the proper network configuration is necessary to migrate a virtual
machine from one host to another. Likewise, a host must be configured properly to communicate
with storage devices.
www.vmware.com
52
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
the virtual machine to any host on the same physical network that has a port group of the same
name.
As shown in the illustration below, Virtual Machine A is associated with Host #1. The deviceName
property of the EthernetCardBackingInfo object corresponds to the name property (“PortGroup1”,)
of a port group on the associated host on Host #1. Host #2 is on the same physical network and
also has a port group named “PortGroup1”. This lets you migrate the virtual machine from Host #1
to Host #2.
Associated
with Host #1 Host #2
Virtual Machine A
VMkernel VMkernel
VNIC VNIC
PortGroup PortGroup
name = "PortGroup1" name = "PortGroup1"
EthernetCardNetworkBackingInfo VSwitch
VSwitch
deviceName = "PortGroup1" Bond Bridge
Bond Bridge
PNIC PNIC
Physical
Network
The port group with which the virtual machine is associated does not necessarily have to be
associated with a VNIC to perform migration. If you want to perform VMotion (hot migration),
however, you must select a VNIC. For more information, see Enabling Migration on page 81.
NIC Teaming
NIC teaming occurs when multiple physical adapters are associated with a single virtual switch to
form a team. A team can either share the load of traffic between physical and virtual networks
among some or all of its members or provide passive failover in the event of a hardware failure or a
network outage. See Defining the Host Network Policy on page 110.
53
VMware Infrastructure SDK Programming Guide
Datastores
A datastore is a storage location for all the files constituting a virtual machine configuration and
disks. To a host, a datastore is a storage abstraction that is backed by one of several types of storage
volumes:
• Local file system
• Network Attached Storage (NAS) volume
• VMware File System (VMFS)
Datastore Path
A datastore path is a generalization of a file path that lets you locate a specific Datastore entity. You
use this path as the dsPath parameter in the SearchDatastore_Task operation when you are
searching for a specific datastore. Similarly, a datastore path is also used as the path parameter in
the RegisterVM_Task operation.
www.vmware.com
54
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
The file path can be absolute or relative. If it is relative, its base directory is implicit in the context.
For example, a relative path to ISO-image is relative to the virtual machine's configuration
directory.
The datastore path syntax is:
<datastore_path><filepath>
iSCSI Support
The VMware Infrastructure SDK supports either hardware or software initiators. Each VMFS
datastore can support an array of iSCSI send or static targets.
55
VMware Infrastructure SDK Programming Guide
Snapshots
A snapshot preserves the virtual machine just as it was when you took that snapshot, the state of
the data on all the virtual machine’s disks and whether the virtual machine was powered on,
powered off, or suspended. You can take snapshots of a virtual machine at any time and revert to
that snapshot at any time. You can set a boolean property that excludes the memory files from
snapshots.
Overview to Snapshots
The example shown in the following figures begins with a virtual machine. At some point, you
create a snapshot of that virtual machine (Virtual Machine Snapshot1). Snapshot1 is a “snapshot” of
the virtual machine with all its configuration at the time that you created the snapshot. At this
point, you are working with Snapshot1. At a certain point (perhaps after you have made some
changes), you create a second snapshot (Virtual Machine Snapshot2). Now you have two
snapshots of the virtual machine at two points in time. As you work with Snapshot2, you make
more changes. At any point, you can revert to any of the existing snapshots. In this example, you
revert to Snapshot1. When you do this, the changes to Snapshot2 are lost. Snapshot2, however,
continues to exist as a “child” of Snapshot1.
As shown below, working with Snapshot1, you make more changes, then create another snapshot,
Snapshot3. Working with Snapshot3, you make changes, but decide that you don’t like the
changes. You want the virtual machine as it was before the changes, when you created Snapshot3.
In this case, you can revert to the “current” snapshot. All the changes are lost. You can begin again
with Snapshot3.
www.vmware.com
56
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
Now you make changes to Snapshot3 and create another snapshot (Snapshot4). You make more
changes and create a Snapshot5. You make changes to Snapshot5.
57
VMware Infrastructure SDK Programming Guide
Finally, you start another branch of the snapshot tree and make changes to Snapshot4, resulting in
a Snapshot6 and Snapshot7. The resulting tree looks like the following figure.
www.vmware.com
58
C H A P T E R 3 VMware Infrastructure SDK Key Concepts
Performance Monitoring
Clients can collect performance data on hosts , hosts, virtual machines, resource pools, or clusters
(VirtualCenter only). This data includes CPU and memory utilization, network and disk performance
data, and floppy and CD-ROM drive performance, and so on. You can specify the frequency of
updates (perf intervals), the number of samples in each update, and the performance data of
interest to the client. In addition, you can retain a history for the performance data. See Monitoring
Performance Data on page 145 for information about individual operations.
Perf Intervals
Performance statistics are collected at multiple defined intervals. The information is collected on
both the host agent and VirtualCenter according to the following pre-defined intervals:
• 20 second sample interval, retained one hour.
• Five minute sample interval, retained one day.
The information is collected on VirtualCenter according to the following pre-defined intervals:
• One hour sample interval, retained one week.
• Six hour sample interval, retained 30 days.
• One day sample interval, retained one year.
Each interval includes the frequency with which the statistics are collected as well as the length of
the time the statistics are kept in the database. For example, daily performance statistics are stored
in the database for one year. This means that one metric value per day is stored for up to one year.
You can define your own intervals with the following restrictions:
• The sample interval must be a multiple of the next shorter interval. Five minutes for one day
and seven minutes for two days is not valid. Five minutes for one day and ten minutes for two
days is valid. In the same way, if you have two existing intervals of five minutes and 15
minutes, you cannot create an interval of ten minutes. Even though the ten minute interval
would be a multiple of the next shorter interval, the 15 minute interval would not be a
multiple of the ten minute interval.
• The length the stats remain in the database must be longer than the previous setting. Five
minutes for two days and ten minutes for one day is not valid, but five minutes for two days
and ten minutes for one year is valid.
Each interval is identified by its sampling period (in seconds). This is the interval Id. For example,
the interval Id for an interval whose sample interval is five minutes is 300.
59
VMware Infrastructure SDK Programming Guide
www.vmware.com
60
Logging On
CHAPTER 4
When you write a client application, you always begin by logging on. This involves establishing
communication with the Web service using the service instance object. The service instance also
gives you access to the various session management objects, such as the authorization manager,
the task manager, and the event manager. It also gives you access to the inventory, which
organizes all your virtual machines and hosts.
This chapter includes the following topics:
• Session Management on page 62
• Instantiating an Instance and Opening a User Session on page 63
• Setting the Locale on page 64
61
VMware Infrastructure SDK Programming Guide
Session Management
The Web service maintains session state for a client by using a special token in the HTTP header to
identify the session. A session token is an identifier given to a Web service client upon login. This
identifier is used by the client to invoke operations over multiple connections because with every
connection, the identifier must be passed in the HTTP header, over any connection.
Session tokens can be passed across multiple connections to the Web service. A session token
expires after a period of inactivity, and can expire after a certain period of time.
www.vmware.com
62
C H A P T E R 4 Logging On
You can invoke using either http or https protocol. See Setting up the VMware Infrastructure
SDK Client on page 25 for information about configuring for these protocols.
3. Retrieve the service instance content by calling the RetrieveServiceContent operation,
passing in the service instance object reference as an argument to the operation.
The ServiceContent data object has references to a number of managed objects that provide
the capabilities to manage your virtual machine environment. One of these objects is the
session manager.
ServiceContent _sic = _service.retrieveServiceContent(_svcRef);
4. From the service instance content, obtain the reference to the session manager object.
The session manager reference might be presented as a property or as an accessor method,
such as getSessionManager().
5. Call the Login operation, passing the reference to the session manager, the user name, and
the password.
_service.login(_sic.getSessionManager(), username, password, null);
From the service instance content, you can obtain the reference to the root folder of the inventory
tree. The root folder has a ChildEntity property that you can use to traverse the inventory tree. The
root folder reference may be presented as a property or as an accessor method, such as
getRootFolder().
63
VMware Infrastructure SDK Programming Guide
www.vmware.com
64
Managing Inventory
CHAPTER 5
This chapter describes the following topics:
• Managing Folders and Datacenters on page 66
• Creating a Virtual Machine on page 69
• Managing Virtual Machine Templates on page 71
• Configuring a Virtual Machine on page 73
• Performing Power Operations on a Virtual Machine on page 79
• Migrating Virtual Machines on page 81
• Managing Virtual Machine Snapshots on page 84
• Managing Clusters and Resource Pools on page 89
• Managing Hosts on page 100
• Configuring Networks for a Host on page 106
• Renaming Managed Entities on page 112
• Managing Datastores on page 113
65
VMware Infrastructure SDK Programming Guide
Creating a Folder
You create folders in the inventory tree using the CreateFolder operation. This operation takes two
parameters:
• Folder managed object reference – The Folder within which you are creating the folder. The
easiest way is to use the FindByInventoryPath operation. See Obtaining a Managed Object
Reference on page 32 for additional ways to obtain a managed object reference.
• name – The name you want to give to the folder.
The operation returns a Folder managed object reference. This object inherits the value of the
childType property of its parent Folder object. The childType property determines the kinds of
objects you can create within the new folder. See The childType Property on page 48 for more
information.
Deleting a Folder
You can use one of two methods to delete a Folder: UnregisterAndDestroy_Task or Destroy_Task.
www.vmware.com
66
C H A P T E R 5 Managing Inventory
Creating a Datacenter
As described in Inventory Management on page 47, the Datacenter managed object is a container
object in which you store virtual machines and compute resources. A compute resource includes
one or more hosts and one or more resource pools.
You create a Datacenter with the CreateDatacenter operation. This operation takes the following
parameters:
• Folder managed object reference – This is the Folder object within which you want to create
the datacenter. You cannot create a datacenter within a Folder that is located within another
datacenter.
• name – The name of the datacenter. The name must be unique within the folder that
contains the new datacenter.
When you create a datacenter, the operation creates two root Folder objects at the first level of the
datacenter, as shown in the following figure: a root virtual machine Folder and a root host Folder.
...
Folder
Datacenter
vmFolder hostFolder
Within these folders and their children, you can create other Folder objects. You can also create
virtual machines or add hosts in the form of computer resources. The type of entity depends on
the value of the childType property of the root folder. (See The childType Property on page 48 for
more information.) Within the root virtual machine folder and its children, you can create virtual
machines and other folders. Within the root host folder, you can add hosts (either as a
ComputeResource or a ClusterComputeResource) and create other folders.
For information about creating virtual machines, see Creating a Virtual Machine on page 69. For
information about adding hosts, see Managing Hosts on page 100.
Deleting a Datacenter
You use the Destroy_Task operation to delete a Datacenter. The Destroy_Task operation takes as its
only parameter the Datacenter ManagedEntity managed object reference that you want to delete.
67
VMware Infrastructure SDK Programming Guide
This operation deletes the entire branch, including Folder objects, virtual machines, and any
associated datastore files. The operation removes the hosts from VirtualCenter management.
www.vmware.com
68
C H A P T E R 5 Managing Inventory
69
VMware Infrastructure SDK Programming Guide
www.vmware.com
70
C H A P T E R 5 Managing Inventory
Creating Templates
There are two ways to create templates: by changing an existing virtual machine to a template and
by cloning an existing virtual machine as a template.
71
VMware Infrastructure SDK Programming Guide
• To retain the template, clone the template by invoking the CloneVM_Task operation on the
template. In the VirtualMachineCloneSpec (the spec parameter) for the operation, set the
template property to false.
www.vmware.com
72
C H A P T E R 5 Managing Inventory
73
VMware Infrastructure SDK Programming Guide
• limit – The maximum allowed resource usage. The utilization of a virtual machine/resource
pool will not exceed this limit, even if there are available resources. This is typically used to
ensure a consistent performance of virtual machines / resource pools independent of
available resources. A value of -1 indicates no fixed limit on resource usage (only bounded by
available resources and shares). Units are MB for memory, MHz for CPU.
• shares – Shares represent a relative metric for allocating memory or processing capacity
among multiple virtual machines. The data object, SharesInfo, comprises two properties: level
and shares. The value of level can be custom, high, low, and normal.
If the level is custom, you use the shares property to define your own number of shares for
this machine. The high, low, and normal levels represent a pre-defined number of shares. (See
the SharesLevel enumerated list in the VMware Infrastructure SDK Reference Guide for the
number of shares for each level.) The level is compared to the level of the other virtual
machines. In general, a virtual machine with a high level gets proportionally more of the CPU
or memory allocation. The allocation is divided evenly between virtual machines with the
same level.
• expandableReservation – This boolean property determines whether or not the the
reservation on a resource pool can grow beyond the specified value, if the parent resource
pool has unreserved resources. A non-expandable reservation is called a fixed reservation.
This property is ignored for virtual machines.
www.vmware.com
74
C H A P T E R 5 Managing Inventory
75
VMware Infrastructure SDK Programming Guide
• Connection Information
The connectable property is a VirtualDeviceConnectInfo data object. This provides
information about restrictions on removing the device while a virtual machine is running. If
the device is not removable, then this property is null.
VirtualDeviceConnectInfo vdci = new VirtualDeviceConnectInfo();
// Allow the guest to control whether the virtual device is connected?
vdci.setAllowGuestControl(false);
// Is the device currently connected?
vdci.setConnected(true);
// Connect the device when the virtual machine starts?
vdci.setStartConnected(true);
• Defining the Controller Key, the Virtual Device Key, and the Unit Number
You define these items with the integer properties: controllerKey, key, and unitNumber. See
the VirtualDevice data object in the VMware Infrastructure SDK Reference Guide for more
information.
• Device Information
The deviceInfo property is a Description data object that comprises a name property and a
summary property. You can supply a string value for each, describing the device.
Description vddesc = new Description();
vddesc.setLabel('CD-ROM Device cdrom0');
vddesc.setSummary('The CD-ROM device for this virtual machine.');
www.vmware.com
76
C H A P T E R 5 Managing Inventory
77
VMware Infrastructure SDK Programming Guide
Defining IDs for Guest Operating System and Configuration File Location
The guestId property lets you define an identification for the guest operating system. The
locationId is a 128-bit hash incorporating the virtual machine's config file location and the UUID of
the host assigned to run the virtual machine.
Normally, this property is not set by a client, allowing the VMware Infrastructure environment to
assign a location ID when the virtual machine is created. However, if the virtual machine's
configuration file has been moved manually, you might need to clear this property (set it to the
empty string) so that it will be regenerated.
www.vmware.com
78
C H A P T E R 5 Managing Inventory
79
VMware Infrastructure SDK Programming Guide
shutdown. After the power state is poweredOff, the ResetVM_Task operation invokes the
PowerOnVM_Task operation.
Note: Although this operation powers off then powers on, the two operations are atomic with
respect to other clients. Other power operations cannot be performed until the reset method
completes.
www.vmware.com
80
C H A P T E R 5 Managing Inventory
Enabling Migration
Before you can perform a migration, both the source and target HostSystem objects must be
properly configured. This requires the following steps:
1. Configure TCP/IP on the VMkernel.
See Configuring TCP/IP on the VMkernel on page 106. During this process, if you are using
VMotion, you select a Virtual Network Interface Card (NIC). If necessary, you can modify the IP
information for the selected Virtual NIC using the UpdateIpConfig operation. See Updating
the VMotion IP Configuration on page 82 for more information.
2. Make sure the virtual machine is configured with the correct ethernet card backing
information. See Configuring the Virtual Machine for Migration on page 76.
3. If you are using VMotion, enable the VMotion feature.
See Enabling the VMotion Feature on page 81.
Every HostSystem object, through its configManager property, gives access to a vmotionSystem
property. This property is a reference to a HostVMotionSystem managed object. This object
contains the configuration for a hot migration.
Note: Both source and target HostSystem objects must be on the same network and must have
access to the same storage/VMFS volume(s) that the virtual machines utilize.
81
VMware Infrastructure SDK Programming Guide
www.vmware.com
82
C H A P T E R 5 Managing Inventory
Moving Files
When you migrate a virtual machine to a different host with the MigrateVM_Task operation, only
the virtual machine’s host association changes. The virtual machine’s disk files remain in their
original location. To move the disk files, you use the the RelocateVM_Task operation. Its parameters
are:
• VirtualMachine managed object reference – A reference to the virtual machine managed
object with the disk files to be moved.
• spec – A VirtualMachineRelocationSpec object. This object defines the specification of where
to relocate the virtual machine. This information includes some or all of the following:
• datastore – A reference to a Datastore managed object. The datastore where the virtual
machine should be located. If this parameter is not specified, the datasore defaults to the
current datastore.
• disk – An optional list that allows specifying the datastore location for each virtual disk.
• host – The target HostSystem managed object reference for the virtual machine. If not
specified, the host association is not changed or is derived from the ResourcePool.
• pool – The ResourcePool to which this virtual machine should be attached. For an import
operation, the is required. For a migrate or clone operation, if the is not supplied, the
resource pool of the source virtual machine is used.
• transform – Transformation (value is either sparse or flat) to perform on the disks. The
backend is free to ignore this hint if it is not valid for the current operation. This can be used
by clients, for example, to create sparse disks for templates.
When you invoke the RelocateVM_Task operation to move files, the virtual machine must be
powered off. You can also use the RelocateVM_Task operation to migrate a powered-off virtual
machine to a new host and move its disk files at the same time. Moving a Virtual Machine’s Virtual
Disks on page 238 shows a code sample of this operation.
Validating Migration
The ValidateMigration operation lets you test a migration before you actually perform the
migration using MigrateVM_Task or RelocateVM_Task.
83
VMware Infrastructure SDK Programming Guide
You can create snapshots, revert to any snapshot in the tree, and remove snapshots.
Note: If the virtual machine is associated with a host on an ESX 2.5 Server, you can only create a
maximum of one snapshot.
Creating Snapshots
The CreateSnapshot_Task operation lets you create snapshots of a virtual machine. The operation
takes a reference to the VirtualMachine managed object that you want to snapshot. In addition,
the operation takes the following required parameters:
• name – The name for this snapshot. The name need not be unique for this virtual machine.
• description – A description of the snapshot.
• memory – A boolean property. If set to TRUE, a dump of the internal state of the virtual
machine (basically a memory dump) is included in the snapshot. Memory snapshots
consume time and resources, and take longer to create.
• quiesce – A boolean property. If set to TRUE and the virtual machine is powered on when the
snapshot is taken, VMware Tools is used to quiesce the file system in the virtual machine. This
assures that a disk snapshot represents a consistent state of the guest file system(s).
www.vmware.com
84
C H A P T E R 5 Managing Inventory
The RenameSnapshot operation lets you change either the name or description (or both) of a
snapshot. The operation takes as one of its parameters a reference to the VirtualMachineSnapshot
managed object (Obtaining a VirtualMachineSnapshot Managed Object Reference on page 88).
The remaining parameters are the new name or description. The parameters must specify at least
one of these.
Note: RenameSnapshot is not supported on virtual machines associated with hosts on ESX 2.x
servers.
Reverting to Snapshots
After you have a snapshot tree built for any virtual machine, you can use one of two operations to
revert to the state of any snapshot in the tree.
The RevertToSnapshot_Task operation lets you revert to the state of any snapshot in the tree. For
example, in the following figure, you use the RevertToSnapshot_Task operation to revert to
Snapshot4. The operation takes as its only parameter a reference to theSnapshot4 managed
object. (See Obtaining a VirtualMachineSnapshot Managed Object Reference on page 88.) After
you revert to Snapshot4, the changes to Snapshot5 are lost although Snapshot5 still exists.
85
VMware Infrastructure SDK Programming Guide
Note: RevertToSnapshot_Task is not supported for virtual machines associated with hosts on an
ESX 2.x server.
The RevertToCurrentSnapshot_Task operation lets you revert to the state of the most recently
created snapshot. The operation takes two parameters:
• VirtualMachine managed object reference – The virtual machine with the current snapshot. If
no snapshot exists, then the operation does nothing, and the virtual machine state remains
unchanged.
• host – (optional) Choice of host for the virtual machine, in case this operation causes the
virtual machine to power on.
If a snapshot was taken while a virtual machine was powered on, and this operation is
invoked after the virtual machine was powered off, the operation causes the virtual machine
to power on to reach the snapshot state. You can use this parameter to specify a choice of
host where the virtual machine should power on.
If this parameter is not set, and the vBalance feature is configured for automatic load
balancing, a host is automatically selected. Otherwise, the virtual machine keeps its existing
host affiliation.
www.vmware.com
86
C H A P T E R 5 Managing Inventory
Note: RevertToCurrentSnapshot_Task is not supported for virtual machines associated with hosts
on an ESX 2.x server.
Removing Snapshots
To remove snapshots of a virtual machine, you have the following options:
• Remove a single snapshot from the tree.
• Remove a snapshot from a tree and all its children.
• Remove all the snapshots in the tree.
To remove a single snapshot, you use the RemoveSnapshot_Task operation. This operation takes
two parameters: the reference to the VirtualMachineSnapshot managed object you want to
remove (Obtaining a VirtualMachineSnapshot Managed Object Reference on page 88) and a
removeChildren boolean. To remove only the single snapshot, you set the boolean to false.
To remove a snapshot and its children, you use the same operation, but you set the boolean to
true. This removes the snapshot, its children, and any children of those children.
For example, the following figure shows a snapshot tree. If we remove Snapshot3 only, Snapshot1
becomes the new parent to the children of Snapshot3. If we remove Snapshot3 and its children,
the following snapshots are also removed: Snapshot4, Snapshot5, Snapshot6, and Snapshot7.
To remove all the snapshots in a tree, you use the RemoveAllSnapshots_Task operation with its
only parameter, a reference to the VirtualMachine managed object whose snapshots you want to
remove.
87
VMware Infrastructure SDK Programming Guide
See Getting Property Information on page 124 for details about creating and using a property
collector.
www.vmware.com
88
C H A P T E R 5 Managing Inventory
89
VMware Infrastructure SDK Programming Guide
• dasConfig – A ClusterDasConfigInfo data object. This object contains a boolean property for
enabling VMware HA. The other properties include:
• A boolean property that defines whether or not virtual machines are allowed to be
powered on if the configured failover level is violated.
• A property that lets you set the failover level, that is, the number of physical host failures
that can be tolerated without impacting the ability to satisfy the minimums for all running
virtual machines. If set, this value must be greater than zero. If the property is not set, then
the value defaults to one.
You can also use the option property to provide advanced settings.
• dasVmConfigSpec – An array of ClusterDasVmConfigSpec data objects. This array lets you
configure each virtual machine associated with the cluster. This comprises an info property of
the ClusterDasVmConfigInfo object whose properties include:
• key – A VirtualMachine managed object reference. The virtual machine configured for the
HA-enabled cluster.
• powerOffOnIsolation – This flag indicates whether or not the virtual machine should be
powered off if a host determines that it (the host) is isolated from the rest of the hosts in
the compute resource. This defaults to true.
• restartPriority – The preference given to the virtual machine if sufficient capacity is not
available to power on all failed virtual machines. The values are disabled (distributed
availability service is disabled for this virtual machine), high, low, and medium.
• drsConfig – A ClusterDrsConfigInfo data object. The object contains a boolean property for
enabling VMware DRS. The other properties include:
• defaultVmBehavior – This defines the default DRS behavior for the virtual machines in the
cluster. You can set the behavior to fullyAutomated, partiallyAutomated, and manual. See
the DrsBehavior enumerated type in the VMware Infrastructure SDK Reference Guide for
more information.
The value you set here is overridden by values set by the behavior property of the
ClusterDrsVmConfigSpec data object.
• vmotionRate – The amount of VMotion recommendations made: aggressive (more),
conservative (fewer), or normal (standard recommendation mode).
• drsVmConfig – An array of ClusterDrsVmConfigSpec data objects. Each element in the array
defines the DRS behavior for each virtual machine associated with a host in the cluster. This
consists of an info property of ClusterDrsVmConfigInfo data object, whose properties include:
• behavior – This property sets the DRS behavior for each virtual machine associated with a
host in the cluster. The values are: fullyAutomated, partiallyAutomated, and manual. See
www.vmware.com
90
C H A P T E R 5 Managing Inventory
the DrsBehavior enumerated type in the VMware Infrastructure SDK Reference Guide for
more information.
The value you set here overrides any default value set by the defaultVmBehavior property
of the ClusterDrsConfigInfo data object.
• key – The reference to the VirtualMachine managed object.
• pinned – If set to true, the virtual machine is “pinned” to its host. VirtualCenter cannot
perform any DRS migration or initial placement recommendations for this virtual machine.
The virtual machine is effectively excluded from resource scheduling. This property
defaults to false.
91
VMware Infrastructure SDK Programming Guide
www.vmware.com
92
C H A P T E R 5 Managing Inventory
The reservation property of the ResourceAllocationInfo object defines the minimum available
resources of the resource pool. As described in Resource Pool Subdivisions on page 39, the sum of
the reservation properties of a parent’s immediate children must be less than or equal to the
parent’s resources. You cannot configure a resource pool’s cpu or memory reservation in such a
way that the resources are overcommitted. You can determine the unreserved amount of cpu or
memory by checking the value of the parent resource pool’s runtime.cpu.unreservedForPool
property or runtime.memory.unreservedForPool property.
For example, in the following figure, the parent resource pool has memory resources equal to 60
gigabytes.
ClusterComputeResource (DRS)
20 GB ResourcePool
60 GB
Res ool
Res ool
ourc
10 GB
P
ourc
P
e
20 GB
e
Resource
Res ool
Pool
ourc
5 GB
P
e
Resource Resource
Pool Pool
15 GB 3 GB
The sum of the children’s reservation properties equals 40 gigabytes. When you want to create
another resource pool, you check the parent’s unreservedForPool property and find that you have
approximately 20 gigabytes available for the new resource pool.
Note: Always leave a “cushion” between the sum of the children and the parent. In other words, it
is recommended that the sum of the children never equal the parent.
If the amount you want to configure for the new resource pool would overcommit the resources
(the sum of the children is greater than the parent), you must reconfigure the reservation values of
the other children first, as shown in the following figure.
93
VMware Infrastructure SDK Programming Guide
ClusterComputeResource (DRS)
10 GB ResourcePool
30 GB
60 GB
Res ool
Res ool
Poo rce
ourc
5 GB
P
ou
ourc
P
l
Res
e
10 GB
e
Resource
Res ool
Pool
ourc
3 GB
P
e
Resource Resource
Pool Pool
4 GB 4 GB
Notice that the minimum resources (the reservation property) of the other children are now 10
gigabytes apiece, ensuring that the resource pool remains undercommitted. Notice also that the
children of those resource pools have been reconfigured to fit the new minimum of their parents.
When a resource pool has children, to ensure undercommitment, you must always reconfigure the
children first.
www.vmware.com
94
C H A P T E R 5 Managing Inventory
Defining Shares
Shares represent a relative metric for allocating memory or processing capacity among multiple
resource pools when there is contention. The data object, SharesInfo, comprises two properties:
level and shares. The value of level can be custom, high, low, and normal.
If the level is custom, you use the shares property to define your own number of shares for the
resource pool. The high, low, and normal levels represent a pre-defined number of shares. (See the
SharesLevel enumerated list in the VMware Infrastructure SDK Reference Guide for the number of
shares for each level.) The level is compared to the level of the other resource pools. In general, a
resource pool with a high level gets proportionally more of the CPU or memory allocation. The
allocation is divided evenly between resource pools with the same level.
95
VMware Infrastructure SDK Programming Guide
ClusterComputeResource (DRS)
20 GB ResourcePool
10 GB 60 GB
Res ool
Res ool
ourc
P
ourc
P
e
20 GB
e
5 GB
Resource
Res ool
4 GB Pool
Reso ool
ourc
P
Reso ool
e
P
urce
Resource Resource
P
urce
2 GB Pool Pool
15 GB
3 GB
Reso ool
P
10 GB Resource
urce
1 GB Pool
Resource Resource
Pool Pool
5 GB 3 GB
www.vmware.com
96
C H A P T E R 5 Managing Inventory
ClusterComputeResource (DRS)
10 GB
Resource
Resource
20 GB
Pool
Pool
4 GB
Resource
ResourcePool
Resource
Pool
1 GB
Pool
60 GB
Resource
Resource
20 GB 10 GB
Pool
5 GB
Pool
Res
ou urce
Res
our P ool rce Reso ool
Poo e c P urce 2 GB
l Reso ool
Res P
15 GB o urce
Poo urce Reso ool 3 GB
l P
3 GB 5 GB
Overcommitting Resources
Resource Pool Subdivisions on page 39 describes how the minimum available resources of the
immediate children must always be less than or equal the resources of the immediate parent.
In the figure above, the children’s resources are correctly undercommitted. The sum of the
minimum available resources of the immediate children (20+20+10+4) is less than the resources of
the parent (60 gigabytes).
The MoveIntoResourcePool operation does not allow you to overcommit resources. When the
operation is invoked, the resource pools are moved on an element-by-element basis as listed in
the array. If a resource pool’s minimum available resources causes the sum to exceed the parent,
then processing stops. The operation moves only those resource pools moved up to the point
when processing stops.
For example, in the figure below, the MoveIntoResourcePool operation attempts to move two
hierarchies (RP1 and RP2) to the root resource pool. The total resources in the root resource pool
are 55 gigabytes. The sum of the minimum available resources for the current immediate children
totals 40 gigabytes. The following code sample snippet invokes the operation:
MoveIntoResourcePool(rootMoRef, ManagedObjectReference[] {rp1Ref, rp2Ref});
Moving the first resource pool in the array (RP1) adds 10 gigabytes to the sum of the minimum
available resources for the current immediate children to 50 gigabytes (20+20+10). The total is still
within the resources of the 55 gigabyte root resource pool. Therefore, the operation moves RP1
successfully.
97
VMware Infrastructure SDK Programming Guide
Moving the second resource pool in the array (RP2) would add another 10 gigabytes
(20+20+10+10) bringing the sum to 60 gigabytes. Moving RP2 is not allowed, because this would
overcommit the resources of the root resource pool. Therefore, the attempt to move RP2 is
unsuccessful.
ClusterComputeResource (DRS)
Res ool
Reso ool
ourc
P
ourc
P
Reso ool
P
e
urce
20 GB
e
P
urce
5 GB 5 GB
Resource
Res ool
Pool
ourc
Reso ool
P
e
P
urce
Resource Resource
3 GB 15 GB Pool Pool
3 GB
RP2 10 GB Resource
Pool
Resource Resource
Pool Pool
5 GB 3 GB
To move RP2 successfully, before you invoke MoveIntoResourcePool, you must reconfigure the
resources of the other immediate children of the parent. See Reconfiguring Resource Pools on
page 91.
www.vmware.com
98
C H A P T E R 5 Managing Inventory
ClusterComputeResource (DRS)
3 GB
Resource
Resource
10 GB
Pool
Pool
Resource 10 GB
ResourcePool
Resource
Pool
5 GB
Pool
55 GB
Resource
Resource
10 GB 10 GB
Pool
5 GB
Pool
Res
ou urce
Res
our P ool rce Reso ool
Poo e c P urce 5 GB
l Reso ool
Res P
5 GB o urce
Poo urce Reso ool 3 GB
l P
3 GB 5 GB
In the figure above, the minimum resources of the other children are now 10 gigabytes apiece,
ensuring that the resource pool remains undercommitted. Notice also, however, that the children
of those resource pools have been reconfigured to fit the new minimum of their parents. When a
resource pool has children, to ensure undercommitment, you must always reconfigure the
children first.
99
VMware Infrastructure SDK Programming Guide
Managing Hosts
When you add a host in the VMware Infrastructure SDK, you can either add the host as a
standalone or you can add the host to an existing cluster of hosts.
Datacenter
...
ClusterComputeResource ComputeResource
www.vmware.com
100
C H A P T E R 5 Managing Inventory
101
VMware Infrastructure SDK Programming Guide
• resourcePool – (optional) The behavior of this parameter depends on whether the host being
moved is a standalone host or a host in a cluster.
• Moving a standalone host
If the host you are moving is a standalone host, this is the resource pool in the target
cluster to which the standalone host’s resource pool hierarchy is appended. If you provide
this argument, all virtual machines are moved with their original resource pool hierarchy. If
you do not provide this argument, all virtual machines are moved to the root resource pool
of the target cluster and the original resource pool hierarchy is discarded.
• Moving a clustered host
If the host you are moving is part of a cluster, this is the resource pool in the target cluster
to which the virtual machines are moved. If this argument is not provided, all virtual
machines are moved to the root resource pool of the new cluster.
Note: If you are moving a standalone host, then the ComputeResource with which the host was
associated is removed as part of this operation.
www.vmware.com
102
C H A P T E R 5 Managing Inventory
All virtual machines associated with a host remain associated with the host after the move. If there
are virtual machines you do not want to associate with the host, migrate them from the host
before initiating the operation. See Migrating Virtual Machines on page 81 for information about
migrating virtual machines.
See Moving Entities into a Folder on page 68 for the parameters and general information about the
MoveIntoFolder_Task operation.
103
VMware Infrastructure SDK Programming Guide
the correct set of agents is installed, and ensuring that networks and datastores are discovered and
registered with VirtualCenter. Any changes in virtual machines or templates registered in a host are
discovered.
The client can change the IP address and port of the host when doing a Reconnect_Task
operation. This can be useful if the client wants to keep the metadata (stats, alarms, privileges, and
so on) associated with the host in VirtualCenter, even though the host is changing its IP address.
Note: VirtualCenter does not store the administrator/root password (specified in the
HostConnectSpec) in the database. It uses this account only when connecting to the host for the
first time. It creates a separate account that is used for subsequent logins. It is this account
information that is saved in the database. Because of this, the first time you connect to a host
(either by invoking AddHost_Task with asConnected set to true or when calling Reconnect on a
host which was added in a disconnected state), you have to pass in a HostConnectSpec.
www.vmware.com
104
C H A P T E R 5 Managing Inventory
The operation uses the recommendation to migrate a set of virtual machines between the hosts in
the cluster to achieve the more efficient resource usage.
105
VMware Infrastructure SDK Programming Guide
www.vmware.com
106
C H A P T E R 5 Managing Inventory
107
VMware Infrastructure SDK Programming Guide
www.vmware.com
108
C H A P T E R 5 Managing Inventory
• nic – The HostVirtualNicSpec data object. This contains the networking information for the
VNIC: a DHCP boolean, the IP address, the subnet mask, and the MAC address.
Adding or Removing a Virtual Network Interface Card (VNIC) for the Service Console
To add the VNIC, you use the AddServiceConsoleVirtualNic operation. This operation takes the
following parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem
managed object to which you are adding the VNIC. See Obtaining the HostNetworkSystem
Managed Object Reference on page 111.
109
VMware Infrastructure SDK Programming Guide
• portgroup – The name of the port group with which you want to associate the VNIC. To
obtain this information, you can use a property collector to return a list of the port groups
associated with the HostNetworkSystem. See Getting Property Information on page 124 for
more information on using the property collector.
• nic – The HostVirtualNicSpec data object. This contains the networking information for the
VNIC: a DHCP boolean, the IP address, the subnet mask, and the Media Access Control (MAC)
address.
To remove the VNIC, you use the RemoveServiceConsoleVirtualNic operation. This operation takes
the following parameters:
• HostNetworkSystem managed object reference – A reference to the network that contains
the VNIC you are removing. See Obtaining the HostNetworkSystem Managed Object
Reference on page 111.
• device – The name of the service console VNIC you are removing.
www.vmware.com
110
C H A P T E R 5 Managing Inventory
can inherit policy settings from the virtual switch with which they are associated. These policy
settings are inherited if the settings for those characteristics on the port group are not set. Because
every policy setting on a port group is optional, every individual policy setting can be inherited. If
policies are set on both the port group and its virtual switch, the policies specified on the port
group take precedence.
The policies comprise the following:
• HostNicTeamingPolicy
This data object defines the connection to the physical network. This includes failure criteria,
active and standby NICs, failover, and load balancing information.
• HostNetOffloadCapabilities
This data object defines capabilities for checksum, TCP Segmentation Offloading, zero copy
transmits.
• HostNetworkSecurityPolicy
This data object defines the security policies for the network.
• HostNetworkTrafficShapingPolicy
This data object establishes parameters for three traffic characteristics: average bandwidth,
peak bandwidth, and the maximum burst size.
See the HostNetworkPolicy data object in the VMware Infrastructure SDK Reference Guide for more
information.
111
VMware Infrastructure SDK Programming Guide
www.vmware.com
112
C H A P T E R 5 Managing Inventory
Managing Datastores
Datastores on page 54 describes the basic concepts used in managing Datastores. This section
describes the major operations involved.
113
VMware Infrastructure SDK Programming Guide
www.vmware.com
114
C H A P T E R 5 Managing Inventory
Disk LUNs referenced by RDMs are found by examining all virtual machines known to the system
and visiting their virtual disk backends. If a virtual disk backend uses an RDM that is referencing a
disk LUN, the disk LUN becomes ineligible for use by a VMFS datastore.
115
VMware Infrastructure SDK Programming Guide
www.vmware.com
116
C H A P T E R 5 Managing Inventory
117
VMware Infrastructure SDK Programming Guide
iterate through the array to find the HBA you want to configure. For more information about using
a property collector, see Getting Property Information on page 124.
www.vmware.com
118
C H A P T E R 5 Managing Inventory
DNS server addresses, the default gateway, and the subnet mask. If the
dhcpConfigurationEnabled property is set to false, the other properties are ignored.
Note: The Media Access Control (MAC) address is not settable.
119
VMware Infrastructure SDK Programming Guide
• iScsiHbaId – The string that identifies the Host Bus Adapter. If you have not identified this
string, see Determining the HBA ID String on page 118.
• authenticationProperties – The HostInternetScsiHbaAuthenticationProperties data object.
This object contains three properties. The chapAuthEnabled property is a boolean that
determines whether or not CHAP is enabled. By default, this boolean is set to false. The
remaining properties define the CHAP user name and CHAP password.
www.vmware.com
120
C H A P T E R 5 Managing Inventory
121
VMware Infrastructure SDK Programming Guide
www.vmware.com
122
Getting Information and Updates
CHAPTER 6
This chapter describes the following topics:
• Getting Property Information on page 124
• Finding Entities Using a Property Value on page 135
• Getting Updates on Properties on page 140
123
VMware Infrastructure SDK Programming Guide
www.vmware.com
124
C H A P T E R 6 Getting Information and Updates
• If you want a reference to the managed object, rather than its properties, set the “all”
property of the PropertySpec object to false and do not set the pathSet property.
• If you want a specific property, or some of the properties, of the managed object, omit the
“all” property and set the “pathSet” property to contain the names of the properties you
want.
The form of the pathSet property depends on whether the property is nested property, a
simple property, or an array property.
• The property path name of a nested property is dot-separated. For example, the
VirtualMachine managed object has a runtime property that has a nested powerState
property. To select for the powerState property, you use the form
runtime.powerState. See Nested Properties and Property Paths on page 35 for more
information.
• The property path name of a simple property contains only the property name.
• The property path name of an array property is a special case of a nested property path
name. An array property represents a list of nested properties under a single property
name. Each nested property in the list is uniquely identified by a key value assigned by the
server. See Indexed and Key-Based Arrays on page 34 for more information.
Each PropertySpec object can specify a set of properties for a different managed object. This lets
you select a number of different managed objects and retrieve properties that are specific to the
different managed object types. For each type of managed object from which you want a
property, you must create a corresponding PropertySpec object.
A PropertySpec for a base class also applies to its derived classes. For example, if you set the type
property as “ManagedEntity” and the pathset property to "name", you do not need to specify that
property for the type Folder or VirtualMachine, because Folder and VirtualMachine are sub-classes
of ManagedEntity.
125
VMware Infrastructure SDK Programming Guide
object specified in the obj property. Each managed object visited during the traversal can be
selected for property retrieval, or can be used to continue the traversal. For more information
about traversing properties, see Traversing Managed Object Properties with a TraversalSpec
on page 126.
An ObjectSpec data object does up to three things:
• Sets the managed object where you want the collection of the information defined in the
PropertySpec to begin.
• If the skip property is set to false or omitted, checks the starting object to see if it should be
collected, that is, if it matches the managed object in the PropertySpec.
• If necessary, defines a traversal path with a selectSet property.
In the simplest use of an ObjectSpec, you set only the obj property. You omit the skip and selectSet
properties. The result is to select only the single managed object from which to retrieve properties.
See Defining a Simple PropertyFilterSpec (No Traversal) on page 127 for sample code.
www.vmware.com
126
C H A P T E R 6 Getting Information and Updates
PropertySpec object keyed to the type of the referenced object. Because the PropertySpec
normally causes the property collector to report properties of the referenced object, a true
value overrides the PropertySpec. Usually, it is safe to omit this field.
• selectSet – An array of SelectionSpec objects representing the next step of the traversal. Each
can be another TraversalSpec object or can name a TraversalSpec object defined elsewhere.
Each TraversalSpec object does up to three things:
• Traverses from one managed object (the type property) to another managed object (the
path property). The path value is a property of the managed object represented by the type
property.
• If the skip property is set to FALSE or omitted, the collector checks to see if the results of the
traversal (the path value) match the propSet value in the PropertySpec.
• If necessary, performs a traversal to additional objects, defined by the selectSet property.
The simplest use consists of three steps: constructing the object, performing the traversal, and
collecting the information. For examples of using TraversalSpec objects, see Defining a
PropertyFilterSpec with TraversalSpec Objects on page 128.
127
VMware Infrastructure SDK Programming Guide
www.vmware.com
128
C H A P T E R 6 Getting Information and Updates
/*
/ Define the managed object at which you want
/ the collection to begin. Set the skip property
/ to TRUE since you are not interested in the
/ datacenter object itself.
*/
ObjectSpec[] ospec = new ObjectSpec();
ospec.setObj(dCenterRef);
ospec.setSkip(Boolean.TRUE);
/*
/ Now define the traversal path. In this TraversalSpec,
/ the program traverses from a Datacenter managed object
/ (in this case, the starting object defined in the ObjectSpec)
/ to the managed object represented by the path value.
/ After the traversal is made, because the skip property is omitted
/ and defaults to FALSE, a collection check is done
/ on the result of the traversal (Datastore managed objects).
/ Notice that the selectSet property is omitted. No additional
/ traversal is needed.
*/
TraversalSpec tspec = new TraversalSpec();
tspec.setType("Datacenter");
tspec.setPath("datastore");
/*
/ Now that the TraversalSpec is defined, you
/ can set the selectSet property of the ObjectSpec.
/ After the starting object is traversed, this
/ defines the additional level that must be traversed.
*/
ospec.setSelectSet(new SelectionSpec[] {tspec});
129
VMware Infrastructure SDK Programming Guide
The resulting set of selected objects contains all those Datastore managed object references
reached by traversing the “datastore” property of the Datacenter object. The selection set is
complemented by the PropertySpec, which specifies collecting the freeSpace property from the
selected objects. Invoking the RetrieveProperties operation results in an array containing the
references to the Datastore managed objects in the Datacenter and the freeSpace property value
for each.
/*
/ _service, and _sic are variables created during log on.
/ See Logging On to the Web Service on page 198.
*/
www.vmware.com
130
C H A P T E R 6 Getting Information and Updates
rootFolder
Datacenter
vmFolder
You have a reference to the Datacenter managed object as the starting point, and you know that
your inventory hierarchy has a single root vmFolder under the Datacenter, and that there are no
nested folders. All the VirtualMachine objects are found exactly two levels below the Datacenter
object, and each can be reached by traversing exactly one Folder object.
public PropertyFilterSpec[] createPfSpecVms(ManagedObjectReference
dCenterRef) {
/*
/ First define the information you want to
/ collect: the type of managed object, the property
/ of that managed object. Set the all property
/ to FALSE, indicating you do not want to collect
/ all the properties of the managed object.
/ You only want the property specified by the propSet property.
*/
PropertySpec[] pspec = new PropertySpec();
pspec.setType(“VirtualMachine”);
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {“config.uuid”});
/*
/ Define the managed object that you want to set
/ as the initial object for the collection.
/ Next, define whether or not you want a collection
/ check performed on this object by setting the
/ skip property. Do you want the program to skip this object, or do you
/ want to check if this managed object matches the kind of
/ managed object you want to collect (defined by the PropertySpec).
/ Set the property to TRUE since you are not interested in whether
/ or not the datacenter is a datastore.
131
VMware Infrastructure SDK Programming Guide
*/
ObjectSpec[] ospec = new ObjectSpec();
ospec.setObj(dCenterRef);
ospec.setSkip(Boolean.TRUE);
/*
/ Now define the traversal path. For this collection,
/ you need to define two TraversalSpec objects:
/ one to traverse the Datacenter
/ and one to traverse the Folder below the Datacenter.
/
/ In dCenterTSpec, the program traverses from the
/ Datacenter to its child property, vmFolder.
/ The skip property is set to TRUE, ensuring that
/ no collection check is done on the result of the traversal
/ (the Folder managed object represented by vmFolder).
/ The selectSet property indicates that
/ another level needs to be traversed.
/
/ In folderTSpec, the program traverses from the
/ Folder (Type) to its child property, childEntity (Path), which in
/ this case is a VirtualMachine. The skip property is
/ set to FALSE, indicating that a collection check should
/ be done on the results of this traversal. The
/ VirtualMachine object matches the
/ PropertySpec, so the virtual machines are collected.
/
/ The code shows no selectSet property at this level, so the
/ traversal ends here.
*/
TraversalSpec folderTSpec = new TraversalSpec();
folderTSpec.setType("Folder");
folderTSpec.setPath("childEntity");
folderTSpec.setSkip(Boolean.FALSE);
/*
/ Now that the TraversalSpec objects are defined, you
/ can set the selectSet property of the ObjectSpec.
/ After the starting object is set, the selectSet
/ defines the next level that must be traversed.
*/
www.vmware.com
132
C H A P T E R 6 Getting Information and Updates
// Call retrieveServiceContent()
ServiceContent sic = vimService.retrieveServiceContent(sir);
133
VMware Infrastructure SDK Programming Guide
• specSet – A PropertyFilterSpec data object array. Specifies the information you want to
retrieve and the process by which retrieval will be obtained. See Defining the Information
Retrieval Process on page 124 for more information.
The following code snippet shows the operation:
ObjectContent[] ocs = vimService.retrieveProperties(pcr, pFilterSpec);
The RetrieveProperties operation retrurns an array of ObjectContent data objects. Each data object
comprises a reference to the object whose properties are returned and a list of name-value pairs,
one for each property of the object. Names of nested properties have the same form as a property
path name. For example, if a client requests a property of a VirtualMachine object named
runtime.powerState, the property is returned with name=runtime.powerState and
value=poweredOn.
www.vmware.com
134
C H A P T E R 6 Getting Information and Updates
135
VMware Infrastructure SDK Programming Guide
www.vmware.com
136
C H A P T E R 6 Getting Information and Updates
• dnsName – The DNS name. For a virtual machine, it is the one returned from VMware tools.
For a host, it is the combination of config.network.dnsConfig.hostName and
config.network.dnsConfig.domainName.
• vmSearch – A boolean. If true, the operation returns a virtual machine. If false, the operation
returns a host.
137
VMware Infrastructure SDK Programming Guide
www.vmware.com
138
C H A P T E R 6 Getting Information and Updates
rootFolder
Datacenter
Immediate child of Immediate child of
Datacenter Datacenter
vmFolder hostFolder
ResourcePool ResourcePool
Immediate children of
ComputeResource
139
VMware Infrastructure SDK Programming Guide
CheckForUpdates
The CheckForUpdates operation includes the following parameters:
• PropertyCollector managed object reference – A property of the ServiceContent data object.
You can obtain this managed object reference by using an accessor method as specified in
Obtaining a Managed Object Reference on page 32.
• version – Optional. The data version currently known to the client. The value can be either the
special initial version (an empty string) or a data version string that was returned from a
previous call to CheckForUpdates.
CheckForUpdates returns an UpdateSet data object that contains only the properties that have
changed since the last call, whereas RetrieveProperties retrieves all the properties each time,
www.vmware.com
140
C H A P T E R 6 Getting Information and Updates
regardless of whether they changed. If you invoke CheckForUpdates when there are no changes
since the last invocation, CheckForUpdates returns an empty UpdateSet.
WaitForUpdates
The WaitForUpdates operation provides the most efficient use of network resources. This operation
implements a form of change notification rather than the polling approach of CheckForUpdates.
WaitForUpdates does not complete until an update occurs, rather than returning an empty
UpdateSet data object. This blocks a processing thread in the client, but can be canceled from
another thread with the CancelWaitForUpdates operation. See Cancelling a Wait for Updates on
page 142.
The WaitForUpdates operation includes the following parameters:
• PropertyCollector managed object reference – A property of the ServiceContent data object.
You can obtain this managed object reference by using an accessor method as specified in
Obtaining a Managed Object Reference on page 32.
• version – Optional. The data version currently known to the client. The value must be either
the special initial version (an empty string), or a data version string that was returned from a
previous call to CheckForUpdates.
Returned Properties
Both CheckForUpdates or WaitForUpdates return properties in a list of PropertyFilterUpdate
objects. Each object represents a set of changes to properties that satisfy a PropertyFilter defined
by the client. The changes for each filter are organized in a list of object references and change
types, along with property name and value. As with the RetrieveProperties return values, names of
nested properties have the same form as a property path name.
Note: The WaitForUpdates operation might return redundant data for objects that have not
changed. Refer to SDK samples to find out how to correctly process changes so that future versions
of the VMware Infrastructure SDK do not adversely impact your code.
141
VMware Infrastructure SDK Programming Guide
// Call retrieveServiceContent()
ServiceContent sic = vimService.retrieveServiceContent(sir);
www.vmware.com
142
C H A P T E R 6 Getting Information and Updates
change list. However, a change to the toolsVersion property is ignored, because it is not
specified in the property filter.
Now suppose the client uses a filter that specifies the summary.guest property of a virtual
machine. If the toolsVersion property changes, that falls within the range of the new filter
because toolsVersion is a nested property of GuestInfo, the data object type of the guest
property. The guest property in turn is a nested property of VirtualMachineSummary, the
data object type of the summary property. A change to a data object is by definition a change to
one of its nested properties, because a data object has no single value of its own.
When an update set is returned to the client, the set can include a copy of the entire data object
called summary.guest, or it can return only the nested property (toolsVersion) that
changed. The choice is determined by the partialUpdates flag. If the flag is true, only the nested
property is returned. If the flag is false, the whole property specified in the property filter is
returned.
143
VMware Infrastructure SDK Programming Guide
www.vmware.com
144
Monitoring Performance Data
CHAPTER 7
Performance Monitoring on page 59 describes the basic concepts involved in monitoring
performance data. This chapter describes the operations involved, including the following topics:
• Configuring Intervals for Statistics on page 146
• Querying Statistics on page 148
• Querying Metadata Information on page 150
145
VMware Infrastructure SDK Programming Guide
The first parameter is the managed object reference for the PerformanceManager. The second
parameter refers to the PerfInterval object created prior to invoking to operation.
Note: You cannot change the sampling period for an interval. To change the sampling period,
you must delete the interval, then re-create the interval with a different sampling period.
www.vmware.com
146
C H A P T E R 7 Monitoring Performance Data
147
VMware Infrastructure SDK Programming Guide
Querying Statistics
The following operations let you gather statistics:
• QueryAvailablePerfMetric
• QueryPerf
• QueryPerfComposite
• QueryPerfProviderSummary
Retrieving MetricIds
The QueryAvailablePerfMetric operation gets the available performance statistic metrics for a
specified ManagedEntity between the optional "beginTime" and "endTime". Those are the
performance statistics that are available for querying for the given time interval.
queryAvailablePerfMetric(pmMor, meMor, 0900, 1200, 6000);
Because the other performance monitoring operations require one or more MetricIds, you invoke
this operation first to get a list of the MetricIds for a certain window in time.
Querying Statistics
The QueryPerf operation retrieves performance statistics for the specified metrics represented by
one or more metricIds for all the entities that are listed in the entity . The returned statistics are all
the available statistics between the optional startTime and endTime. If the optional metricId is not
provided, all metrics collected for the entity are returned. You must specify at least one entity to
this query. See Starting Time/Ending Time/Maximum Samples on page 60 for information about
using the optional startTime, endTime, and maxSample.
If you omit the optional Interval identifier, the operation will summarize across all the intervals. For
example, suppose you have two intervals, a five minute sample for one hour, and a one hour
sample for two days. The database persists 12 samples for each metric from now back to one hour
ago, then 23 samples for each metric from one hour ago to 24 hours ago.
www.vmware.com
148
C H A P T E R 7 Monitoring Performance Data
149
VMware Infrastructure SDK Programming Guide
QueryPerfCounter(pmMor, counterids);
www.vmware.com
150
Managing Events, Tasks, and Alarms
CHAPTER 8
Events, Tasks, and Alarms on page 49 describes the concepts behind events, tasks, and alarms in
the VMware Infrastructure SDK. This chapter includes the following topics:
• Logging a User-Defined Event on page 152
• Managing Tasks on page 153
• Retrieving Historical Information on page 159
• Managing Alarms on page 165
151
VMware Infrastructure SDK Programming Guide
www.vmware.com
152
C H A P T E R 8 Managing Events, Tasks, and Alarms
Managing Tasks
As described in Tasks on page 49, scheduled tasks are actions that you define on an entity in the
inventory tree according to a schedule.
153
VMware Infrastructure SDK Programming Guide
Notice that the argument property is not set. Because the task is defined on a Folder entity, the task
applies to the children of the Folder entity. The VirtualMachine managed object reference is
implied to be each virtual machine in the Folder’s tree. For this reason, the argument property is
not necessary.
www.vmware.com
154
C H A P T E R 8 Managing Events, Tasks, and Alarms
• OnceTaskScheduler – You can schedule the task to run only one time. The runAt property
(dateTime type) specifies the date and time to perform the task.
// Run the task once at the specified dateTime
OnceTaskScheduler ots = new OnceTaskScheduler ();
ots.setRunAt(dateTime);
• RecurrentTaskScheduler – The base type for the Hourly-, Daily-, Weekly-, and
MonthlyTaskScheduler objects. The interval property lets you define how often to run a
schedule task. For example, by setting the interval property with a value of 4 for an hourly
task, you cause the task to run every 4 hours.
• HourlyTaskScheduler – You schedule a task to run once every hour (or every specified
number of hours) at a specified time. Set the interval property to run the task after a specified
number of hours.
// Run the task every 4 hours at 30 minutes past the hour
HourlyTaskScheduler hts = new HourlyTaskScheduler();
hts.setMinute(30);
hts.setInterval(4);
• DailyTaskScheduler – You schedule a task to run every day (or every specified number of days)
at a specified hour and minute. You can set the interval property to run the task after a
specified number of days.
// Run the task every day at 30 minutes past the noon hour
DailyTaskScheduler dts = new DailyTaskScheduler();
dts.setMinute(30);
dts.setHour(12);
• WeeklyTaskScheduler – You schedule a task to run every week (or every specified number of
weeks) on a specified day (or days), hour, and minute. Seven boolean properties represent the
days of the week. You must set at least one of the properties to true. You can also set the
interval property to run the task after a specified number of weeks.
// Run the task every Monday and Wednesday
// at 30 minutes past the noon hour
WeeklyTaskScheduler wts = new WeeklyTaskScheduler();
wts.setMonday(true);
wts.setTuesday(false);
wts.setWednesday(true);
wts.setThursday(false);
wts.setFriday(false);
wts.setSaturday(false);
wts.setSunday(false);
dts.setMinute(30);
dts.setHour(12);
155
VMware Infrastructure SDK Programming Guide
• MonthlyByDayTaskScheduler – You schedule a task to run every month (or every specified
number of months) on a specified day at a specified hour and minute. You can also set the
interval property to run the task after a specified number of months.
// Run the task every 3 months(at 30 minutes past the noon hour)
// on the 31st day of the month (the last day if the month
// does not have 31 days)
MonthlyByDayTaskScheduler mbdts = new MonthlyByDayTaskScheduler();
mbdts.setDay(31);
mbdts.setInterval(3);
mbdts.setMinute(30);
mbdts.setHour(12);
Cancelling a Task
The CancelTask operation lets you cancel a running task that is either a scheduled task or the result
of an operation being invoked. The only parameter for the Cancel operation is a reference to the
Task managed object.
The operation cancels the current run of the scheduled task. It does not cancel subsequent runs of
the scheduled task. To cancel a scheduled task before it runs, the easiest way is to reconfigure the
www.vmware.com
156
C H A P T E R 8 Managing Events, Tasks, and Alarms
scheduled task to comment out or eliminate the run. See Configuring and Reconfiguring a
Scheduled Task on page 153.
157
VMware Infrastructure SDK Programming Guide
www.vmware.com
158
C H A P T E R 8 Managing Events, Tasks, and Alarms
159
VMware Infrastructure SDK Programming Guide
When you invoke this operation, you include the following parameters: the
EventHistoryCollector managed object reference and the maximum number of items you
want in the scrollable view. No items are returned if you have reached the end of the
collector.
The name property is derived from the vm, host, and datacenter properties of the Event object.
To format a string based on a specific context, you use the properties of the
EventDescriptionEventDetail data object:
• formatOnComputeResource – A string that’s appropriate for the context of a specific cluster.
For example, a powering on event in this context produces the following string:
"{vm.name} on {host.name} is powered on"
• formatOnHost – A string that’s appropriate in the context of a specific Host. For example, a
powering on event in this context produces the following string:
"{vm.name} is powered on"
• formatOnVm – A string that’s appropriate for the context of a specific virtual machine. For
example, a powering on event in this context produces the following string:
"Virtual machine on {host.name} is powered on"
www.vmware.com
160
C H A P T E R 8 Managing Events, Tasks, and Alarms
The oldName and newName properties are properties of the vmRenamedEvent data object.
• fullFormat – A string that’s appropriate for the root context. This produces the same string as
the fullFormattedMessage property of the Event object.
Formatting Event Messages on page 229 contains sample code that illustrates the use of these
structures.
161
VMware Infrastructure SDK Programming Guide
When you invoke this operation, you include the following parameters: the
TaskHistoryCollector managed object reference and maxCount (the maximum number of
items you want in the scrollable view).
• Invoke the ReadPreviousTasks operation
This operation lets you retrieve the previous page of items in the collector based on the
current position in the list. SeeModifying the Current Position on page 163 for an explanation
of current position and how to modify it.
When you invoke this operation, you include the following parameters: the
TaskHistoryCollector managed object reference and the maximum number of items you
want in the scrollable view. No items are returned if you have reached the end of the
collector.
Two Items
Added
Two Items
Oldest Removed Newest
{
www.vmware.com
162
C H A P T E R 8 Managing Events, Tasks, and Alarms
Current Position
Oldest Newest
{
Viewable Latest Page
Latest Page Size = 100
{
500 Tasks
You invoke the ReadNextTasks operation (with the maxCount parameter set to 100). The following
illustration shows the current position after the read.
163
VMware Infrastructure SDK Programming Guide
Current Position
Oldest Newest
{
{
maxCount = 100 Viewable Latest Page
Latest Page Size = 100
You can move to the beginning or end of the list using one of the following operations:
• ResetCollector – This operation moves the scrollable view to the item immediately preceding
the viewable latest page.
• RewindCollector – This operation moves the scrollable view to the oldest item.
For example, the following illustration shows the result of invoking ResetCollector on the
TaskHistoryCollector shown in the previous illustration.
Current Position
Oldest Newest
{
Viewable Latest Page
Latest Page Size = 100
Deleting a Collector
After you create a collector, the collector exists for the length of the session or until you invoke the
Remove operation. The Remove operation takes as its only parameter the reference to the
EventHistoryCollector or TaskHistoryCollector that you want to delete.
www.vmware.com
164
C H A P T E R 8 Managing Events, Tasks, and Alarms
Managing Alarms
As described in Alarms on page 50, alarms let you trigger actions conditionally. This section
describes the operations that let you manage alarms effectively.
Creating Alarms
You create an alarm by invoking the CreateAlarm operation. This operation requires three
parameters:
• AlarmManager managed object reference – You obtain this managed object reference by
invoking an accessor method on the alarmManager property of the ServiceContent data
object type. See Obtaining a Managed Object Reference on page 32.
• ManagedEntity managed object reference – The managed entity (or entities) whose
conditions will trigger the alarm. You can place an alarm on any managed entity. If the alarm
is placed on a leaf node in the inventory tree, it applies only to a single entity (VirtualMachine
or HostSystem). If the alarm is placed on a folder, a datacenter, a compute resource, or a
resource pool, it applies to the VirtualMachine or HostSystem descendants of the entity. You
obtain this managed object reference using a PropertyFilterSpec as described in Getting
Information and Updates on page 123.
• spec – The AlarmSpec data object type. The specification that defines the alarm. See
Configuring or Reconfiguring an Alarm on page 165.
This operation returns a reference to an Alarm managed object.
Note: See Creating and Monitoring Alarms on page 248 for a complete code sample using the
CreateAlarm operation.
165
VMware Infrastructure SDK Programming Guide
• setting – Through the AlarmSetting data object type, you can control how often an alarm is
allowed to trigger, as well as the tolerance range. The tolerance range defines a percentage
above or below the transition point. The alarm triggers only after reaching this point. See
Setting the Range and Frequency of a Metric Expression on page 168.
• enabled – This defines whether or not an alarm is enabled or disabled.
• name, description – The name and description of the alarm.
See the following sections for a further explanation of these properties.
www.vmware.com
166
C H A P T E R 8 Managing Events, Tasks, and Alarms
Red
90 x x x
Yellow
75 x x x
Green
CPU Usage
In this case, an entity transitions from green to yellow when its CPU usage is above 75. The entity
transitions from yellow to red when its CPU usage is above 90. You define the value of each
threshold using a MetricAlarmExpression object, then you set the threshold using the red or yellow
property of the VMMetricAlarmExpression object.
Note: The red and yellow properties are optional, but you must set one of these properties. You
can decide on one or two trigger points for each alarm expression. If you need only one trigger
point, set only the yellow value (or state) for the expression. If you need two trigger points, set both
the yellow and red values (or states).
The following code snippet defines these transitions when checking the CPU usage on a virtual
machine:
// Simple metric expression Red = CPU > 90, Yellow = CPU > 75
167
VMware Infrastructure SDK Programming Guide
alarmExpression.setRed(90);
alarmExpression.setYellow(75);
The operator property defines the operation to be tested, in this case, whether or not the CPU
usage is above the red or yellow threshold points.
www.vmware.com
168
C H A P T E R 8 Managing Events, Tasks, and Alarms
how often the alarm will be triggered, as well as set a tolerance range, above or below a transition
point. The setting property is an AlarmSetting data object type. This object comprises two
properties: reportingFrequency and toleranceRange.
In the following figure, you can see that CPU usage transitions to red approximately every five
seconds.
Red
90
Yellow
75
Green
5 seconds 10 15 20
CPU Usage
By setting the reportingFrequency property to 0 (the default), you can have the alarm triggered as
often as the transition point is passed. Alternatively, by setting the same property to a non-zero
integer (representing a number of seconds), you can have subsequent triggers suppressed for the
number of seconds represented by the integer.
In the following figure, the CPU usage transitions from yellow to red and red to yellow at 90.
169
VMware Infrastructure SDK Programming Guide
Red
90 x x x
Yellow
75 x x x
Green
CPU Usage
By setting the toleranceRange property, however, you can choose a ± tolerance range. By setting
the property to 0, the alarm triggers whenever the metric value is above or below the transition
point. By setting the property to a non-zero integer, you are choosing to trigger the alarm only
after reaching a certain percentage (represented by the integer) above or below the transition
point.
The following code snippet sets a reporting frequency of 20 seconds and a tolerance range of
±5%:
AlarmSetting asetting = new AlarmSetting();
asetting.setReportingFrequency(20);
asetting.setToleranceRange(5);
www.vmware.com
170
C H A P T E R 8 Managing Events, Tasks, and Alarms
• statePath – The path of the state property. The value of this string property depends on
whether the value of the type property is “VirtualMachine” or “HostSystem”.
• If the type property is “VirtualMachine”, the supported values are “runtime.powerState” and
“runtime.connectionState”.
• If the type property is “HostSystem”, the supported value is “runtime.connectionState”.
• operator – The operation to be tested on the target state: isEqual or unEqual.
• red – The value of the red condition. If the property is not set, the red status is not calculated.
• yellow – The value of a yellow condition. If the property is not set, the the yellow status is not
calculated.
The value of the red or yellow property depends on whether the type property is “VirtualMachine”
or “HostSystem”:
• If the type is “VirtualMachine”, the supported values are the values of the runtime.powerState
enumerated list (poweredOn, poweredOff, suspended) and runtime.connectionState
enumerated list (connected, disconnected, notResponding).
• If the type is “HostSystem”, the supported values are the values of the
runtime.connectionState enumerated list (connected, disconnected, notResponding).
Note: If both the red and yellow properties are set, they cannot contain the same value.
The following code snippet shows a state alarm expression defined to check the state of a virtual
machine:
// Simple metric expression Red = poweredoff, Yellow = suspended
StateAlarmExpression checkVM = new stateAlarmExpression();
checkVM.setType(“VirtualMachine”);
checkVM.setStatePath(“runtime.powerState”);
checkVM.setOperator(StateAlarmOperator.isEqual);
checkVM.setRed(“poweredOff”);
checkVM.setYellow(“suspended”);
The value of the alarm expression is determined by comparing the red and/or yellow properties
with the state of the managed entity. In this case, the alarm expression is “red” if the state of the
managed entity is “poweredOff”. The state is “yellow” if the state is “suspended”. Otherwise, the
state is “green”. For more explanation, see the StateAlarmExpression data object in the VMware
Infrastructure SDK Reference Guide.
171
VMware Infrastructure SDK Programming Guide
The AlarmTriggeringAction lets you fire off a single action based on one or more triggering
transitions (from green to yellow, red to yellow, and so on). The GroupAlarmAction lets you fire off
multiple actions that will occur when the alarm is triggered.
The actions are defined through the action property of type Action. You define the actions
through its child data object types:
• MethodAction – Actions are invoked using an operation in the API. This data object type
includes two properties: name and argument. The name is the name of the operation you
want to invoke. The string must appear exactly as the name appears in the WSDL. The
argument is an array consisting of the arguments for the operation.
If the Alarm is defined on a container entity (such as a Folder or Datacenter), then the
argument property does not require a managed object reference. For example, the
PowerOffVM_Task operation normally requires one parameter, a reference to a
VirtualMachine managed object. The following code snippet pre-supposes an alarm defined
on a Folder entity. In this case the VirtualMachine managed object reference is implied, so the
argument property is not necessary.
// Alarm action
// Power off all virtual machines in a certain folder that
// meet the triggering conditions.
MethodAction meAction = new MethodAction();
meAction.setName("PowerOffVM_Task");
• RunScriptAction – An action that runs a script. The script property is a string that contains a
fully qualified path to a shell script that runs on the VirtualCenter server.
• SendEmailAction – Sends an email. This data object type consists of four properties:
• body – The content of the email notification.
• ccList – A comma-separated list of addresses that are copied on the email notification.
• subject – The subject of the email notification.
• toList – A comma-separated list of addresses to which the email notification is sent.
• SendSNMPAction – Sends an SNMP trap.
The following code snippet shows the SendEmailAction triggered for the condition defined in
Defining a Metric Alarm Expression on page 166.
// Alarm action...
// Send an email
SendEmailAction seAction = new SendEmailAction();
seAction.setToList("sdk-bounces@vmware.com");
seAction.setSubject("VM CPU Alarm triggered");
seAction.setBody("You should check out your VMs!");
www.vmware.com
172
C H A P T E R 8 Managing Events, Tasks, and Alarms
173
VMware Infrastructure SDK Programming Guide
Deleting an Alarm
After you create an alarm with the CreateAlarm operation, the alarm will remain active until you
either disable the alarm, using the enabled boolean property of the AlarmSpec data object type, or
delete the alarm using the RemoveAlarm operation.
The RemoveAlarm operation requires as its only parameter a reference to the Alarm managed
object that you want to remove. As described in Getting Information and Updates on page 123,
you use a property collector to obtain the managed object reference.
The following code snippet shows the code for deleting an alarm:
// Remove Alarm
service.removeAlarm(alarmMoRef);
Disabling an Alarm
To disable an alarm, you reconfigure the alarm using the enabled boolean property of the
AlarmSpec object. To do this, you define a new AlarmSpec object. See Configuring or
Reconfiguring an Alarm on page 165.
For example, the following code snippet shows the enabled property being set to false:
// Spec for the whole thing
AlarmSpec alarmSpec = new AlarmSpec();
alarmSpec.setName("VM CPU");
alarmSpec.setDescription("Red = CPU > 90, Yellow = CPU > 75");
alarmSpec.setEnabled(false);
alarmSpec.setExpression(alarmExpression);
alarmSpec.setAction(alarmAction);
reconfigureAlarm(alarmMoRef, alarmSpec);
www.vmware.com
174
Managing Users
CHAPTER 9
To perform actions (invoke operations or read certain properties) within the VMware Infrastructure
SDK, a user must have the right set of privileges either as the user or as a member of a group which
has the privileges. Security Management on page 176 describes the concepts that comprise the
security model in the VMware Infrastructure SDK. The remaining sections describes the operations
that let you manage those concepts.
This chapter contains the following topics:
• Security Management on page 176
• Adding and Maintaining Users and Groups (ESX only) on page 182
• Querying for Users and Groups on page 184
• Adding and Maintaining Authorization Roles on page 185
• Setting and Maintaining Permissions on an Entity on page 186
• Querying for Permissions on page 188
• Obtaining a Reference to the AuthorizationManager on page 189
175
VMware Infrastructure SDK Programming Guide
Security Management
You must have one or more authorization privileges before you can invoke perform actions in the
VMware Infrastructure SDK. Authorization is defined by permissions and roles. Each role is assigned
one or more authorization privileges. Each permission associates a user or group with a role that
contains privileges applied to the entity.
Privileges
Privileges are the basic individual rights required to perform actions and read properties. They are
statically defined and never change for a single version of a product. Privileges have the following
format:
<group>[.<group>].privilege
www.vmware.com
176
C H A P T E R 9 Managing Users
• UpdateChildResourceConfiguration
• UpdateConfig
• SetEntityPermissions
• ResetEntityPermissions
For example, to delete a datacenter, you invoke the Destroy_Task operation on the Datacenter
managed entity. To invoke this operation successfully, you must have the Datacenter.Delete
privilege not only on the Datacenter entity being deleted, but also on the datacenter’s parent
Folder entity.
For specific information about privileges, see the description of these operations in the VMware
Infrastructure SDK Reference Guide.
Roles
Roles are an aggregation of privileges, grouped for convenience. The two types of roles are: system
roles and user-defined roles.
The system roles are:
• Administrator – Super-user access, or the set of all defined privileges. The system maintains
that this special role must be granted to a user or group on the root node, to ensure that at
least one way to change access rights always exists.
• Read-Only User – Read-only access, or the set of no mutating privileges. This role is
equivalent to a user-defined role with no privileges assigned to it. A user with this role can
read any data or properties and invoke query methods, but cannot make any changes to the
system.
• No Permission – No access. This role indicates that a user or group is explicitly denied access.
A user cannot see objects where this role has been granted. It is used primarily to mask out
sub-trees where a higher-level propagated permission has been defined.
You can also provide user-defined roles, such as:
• Virtual Machine Administrator – Comprises the privileges necessary to manage virtual
machines and hosts within the system.
177
VMware Infrastructure SDK Programming Guide
• Datacenter Administrator –Comprises the privileges necessary to manage resources but not
interact with virtual machines.
• Virtual Machine Provider – Comprises the privileges necessary to provision resources.
• Virtual Machine Power User – Comprises the privileges for a virtual machine user that can also
make configuration changes and create new virtual machines.
• Virtual Machine User – Comprises the privileges necessary to interact with, but not
reconfigure, virtual machines.
You can modify these roles and also define your own roles to include customized sets of privileges.
For example, suppose you have one or more users whose role is to create virtual machines. You
create a role that includes the privilege for invoking the operation that accomplishes this role.
Permissions
You assign privileges by setting a permission for a user or group on a ManagedEntity. Permissions
are access-control rules that specify the following:
• The user or group ("principal") to which the rule applies
• The role that specifies the privileges being granted to the user or group
You assign this permission to a ManagedEntity. If the privileges are for operations or properties
associated with managed objects that are not managed entities, then you assign the permission to
the rootFolder managed entity. If the privileges are for operations or properties associated with
managed entities, then you set the permission on a specific managed entity (folder, datacenter,
and so on).
To continue the example described in the last section, after you add the authorization role with the
privileges for virtual machine inventory, you create a permission that associates the user or users
(in the form of a group) with that authorization role. Then you assign the permission to a specific
ManagedEntity. Because the operation to create virtual machines is associated with a Folder
managed entity, you assign this permission to the specific Folder where you want the user to be
able to create virtual machines.
www.vmware.com
178
C H A P T E R 9 Managing Users
rootFolder (N)
Datacenter (N)
VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) ComputerResource ComputeResource ComputerResource ComputeResource
ResourcePool ResourcePool
In this figure, a user is granted permission on the vmFolder ManagedEntity. The propagate flag is
set to true. In this case, the user can not only “see” the vmFolder ManagedEntity but can perform
operations on the entity as defined by privileges associated with the role assigned to the
permission. Because of the setting of the propagate flag, the user can also see and perform
operations on the VirtualMachine entities within the vmFolder. The priviliges, however, are not
assigned “up”. While the user can see the Datacenter, its parent Folder, and the rootFolder, the user
cannot perform operations on these entities. To do that, the user would have to be assigned
permission to the parent entities in one of the following ways:
• Assign permission for the user to each of the managed entities, or
• Find the node at which (and below) the user needs authorization, then assign permission at
that level.
For example, if you assign permission at the Datacenter node (with the propagate flag set to
true), the user can perform the authorized operations on the Datacenter and any entities
below the Datacenter, including the vmFolder, hostFolder, virtual machines, compute
resources, hosts, and so on.
179
VMware Infrastructure SDK Programming Guide
These complex entities affect setting and querying permissions. For details, see Setting, Updating,
or Resetting Entity Permissions on page 186 and Querying for the Permissions on a Specific Entity
on page 188.
www.vmware.com
180
C H A P T E R 9 Managing Users
a case unique to virtual machines because they have a special relationship with resource pools. All
other entities (Folder, Datacenter, ComputeResource) have only one parent.
Note: Virtual machine templates are not associated with a resource pool. They get permissions
only from their containing folder.
181
VMware Infrastructure SDK Programming Guide
www.vmware.com
182
C H A P T E R 9 Managing Users
This operation lets you remove a user from a group. The parameters include a
HostLocalAccountManager managed object reference, the user acount that you want to
unassign, and the group from which you want to unassign the user. Use the
RetrieveUserGroups operation to get the user and group account. See Querying for Users and
Groups on page 184.
183
VMware Infrastructure SDK Programming Guide
www.vmware.com
184
C H A P T E R 9 Managing Users
185
VMware Infrastructure SDK Programming Guide
www.vmware.com
186
C H A P T E R 9 Managing Users
• A propagate boolean that defines whether or not the permission extends to include the
children of the ManagedEntity (for an explanation, see Permissions and Sub-Objects on
page 178).
Note: SetEntityPermissions and ResetEntityPermissions require that you have the
Authorization.ModifyPermissions privilege on the entity for which you want to set/reset
permissions as well as its parent.
187
VMware Infrastructure SDK Programming Guide
www.vmware.com
188
C H A P T E R 9 Managing Users
_sic = _service.retrieveServiceContent(_svcRef);
ManagedObjectReference _authManRef = _sic.getAuthorizationManager();
189
VMware Infrastructure SDK Programming Guide
www.vmware.com
190
Creating a Simple Java Client
CHAPTER 10
Application
This simple client retrieves and prints a list of all the managed entities known to the Web service
server.
package com.vmware.vimsample.simpleclient;
import java.net.URL;
import javax.xml.rpc.Stub;
/**
* This is a simple standalone client whose purpose is to demonstrate the
* process for Logging into the Webservice, and get Inventory contents
* starting at the root Folder available in the ServiceInstanceContent
*/
public class SimpleClient {
191
VMware Infrastructure SDK Programming Guide
/**
* Create the Managed Object Reference for the service
*
* @param svcRefVal to define service reference for HostAgent or VPX
*/
public void createServiceRef() throws Exception {
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
/**
* Creates an instance of the VMA proxy and establishes a connection
*
* @param url web service url
* @param username authorized user
* @param password authorized password for user
*/
public void connect(String urlStr, String username, String password)
throws Exception {
if (_service != null) {
disconnect();
}
_sic = _service.retrieveServiceContent(_svcRef);
_propCol = _sic.getPropertyCollector();
_rootFolder = _sic.getRootFolder();
if (_sic.getSessionManager() != null) {
_service.login(_sic.getSessionManager(), username, password, null);
}
}
/**
* Log's out and Disconnects from the WebService
www.vmware.com
192
C H A P T E R 1 0 Creating a Simple Java Client Application
*/
public void disconnect()throws Exception {
if (_service != null) {
// does not work at this time
//_service.logout(_svcRef);
_service = null;
_sic = null;
}
}
/**
* Get all entities accessable from rootFolder
*/
public void getAndPrintInventoryContents()throws Exception {
193
VMware Infrastructure SDK Programming Guide
datacenterHostTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });
www.vmware.com
194
C H A P T E R 1 0 Creating a Simple Java Client Application
if (pcary != null) {
for (int pci = 0; pci < pcary.length; pci++) {
pc = pcary[pci];
System.out.println(" Property Name : " + pc.getName());
if (pc != null) {
if (!pc.getVal().getClass().isArray()) {
System.out.println(" Property Value : " +
pc.getVal());
}
else {
Object[] ipcary = (Object[])pc.getVal();
System.out.println("Val : " + pc.getVal());
for (int ii = 0; ii < ipcary.length; ii++) {
Object oval = ipcary[ii];
if(oval.getClass().getName().indexOf(
"ManagedObjectReference") >= 0) {
ManagedObjectReference imor =
(ManagedObjectReference)oval;
195
VMware Infrastructure SDK Programming Guide
/**
* The main entry point for the application.
*/
public static void main(String[] args) {
if (args == null || args.length != 3) {
System.out.println(
"Usage : SimpleClient <webserviceurl> <username> <password>"
);
}
try {
// Create the Service Managed Object Reference
sc.createServiceRef();
To compile the simple client, add the directory containing SimpleClient.java to the
CLASSPATH variable, and compile SimpleClient.java using javac.
To run the application, type:
java SimpleClient protocol://<server_name_or_ip_address>/sdk
<username> <password>
This client application returns a list of all the virtual machines. If there are no virtual machines, use
the VMware VirtualCenter interface to create some.
www.vmware.com
196
Java Code Examples for Basic
CHAPTER 11
Operations
The sample code snippets in this chapter represent a small portion of code and are designed only
to show the basic logic and programming constructs needed to use the VMware Infrastructure
SDK effectively. A complete listing of compilable samples is contained in the in the
SDK\samples_2_0\Axis\java\com\vmware\vimsample directory.
This chapter covers the following topics:
• Logging On to the Web Service on page 198
• Basic Data Synchronization Loop on page 199
• Handling Permissions and Roles on page 201
• Getting Information About Properties on page 210
• Getting Updates on an Inventory Object on page 214
• Handling Exceptions in the Data Synchronization Loop on page 215
• Testing on page 216
197
VMware Infrastructure SDK Programming Guide
www.vmware.com
198
C H A P T E R 1 1 Java Code Examples for Basic Operations
199
VMware Infrastructure SDK Programming Guide
objUpdate[0].getChangeSet()[0].getVal());
}
}
Thread.sleep(10000);
}
_service.logout(_sic.getSessionManager);
}
}
This code polls the Web service server every 10 seconds to obtain a fresh copy of the data
corresponding to a specific virtual machine. The preceding code works for a simple application,
but it will not scale to a system that is managing a large number of virtual machines and other
entities, due to the large amount of network traffic it generates.
The previous code polls for changes only every 10 seconds. Any changes to the power state
between those polling periods is lost. A more efficient way to pool the Web service server, one that
catches any changes, is to replace the while loop with the WaitForUpdates operation. Because
WaitForUpdates does not complete until an update happens, it is best to invoke this operation on
a separate thread.
www.vmware.com
200
C H A P T E R 1 1 Java Code Examples for Basic Operations
try {
_service.createUser(_sic.getAccountManager(), acctSpec);
}
catch (AlreadyExists exists){
System.out.println("Local user account already exists.");
}
catch (Invalid inVal) {
System.out.println("Id or password is in an invalid format.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}
201
VMware Infrastructure SDK Programming Guide
/*
* Construct a HostAccountSpec for the new group. Note that, as described
* in Adding and Maintaining Users and Groups (ESX only) on page 182, no password is
* set when creating a group.
*/
HostAccountSpec groupAcctSpec = new HostAccountSpec();
acctSpec.setDescription("A group account");
acctSpec.setId("groupacct");
try {
_service.createGroup(_sic.getAccountManager(), acctSpec);
}
catch (AlreadyExists exists){
System.out.println("Local group account already exists.");
}
catch (Invalid inVal) {
System.out.println("Id or password is in an invalid format.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}
The following code snippet adds the created user to the group.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
_service.assignUserToGroup(_sic.getAccountManager(), "rbothne",
"groupacct");
}
catch (NumberFormatException number){
System.out.println("The user or group id should be an integer.");
}
catch (AlreadyExists member){
System.out.println("The user is already a member of this group.");
}
catch (UserNotFound noFind) {
System.out.println("The user or group does not exist.");
}
catch (RuntimeFault rFault) {
www.vmware.com
202
C H A P T E R 1 1 Java Code Examples for Basic Operations
Adding AuthorizationRoles
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
String roleName = "MgeRoles";
String privs[] = {"Authorization.ModifyRoles", "System.View"};
AddAuthorizationRole(_sic.getAuthorizationManager(), roleName,
privs);
catch (AlreadyExists exists){
System.out.println("Name already exists.");
}
catch (InvalidName inVal) {
System.out.println("Name is not provided.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}
203
VMware Infrastructure SDK Programming Guide
www.vmware.com
204
C H A P T E R 1 1 Java Code Examples for Basic Operations
try {
_service.setEntityPermissions(_sic.getAuthorizationManager(), meRef,
Permissions[] {p1, p2, p3});
}
catch (NotFound nFound){
System.out.println("The role does not exist.");
}
catch (Invalid inVal) {
System.out.println("The role is a system role.");
}
catch (RemovedFailed failed) {
System.out.println("The role has permissions and cannot be
205
VMware Infrastructure SDK Programming Guide
removed.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}
Merging Permissions
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
_service.mergePermissions(_sic.getAuthorizationManager(),
mySourceRole, myDestRole);
}
catch (NumberFormatException number){
System.out.println("The role id must be an integer.");
}
catch (NotFound nFound){
System.out.println("The role does not exist.");
}
catch (Invalid inVal) {
System.out.println("Either the destination role is
the View or Anonymous role, or both role IDs are the same.");
}
catch (AuthMinimumAdminPermission minAdmin) {
System.out.println("The source role is an Administrator role.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}
www.vmware.com
206
C H A P T E R 1 1 Java Code Examples for Basic Operations
207
VMware Infrastructure SDK Programming Guide
Removing a Permission
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
ManagedEntity meRef = FindByInventoryPath(_sic.getSearchIndex,
PathToEntity);
boolean group = false;
_service.removeEntityPermissions(_sic.getAuthorizationManager(),
meRef,
rbothne,
group);
}
catch (AuthMinimumAdminPermission minAdmin){
System.out.println("this change would leave the system with no
Administrator permission on the root node.");
}
catch (NotFound nFound){
System.out.println("A permission for this entity and user or group
does not exist.");
}
www.vmware.com
208
C H A P T E R 1 1 Java Code Examples for Basic Operations
209
VMware Infrastructure SDK Programming Guide
rootFolder
Datacenter
vmFolder hostFolder
ResourcePool ResourcePool
To begin, you create two PropertySpec data objects and an ObjectSpec data object. Each
PropertySpec defines one managed object and the information (properties) you want to collect
about that managed object. In each PropertySpec, the all property is set to FALSE indicating that
you do not want to collect all the information about the managed object.
As described in Defining the Property Collection with an ObjectSpec on page 125, the ObjectSpec
data object does three things:
• Sets the managed object where you want the collection to begin.
• Defines whether or not to check the starting object to determine whether it should be
“skipped” or collected, that is, if it matches the managed object in the PropertySpec.
www.vmware.com
210
C H A P T E R 1 1 Java Code Examples for Basic Operations
• If necessary, defines a traversal path with a selectSet property. Because one or more
TraversalSpec data objects comprise the selectSet property, the selectSet is added later in the
code.
public PropertyFilterSpec[] createPfSpec2(ManagedObjectReference objRef)
{
Now you define the TraversalSpec data objects for each possible path through the hierarchy. As
described in Traversing Managed Object Properties with a TraversalSpec on page 126, each
TraversalSpec object comprises up to three things:
• A traversal from one managed object, represented by the type property, to another managed
object, represented by the path property. The path value is a property of the source managed
object (type)
• A collection. Unless the skip property is set to false, the collector checks to determine
whether the results of the traversal (the path value) matches the propSet value in the
PropertySpec. (If the skip property is omitted, the value defaults to FALSE.)
• A traversal to additional objects, defined by a selectSet property.
For this program, you define six TraversalSpec objects to cover the six possible paths through the
hierarchy:
• Folder --> childEntity.
A Folder can traverse to either another Folder or to some managed entity, such as a
VirtualMachine. See Folder in the VMware Infrastructure SDK Reference Guide for a more
detailed explanation of the childEntity property.
• Datacenter --> hostFolder
• Datacenter --> vmFolder
• ComputeResource --> resourcePool
211
VMware Infrastructure SDK Programming Guide
Now that you have defined the TraversalSpec objects, you can add the selectSet property to the
ObjectSpec. As described earlier, this describes the next traversal from the starting object. Notice
www.vmware.com
212
C H A P T E R 1 1 Java Code Examples for Basic Operations
that, because we do not know the starting object, all the TraversalSpec objects are represented. If a
TraversalSpec does not match the starting object, the program moves on to the next element in
the array.
oSpec.setSelectSet(new SelectionSpec[]{folderTSpec});
Now you define the PropertyFilterSpec itself and its return value.
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] {pspec, pspec2});
pfSpec.setObjectSet(new ObjectSpec[] {ospec});
This program results in a PropertyFilterSpec that includes all managed entities below and including
the starting managed object. After creating one or more PropertySpec objects, you can use the
property collector to collect properties from all the collected managed entities.
213
VMware Infrastructure SDK Programming Guide
www.vmware.com
214
C H A P T E R 1 1 Java Code Examples for Basic Operations
215
VMware Infrastructure SDK Programming Guide
Testing
To test your client applications:
1. If the VMware Infrastructure client is not running, start this application.
2. Start the Web service.
3. Run your test programs.
a. Make changes in the VMware Infrastructure client application to determine whether
your client application responds appropriately.
b. Make changes using your client application to determine whether VMware
Infrastructure client reflects your changes.
Note: You can also test the sample code that is provided with this distribution in a similar manner.
www.vmware.com
216
Java Code Examples for Advanced
CHAPTER 12
Operations
The sample code snippets in this chapter represent a small portion of code and are designed only
to show the basic logic and programming constructs needed to use the VMware Infrastructure
SDK effectively. A complete listing of compilable samples is contained in the in
SDK\samples_2_0\Axis\java\com\vmware\vimsample.
• Creating and Configuring a Virtual Machine on page 219
• Creating a Template on page 224
• Performing Power Operations on a Virtual Machine on page 226
• Monitoring Tasks on page 227
• Formatting Event Messages on page 229
• Resetting a Virtual Machine on page 234
• Moving Virtual Machines Across Hosts on page 236
• Responding to Virtual Machine Questions on page 241
• Taking a Snapshot of a Virtual Machine on page 242
• Creating and Deleting Inventory Objects on page 243
217
VMware Infrastructure SDK Programming Guide
www.vmware.com
218
C H A P T E R 1 2 Java Code Examples for Advanced Operations
import com.vmware.vimsample.clientutils.*;
import com.vmware.vimsample.vmutils.VmUtils;
import com.vmware.vim.*;
/**
* Create Virtual Machine implementation.
*/
public class VmCreate extends ClientBase implements ClientBase.Delegate {
VmUtils _vmUtils;
219
VMware Infrastructure SDK Programming Guide
return cpus;
}
return sizeMB;
}
www.vmware.com
220
C H A P T E R 1 2 Java Code Examples for Advanced Operations
ManagedObjectReference hostfoldermor =
_vmUtils.getHostFolder(dcmor);
ManagedObjectReference compresmor =
_vmUtils.getComputeResource(hostfoldermor);
ManagedObjectReference hostmor = _vmUtils.getHost(hostfoldermor,
getCreateOnHost());
ManagedObjectReference resourcePool =
_vmUtils.getResourcePool(compresmor);
221
VMware Infrastructure SDK Programming Guide
ManagedObjectReference taskmor =
clientInfo.getConnection().getService().createVM_Task(
vmFolderMor, vmConfigSpec, resourcePool, hostmor
);
Object[] result =
clientInfo.getServiceUtil().waitForValues(
taskmor, new String[] { "info.state", "info.error" },
new String[] { "state" }, // info has a property - state for
// state of the task
new Object[][] { new Object[] { TaskInfoState.success,
TaskInfoState.error } }
);
www.vmware.com
222
C H A P T E R 1 2 Java Code Examples for Advanced Operations
if (!app.clientInfo.isHasMinimumArgs()) {
return;
}
app.run(app);
}
}
223
VMware Infrastructure SDK Programming Guide
Creating a Template
As described in Creating Templates on page 71, there are two ways to create templates. You can
clone an existing virtual machine as a template or you can take an existing virtual machine and
mark it as a template.
/**
* The next line creates a VirtualMachineRelocateSpec. This
* will be needed to set the location property of the
* VirtualMachineCloneSpec, whose properties
* provide information about where the datastore
* information is located, the target host, the resource pool, and
* the kind of transformation (flat or sparse) to perform on the disks.
* If datastore information is not provided, defaults are provided.
* See the VirtualMachineRelocateSpec in the
* VMware Infrastructure SDK Reference Guide for more information.
*
* In this case, except for setting the transform property, we will
* create an empty spec.
*/
VirtualMachineRelocateSpec vmRelocSpec =
new VirtualMachineRelocateSpec();
vmRelocSpec.setTransform(VirtualMachineRelocateTransformation.sparse);
www.vmware.com
224
C H A P T E R 1 2 Java Code Examples for Advanced Operations
_service.MarkAsTemplate(vmMoRef);
...
}
}
225
VMware Infrastructure SDK Programming Guide
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
if(powerOp.equals("on"))
ManagedObjectReference taskMoRef =
_service.powerOnVm(vmMoRef, hostMoRef);
else if(powerOp.equals("off"))
ManagedObjectReference taskMoRef = _service.powerOffVm(vmMoRef);
else if(powerOp.equals("suspend")
ManagedObjectReference taskMoRef = _service.suspendVm(vmMoRef);
else
System.out.println("Operation must be either \"on\", \"off\", or
\"suspend\".");
System.exit(0);
...
}
}
www.vmware.com
226
C H A P T E R 1 2 Java Code Examples for Advanced Operations
Monitoring Tasks
This code sample snippet uses the power operations code from the last section and adds a code
block that monitors the task that was returned.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
if(powerOp.equals("on"))
ManagedObjectReference taskMoRef =
_service.powerOnVm(vmMoRef, hostMoRef);
else if(powerOp.equals("off"))
ManagedObjectReference taskMoRef = _service.powerOffVm(vmMoRef);
else if(powerOp.equals("suspend")
ManagedObjectReference taskMoRef = _service.suspendVm(vmMoRef);
else
System.out.println("Operation must be either \"on\", \"off\", or
\"suspend\".");
System.exit(0);
227
VMware Infrastructure SDK Programming Guide
do {
ObjectContent[] objs = __service.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });
if(objs == null)
return null;
if((TaskInfoState)dProps[0].val == TaskInfoState.error)
System.out.println("Task completed with an error.");
else
System.out.println("Task completed successfully.");
...
}
}
www.vmware.com
228
C H A P T E R 1 2 Java Code Examples for Advanced Operations
{
...
final int Vm= 0;
final int Host = 1;
final int ComputeResource = 2;
final int Datacenter = 3;
final int Full = 4;
/*
* Retrieve inventory from the given root
*/
private void formatLatestEvent() throws Exception {
try {
// Get the static EventDescriptionEventDetail[]
// (format strings etc.) using a PropertyCollector
ObjectContent[] oc = getObjectProperties(_propCollector,
_eventManager, "description.eventInfo");
EventDescriptionEventDetail[] eventDetails =
(EventDescriptionEventDetail[])oc[0].getPropSet(0).getVal();
229
VMware Infrastructure SDK Programming Guide
eventDetail,
anEvent));
System.out.println(formatEvent(Datacenter, eventDetail, anEvent));
System.out.println(formatEvent(Full, eventDetail, anEvent));
} catch (Exception e) {
clientInfo.getUtil().logException(e);
log.logLine(clientInfo.getAppName() + " : Failed Formating
the event");
throw e;
}
log.logLine(clientInfo.getAppName() +
" : Successful Formating the event");
}
// <summary>
// This function formats the event message using the format strings
// in the EventDescriptionEventDetail for the event passed in
// using the passed in format requested
// </summary>
// <param name="fType">The format type you wish to display</param>
// <param name="eventDetail">Map of Event typename to
// EventDescriptionEventDetail objects</param>
// <param name="theEvent">The Event to format the message for</param>
// <returns></returns>
// The place holder used for string replacement has the following
// format:
//
// {<property-path>}
//
// Where <property-path> is the path to the data that should be used to
// replace the place holder. These are relative to the event in question
// For example, the messages for the Event type 'VmPoweredOnEvent' are:
www.vmware.com
230
C H A P T E R 1 2 Java Code Examples for Advanced Operations
if("VmPoweredOnEvent".equals(typeName)) {
231
VMware Infrastructure SDK Programming Guide
www.vmware.com
232
C H A P T E R 1 2 Java Code Examples for Advanced Operations
format = format.replace("{datacenter.name}",
theEvent.getDatacenter().getName());
if(theEvent.getHost() != null)
format = format.replace("{host.name}",
theEvent.getHost().getName());
if(theEvent.getVm() != null)
format = format.replace("{vm.name}", theEvent.getVm().getName());
return format;
}
...
233
VMware Infrastructure SDK Programming Guide
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
do {
ObjectContent[] objs = _service.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });
if(objs == null)
return null;
www.vmware.com
234
C H A P T E R 1 2 Java Code Examples for Advanced Operations
if((TaskInfoState)dProps[0].val == TaskInfoState.success |
(TaskInfoState)dProps[0].val == TaskInfoState.error)
break;
Thread.Sleep(1000);
} while(true);
if((TaskInfoState)dProps[0].val == TaskInfoState.error)
System.out.println("Task completed with an error.");
else
System.out.println("Virtual machine has been reset.");
...
}
}
235
VMware Infrastructure SDK Programming Guide
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
ManagedObjectReference poolMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToRPool);
if(pState.equals("on"))
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.poweredOn);
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.poweredOn);
}
else
www.vmware.com
236
C H A P T E R 1 2 Java Code Examples for Advanced Operations
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.poweredOn);
}
elseif(pState.equals("off"))
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.poweredOff);
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.poweredOff);
}
else
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.poweredOff);
}
elseif(pState.equals("suspended")
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.suspended);
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.suspended);
237
VMware Infrastructure SDK Programming Guide
else
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.suspended);
}
else
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority);,
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.highPriority);
}
else
{
ManagedObjectReference taskRef = _service.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.lowPriority);
}
}
...
}
}
www.vmware.com
238
C H A P T E R 1 2 Java Code Examples for Advanced Operations
{
// Log on code. See Logging On to the Web Service on page 198.
...
/**
* There are many ways you can specify the target location for the
* disks. See the VirtualMachineRelocateSpec in the
* VMware Infrastructure SDK Reference Guide for more information.
* This code sample needs a Datastore managed object reference
* as well as a ResourcePool managed object reference. Using the
* Datacenter and ComputeResource managed object references, you create
* a PropertyCollector to find the datastore and resource pool. See
* Getting Property Information on page 124 for more information about using
* using a PropertyCollector.
*/
239
VMware Infrastructure SDK Programming Guide
...
}
}
www.vmware.com
240
C H A P T E R 1 2 Java Code Examples for Advanced Operations
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
241
VMware Infrastructure SDK Programming Guide
{
// Log on code. See Logging On to the Web Service on page 198.
...
...
}
}
www.vmware.com
242
C H A P T E R 1 2 Java Code Examples for Advanced Operations
Creating a Datacenter
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
...
}
}
...
}
}
243
VMware Infrastructure SDK Programming Guide
...
}
}
www.vmware.com
244
C H A P T E R 1 2 Java Code Examples for Advanced Operations
Renaming an Object
The following sample illustrates renaming an object.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedObjectReference meRef = _service.findByInventoryPath(
_sic.getSearchIndex(), PathToEntity);
245
VMware Infrastructure SDK Programming Guide
{
// Log on code. See Logging On to the Web Service on page 198.
...
// Find the managed entity.
ManagedObjectReference meRef = _service.findByInventoryPath(
_sic.getSearchIndex(), PathToEntity);
/*
* These lines define the level from which events are to be collected.
* “all” (collect events pertaining to both the managed entity and
* its children), “children” (collect events pertaining to the
* children of the managed entity), and “self” (collect events
* pertaining only to the managed entity).
*/
entitySpec.setRecursion(EventFilterSpecRecursionOption.all);
www.vmware.com
246
C H A P T E R 1 2 Java Code Examples for Advanced Operations
...
}
}
247
VMware Infrastructure SDK Programming Guide
Red
90 x x x
Yellow
75 x x x
Green
CPU Usage
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
/*
* The counterId and instance are returned by the
* QueryAvailablePerfMetric. For more information,
* see Retrieving MetricIds on page 148.
*/
PerfMetricId cpuMetric = new PerfMetricId();
cpuMetric.setCounterId(cpuCounter);
cpuMetric.setInstance(cpuInstance);
/*
* Now create an alarm expression that defines the type of entity
* being tested, sets the red-yellow thresholds (Red = CPU > 90,
* Yellow = CPU > 75), and defines whether
* the alarm triggers above or below the thresholds.
*/
www.vmware.com
248
C H A P T E R 1 2 Java Code Examples for Advanced Operations
/*
* Set a reporting frequency and tolderance range.
* For an explanation of these settings, see
* Setting the Range and Frequency of a Metric Expression on page 168.
*/
AlarmSetting aSetting = new AlarmSetting();
aSetting.setReportingFrequency(20);
aSetting.setToleranceRange(5);
/*
* Now create an action which occurs when the alarm is triggered.
* Power off all virtual machines in a certain folder that
* meet the triggering conditions.
*/
MethodAction meAction = new MethodAction();
meAction.setName("PowerOffVM_Task");
/*
* Get the managed object reference for the managed entity
* for which the alarm is being created. Begin by getting a
* SearchIndex managed object reference.
*/
249
VMware Infrastructure SDK Programming Guide
...
}
}
www.vmware.com
250
C H A P T E R 1 2 Java Code Examples for Advanced Operations
251
VMware Infrastructure SDK Programming Guide
www.vmware.com
252
C H A P T E R 1 2 Java Code Examples for Advanced Operations
Ending a Task
You can use CancelTask to cancel either a scheduled task or a task resulting from an invoked
operation.
253
VMware Infrastructure SDK Programming Guide
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
_service.cancelTask(taskMoRef);
}
...
}
www.vmware.com
254
C H A P T E R 1 2 Java Code Examples for Advanced Operations
if(objs == null)
return null;
255
VMware Infrastructure SDK Programming Guide
www.vmware.com
256
C# Code Examples for Basic Operations
CHAPTER 13
The sample code snippets in this chapter represent a small portion of code and are designed only
to show the basic logic and programming constructs needed to use the VMware Infrastructure
SDK effectively. A complete listing of compilable samples is contained in the in the
SDK\samples_2_0\DotNet\cs directory.
This chapter covers the following topics:
• Logging On to the Web Service on page 258
257
VMware Infrastructure SDK Programming Guide
www.vmware.com
258
Troubleshooting with the Managed
CHAPTER 14
Object Browser
The Managed Object Browser is a Web site, available on both individual ESX hosts and
VirtualCenter, that lets you examine server objects, properties, and values. As described in Getting
Property Information on page 124, when you are writing an application, you use a
PropertyCollector to retrieve property information. However, if you want to view property
information, then you can use the Managed Object Browser. This can be very helpful as a
diagnostic tool.
For example, several operations return a reference to a Task managed object. The recentTask
property of the TaskManager provides information about tasks, including their current state. You
can use the Managed Object Browser to determine the current state of these tasks.
This chapter includes the following:
• Accessing the Managed Object Browser on page 260
• Viewing Task Information with the Managed Object Browser on page 262
259
VMware Infrastructure SDK Programming Guide
The home page displays the ServiceInstance managed object type, its properties, values, and
methods. In this case, the property values point to other data objects, represented by links. For
example, if you click the content link, you display the ServiceContent data object and its properties.
www.vmware.com
260
C H A P T E R 1 4 Troubleshooting with the Managed Object Browser
By comparing this with the ServiceContent as described in the VMware Infrastructure SDK Reference
Guide, you can see that this screen contains all the ServiceContent properties with their current
values. If the property value consists of a data object or a managed object, a link is displayed. You
can click this link to see the data object and its properties.
261
VMware Infrastructure SDK Programming Guide
In this case, the recentTask property shows an array consisting of all the recent tasks. If you click on
one of these links, the screen displays the Task managed object with its info property. This property
is the TaskInfo data object. If you click this link, you can view the information about this task.
www.vmware.com
262
C H A P T E R 1 4 Troubleshooting with the Managed Object Browser
Among the properties is the state property, represented by the TaskInfoState enumerated type,
whose value is success.
263
VMware Infrastructure SDK Programming Guide
www.vmware.com
264
Glossary
CHAPTER 15
Access Control List
An access control list is a set of <group, rights> pairs that defines the access rights for an object.
Alarm
An entity that monitors one or more properties of a virtual machine, such as CPU load. Alarms use
green, red, and yellow color coding to issue notifications as directed by the configurable alarm
definition.
Allocated disk
A type of virtual disk in which all disk space for the virtual machine is allocated at the time the disk
is created. This is the default type of virtual disk created by VirtualCenter.
Apache Axis
Apache Axis is a more modular, more flexible, and higher-performing SOAP implementation
designed around a streaming model and is a successor to Apache SOAP 2.0.
API
Application programming interface. A specified set of functions that allows one to access a
module or service programmatically.
265
VMware Infrastructure SDK Programming Guide
Authorization Role
A set of privileges grouped for convenient identification under names such as “Administrator”.
Child
A managed entity grouped by a Folder object or other managed entity.
Clone
The process of making a copy of a virtual machine. This process includes the option to customize
the guest operating system of the new virtual machine. When a clone is created, VirtualCenter
provides an option to customize the guest operating system of that virtual machine. Clones can be
stored on any host within the same farm as the original virtual machine.
ComputeResource
A managed object that represents either a standalone host or a cluster of hosts available for
backing virtual machines.
Configuration
See Virtual machine configuration file.
Customization
The process of customizing a guest operating system in a virtual machine as it is being deployed
from a template or cloned from another existing virtual machine. Customization options include
changing the new virtual machine identification and network information.
Datacenter
An entity used to group virtualmachine and host entities.
Data object
A composite object that is passed by value between the client and the Web service. A data object
has properties associated with it but does not have any operations of its own. See also
ManagedObject on page 268.
Datastore
The storage location for the virtual machine files. This may be a physical disk, a RAID, a SAN, or a
partition on any of these.
Event
An action that is of interest to VirtualCenter. Each event triggers an event message. Event
messages are archived in the VirtualCenter database.
www.vmware.com
266
C H A P T E R 1 5 Glossary
Farm
A structure (in VirtualCenter 1) under which hosts and their associated virtual machines are added
to the VirtualCenter server.
Fault
A data object containing information about an exceptional condition encountered by an
operation.
Folder
A managed entity used to group other managed entities. The contents of a group are child entities
with respect to the Folder object. See Child on page 266.
A Folder can contain different child entities depending on its location in the ManagedEntity
inventory. The childType property of the Folder determines the managed entities that can be
grouped within the Folder object at any particular level. See the Folder managed object in the
VMware Infrastructure SDK Reference Guide for more information.
Group
A group is a set of users and groups.
Host
The physical computer on which the virtual machines managed by VirtualCenter are installed.
Host agent
Installed on a virtual machine host, it performs actions on behalf of a remote client.
IDL
Interface definition language. A human-readable syntax used to specify an API. The IDL may be
compiled into stubs on a client machine. See Stub on page 270.
Inventory
A hierarchical structure used by the VirtualCenter server or the host agent to organize managed
entities.
JAX-RPC
JAX-RPC (or Java API for XML-based RPC) is an API that builds Web services and clients that use
remote procedure calls (RPC) and XML. Remote procedure calls and responses are transmitted as
SOAP messages (XML files) over HTTP (the Web).
267
VMware Infrastructure SDK Programming Guide
ManagedEntity
A managed object that is present in the inventory. See Inventory on page 267.
ManagedObject
A composite object that resides on a server and is passed between the client and the Web service
only by reference. A managed object has operations associated with it, but might or might not
have properties. See also Data object on page 266.
Message
A message is a data element that is used by an operation to carry data. It lists the data types
exchanged between the Web service and the client.
Migration
Moving a virtual machine between hosts. Unless VMotion is used, the virtual machine must be
powered off when you migrate it. See VMotion on page 272.
Nonpersistent mode
If you configure a virtual disk as an independent disk in nonpersistent mode, all disk writes issued
by software running inside a virtual machine with a disk in nonpersistent mode appear to be
written to disk but are in fact discarded after the virtual machine is powered off. As a result, a virtual
disk or physical disk in independent-nonpersistent mode is not modified by activity in the virtual
machine.
See also Persistent mode on page 268.
Operation
A function performed for a client by the Web service.
Permission
A data object comprising an authorization role, a user or group name, and a managed entity
reference. Allows a specified user to access the entity with any of the privileges pertaining to the
role. See also Authorization Role on page 266.
Persistent mode
If you configure a virtual disk as an independent disk in persistent mode, all disk writes issued by
software running inside a virtual machine are immediately and permanently written to the virtual
www.vmware.com
268
C H A P T E R 1 5 Glossary
disk in persistent mode. As a result, a virtual disk or physical disk in independent-persistent mode
behaves like a conventional disk drive on a physical computer.
See also Nonpersistent mode on page 268.
Privilege
Authorization to perform a specific action or set of actions on a managed entity or group of
managed entities. Privileges are grouped together under an authorization role. See also
Authorization Role on page 266.
Property
An attribute of a managed object or data object. A property may be a nested data object or a
managed object reference.
PropertyCollector
A managed object used to control the reporting of managed object properties. The primary
means of monitoring status on host machines.
Resource pool
A division of computing resources used to manage allocations between virtual machines.
Represented by the ResourcePool managed object.
Resume
Return a virtual machine to operation from its suspended state. When you resume a suspended
virtual machine, all applications are in the same state they were when the virtual machine was
suspended.
See also Suspend on page 270.
Role
See Authorization Role on page 266.
Rollup Type:
A category of information in performance measurement. Identifies the type of statistic rolled up
during the performance interval. The value may be no value, an average, a minimum, a maximum,
a summation of all of the statistics, or the latest statistic.
Scheduled task
A VirtualCenter activity that is configured to occur at designated times. Represented by the
ScheduledTask managed object.
SDK
Software developer kit. It comprises some or all of: an API, an IDL, client stubs, sample code, and
manuals.
269
VMware Infrastructure SDK Programming Guide
Service console
The command line interface for an ESX Server system. The service console lets administrators
configure the ESX Server system. You can open the service console directly on an ESX Server
system. If the ESX Server system’s configuration allows Telnet or SSH connections, you can also
connect remotely to the service console.
Service instance
The managed entity at the root of the inventory. Clients must access the service instance to begin
a session.
Snapshot
A snapshot preserves the virtual machine just as it was when you took the snapshot — the state of
the data on all the virtual machine's disks and whether the virtual machine was powered on,
powered off, or suspended. SDK lets you take a snapshot of a virtual machine at any time and
revert to that snapshot at any time. You can take a snapshot when a virtual machine is powered on,
powered off, or suspended.
SOAP
Simple Object Access Protocol (SOAP) is an XML-based communication protocol and encoding
format for inter-application communication in a decentralized, distributed environment. It
specifies a standard way to encode parameters and return values in XML, and standard ways to
pass them over common network protocols like HTTP (Web) and SMTP (email). SOAP provides an
open methodology for application-to-application communication (Web services).
SOAP::LITE
SOAP::Lite is an open source collection of Perl modules that provides a simple and lightweight
interface to SOAP.
Statistic Type
A category of information in performance measurement. Describes the nature of the statistical
value that is collected or calculated for this counter. Statistics may indicate an amount of change,
an absolute value, or a rate value.
Stub
A procedure that implements the client side of a remote procedure call. The client calls the stub to
perform a task, and the stub then transmits parameters over the network to the server and returns
the results to the client.
Suspend
Save the current state of a running virtual machine. To return a suspended virtual machine to
operation, use the resume feature.
www.vmware.com
270
C H A P T E R 1 5 Glossary
Task
A managed object representing the state of a long-running operation.
TCP
Transmission Control Protocol. A reliable transfer protocol between two endpoints on a network.
TCP is built on top of IP.
Template
A master image of a virtual machine. This typically includes a specified operating system and a
configuration that provides virtual counterparts to hardware components. Optionally, a template
can include an installed guest operating system and a set of applications. Templates are used by
VirtualCenter to create new virtual machines.
UUID
Universally Unique Identifier (ID). A number used to uniquely identify some object or entity in the
VMware object model. The UUID is either assigned by VMware Infrastructure (in the case of virtual
machines) or is hardware-assigned (in the case of SCSI LUNs). VirtualCenter tries to ensure that the
UUIDs of all virtual machines being managed are unique, changing the UUIDs of conflicting virtual
machines if necessary. In rare cases (for instance, if you have made a manual copy of a virtual
machine), you might have two virtual machines with the same UUID.
User
A user is a principal known to the system.
VirtualCenter
VMware VirtualCenter is a software solution for deploying and managing virtual machines across
the data center.
VirtualCenter agent
Installed on each virtual machine host, it coordinates the actions received from the VirtualCenter
server.
VirtualCenter database
A persistent storage area for maintaining status of each virtual machine and user managed in the
VirtualCenter environment. This is located on the same machine as the VirtualCenter server.
271
VMware Infrastructure SDK Programming Guide
VirtualCenter server
A service that acts as a central administrator for VMware servers connected on a network. This
service directs actions upon the virtual machines and the virtual machine hosts. VirtualCenter
server is the central working core of VirtualCenter.
Virtual disk
A virtual disk is a file or set of files that appear as a physical disk drive to a guest operating system.
These files can be on the host machine or on a remote file system.
Virtual machine
A virtualized x86 PC environment in which a guest operating system and associated application
software can run. Multiple virtual machines can operate on the same host system concurrently.
VMFS
See VMware ESX Server file system on page 272.
VMODL
The interface definition language used in the VMware Infrastructure SDK.
VMotion
The feature that lets you move a virtual machine from one ESX Server system to another without
interrupting service. VMotion requires licensing on both the source and target hosts. VMotion is
activated by the VirtualCenter agent. The VirtualCenter server centrally coordinates all VMotion
activities.
VMware DRS
VMware DRS is a feature that intelligently and continuously balances virtual machine workloads
across your ESX Server hosts. VMware DRS detects when virtual machine activity saturates an ESX
Server host and triggers automated VMotion live migrations, moving running virtual machines to
other ESX Server nodes so that all resource commitments are met.
www.vmware.com
272
C H A P T E R 1 5 Glossary
One VMFS partition is supported per SCSI storage device or SAN. Each version of ESX Server uses a
corresponding version of VMFS. For example, VMFS3 was introduced with ESX Server 3.
VMware HA
VMware HA is a feature that detects failed virtual machines and automatically restarts them on
alternate ESX Server hosts. VMware HA selects a failover host that can honor the virtual machine’s
resource allocations so that service level guarantees remain intact.
VMware Infrastructure
A system of hosts, agents, and clients that communicate to deploy and operate virtual machines.
The total VMware solution to managing a data center. See Host on page 267, Host agent on
page 267, VirtualCenter on page 271.
VMware Tools
A suite of utilities and drivers that enhances the performance and functionality of your guest
operating system. Key features of VMware Tools include some or all of the following, depending on
your guest operating system: an SVGA driver, a mouse driver, the VMware guest operating system
service, the VMware Tools control panel, time synchronization with the host, VMware Tools scripts,
and connecting and disconnecting devices while the virtual machine is running.
Web service
A programming interface based on SOAP and WSDL.
WSDL
Web Services Description Language, an XML-based language used to describe a Web service’s
capabilities and to provide a way for individuals and businesses to access those services
electronically.
XML
Extensible Markup Language, a text-based markup language that is especially designed for Web
documents.
273
VMware Infrastructure SDK Programming Guide
www.vmware.com
274
Upgrading VMware Tools
APPENDIX A
After upgrading the ESX Server from 3.0 to 3.0.1, you should upgrade VMware Tools on all virtual
machines. For virtual machines with ESX Server 3.0 and later Tools installed in them, you can use
the UpgradeTools_Task operation to upgrade Tools simultaneously without user interaction.
Prerequisites
Upgrading VMware Tools with the UpgradeTools_Task operation requires the following:
• ESX Server must be version 3.0.1 or later.
• The virtual machine must be powered on.
• VMware Tools must be installed and running.
The VirtualMachine’s guest.toolsStatus property must be either "toolsOK" or "toolsOld".
• VMware Tools must be the version that ships with ESX 3.0.
The easiest way to check of a VMware Tools is upgrade-capable is to check the
disabledMethod property of the virtual machine. The disabledMethod property takes into
account both the toolsAutoUpdateSupported property as well as whether the virtual
machine is powered on and whetehr the VMware Tools are running.
275
VMware Infrastructure SDK Programming Guide
Invoking UpgradeTools_Task
The operation takes the following parameters:
• Virtual Machine managed object reference – The virtual machine whose VMware Tools is
being upgraded.
• installerOptions – Command line options passed to the installer. This parameter is not used in
the current release.
Failure Mode
For a complete list of faults, see the method description in the VMware Infrastructure SDK Reference
Guide. The major faults are:
• NotSupported – Upgrading tools is not supported. See Prerequisites on page 275.
• ToolsUnavailable – VMware Tools is not running.
• VmToolsUpgradeFault – A fault indicating that something went wrong when upgrading
tools. When a user receives this fault, it implies that the virtual machine did have tools
running inside it, but something went wrong with the upgrade - maybe the particular version
of tools did not support upgrade or something went wrong inside the guestOS that
prevented a successful upgrade.
• TaskInProgress –The operation tried to access an entity that already has another (long)
operation in progress.
www.vmware.com
276
A P P E N D I X A Upgrading VMware Tools
/**
* This is a simple standalone client whose purpose is to demonstrate the
* process for Logging into the Webservice, and upgrading the VMware Tools
* for one virtual machine.
*/
public class toolsUpgrade1 {
/**
* Create the Managed Object Reference for the service
*
* @param svcRefVal to define service reference for HostAgent or VPX
*/
public void createServiceRef() throws Exception {
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
/**
277
VMware Infrastructure SDK Programming Guide
_sic = _service.retrieveServiceContent(_svcRef);
_sindex = _sic.getSearchIndex();
_propCol = _sic.getPropertyCollector();
if (_sic.getSessionManager() != null) {
_service.login(_sic.getSessionManager(), username, password, null);
}
}
/**
* Log's out and Disconnects from the WebService
*/
public void disconnect()throws Exception {
if (_service != null) {
// does not work at this time
//_service.logout(_svcRef);
_service = null;
_sic = null;
}
}
/**
* Get the reference to the virtual machine managed object
* that contains the VMware Tools to be upgraded.
*
* Test the virtual machine to see if its tools can be upgraded
* by checking the contents of the virtual machine's disabledMethod
* property.
*/
public void upgrade(String _invPath)throws Exception {
www.vmware.com
278
A P P E N D I X A Upgrading VMware Tools
279
VMware Infrastructure SDK Programming Guide
System.out.println("UpgradeTools_Task is disabled!");
}
}
}
/**
* The main entry point for the application.
*/
public static void main(String[] args) {
if (args == null || args.length != 4) {
System.out.println(
"Usage : toolsUpgrade1 <webserviceurl> <username> <password>
<inventory path>"
);
}
try {
// Create the Service Managed Object Reference
tu1.createServiceRef();
www.vmware.com
280
A P P E N D I X A Upgrading VMware Tools
/**
* This is a simple standalone client whose purpose is to demonstrate the
* process for Logging into the Webservice, and upgrading VMware tools
* installed in the guest OS of each virtual machine in inventory
*/
public class toolsUpgrade {
/**
* Create the Managed Object Reference for the service
*
* @param svcRefVal to define service reference for HostAgent or VPX
*/
public void createServiceRef() throws Exception {
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
/**
* Creates an instance of the VMA proxy and establishes a connection
*
281
VMware Infrastructure SDK Programming Guide
_sic = _service.retrieveServiceContent(_svcRef);
_propCol = _sic.getPropertyCollector();
_rootFolder = _sic.getRootFolder();
if (_sic.getSessionManager() != null) {
_service.login(_sic.getSessionManager(), username, password, null);
}
}
/**
* Log's out and Disconnects from the WebService
*/
public void disconnect()throws Exception {
if (_service != null) {
// does not work at this time
//_service.logout(_svcRef);
_service = null;
_sic = null;
}
}
/**
* Get all the virtual machines accessable from rootFolder
* and upgrade their tools if able
*/
public void upgradeTools()throws Exception {
www.vmware.com
282
A P P E N D I X A Upgrading VMware Tools
datacenterVmTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });
283
VMware Infrastructure SDK Programming Guide
if (pcary != null) {
for (int pci = 0; pci < pcary.length; pci++) {
pc = pcary[pci];
if(pc.getName().equals("disabledMethod")) {
String[] pci2 = (String[])pc.getVal();
for (int x = 0 ; x < pci2.length; x++){
if (pci2[x].equals("UpgradeTools_Task")) {
UpgradeOk = false;
}
}
}
else
{
vmName = (String)pc.getVal();
}
}
}
if(UpgradeOk) {
_service.upgradeTools_Task(vmRef, "");
System.out.println("The tools for " + vmName +
" have been upgraded.");
}
else
{
System.out.println("UpgradeTools_Task is disabled for " +
vmName + ". The tools cannot be upgraded.");
}
}
}
}
/**
* The main entry point for the application.
*/
public static void main(String[] args) {
if (args == null || args.length != 3) {
System.out.println(
"Usage : toolsUpgrade <webserviceurl> <username> <password>"
);
}
try {
// Create the Service Managed Object Reference
tu.createServiceRef();
www.vmware.com
284
A P P E N D I X A Upgrading VMware Tools
285
VMware Infrastructure SDK Programming Guide
www.vmware.com
286
Performance Counters
APPENDIX B
This appendix contains a data dictionary that lists the performance counters in the VMware
Infrastructure SDK. This includes the following sections:
• Counter Information Categories on page 288
• Most Useful Performance Counters on page 289
• Complete List of Performance Counters on page 292
287
VMware Infrastructure SDK Programming Guide
www.vmware.com
288
A P P E N D I X B Performance Counters
289
VMware Infrastructure SDK Programming Guide
www.vmware.com
290
A P P E N D I X B Performance Counters
291
VMware Infrastructure SDK Programming Guide
www.vmware.com
292
A P P E N D I X B Performance Counters
293
VMware Infrastructure SDK Programming Guide
www.vmware.com
294
A P P E N D I X B Performance Counters
295
VMware Infrastructure SDK Programming Guide
www.vmware.com
296
A P P E N D I X B Performance Counters
297
VMware Infrastructure SDK Programming Guide
www.vmware.com
298
A P P E N D I X B Performance Counters
299
VMware Infrastructure SDK Programming Guide
www.vmware.com
300
Privileges
APPENDIX C
This appendix lists the privileges in the VMware Infrastructure SDK. They are divided into privileges
required to perform operations and privileges required to read properties. See Security
Management on page 176 for more information about privileges, roles, and permissions.
301
VMware Infrastructure SDK Programming Guide
www.vmware.com
302
A P P E N D I X C Privileges
303
VMware Infrastructure SDK Programming Guide
www.vmware.com
304
A P P E N D I X C Privileges
305
VMware Infrastructure SDK Programming Guide
www.vmware.com
306
A P P E N D I X C Privileges
307
VMware Infrastructure SDK Programming Guide
www.vmware.com
308
A P P E N D I X C Privileges
309
VMware Infrastructure SDK Programming Guide
www.vmware.com
310
A P P E N D I X C Privileges
a. In order to invoke this operation on a managed entity, you must also have the
same privilege associated with the parent of the managed entity.
311
VMware Infrastructure SDK Programming Guide
www.vmware.com
312
A P P E N D I X C Privileges
313
VMware Infrastructure SDK Programming Guide
www.vmware.com
314
Revision History
APPENDIX D
The following table lists the revision history for the VMware Infrastructure SDK Programming Guide.
315
VMware Infrastructure SDK Programming Guide
www.vmware.com
316
Index _Task 45
info.result 45
info.state 45
Symbols
authorization role
_Task 45 adding 185
A adding (Java sample) 203
access control list 265 defined 266
removing (Java sample) 204
active tasks, states 50
updating (Java sample) 203
AddAuthorizationRole 185
Axis 23
AddHost_Task 101
B
AddPortGroup 108
backing devices 75
AddServiceConsoleVirtualNic 109
C
AddStandaloneHost_Task 100
cancelable (TaskInfo property) 157
AddVirtualSwitch 107
catagories, events 49
affinity rule 91
certificate store
alarm conditions, multiple 168
creating 28
AlarmAction 171 location 28
AlarmExpression 50 certificate, SSL
alarms configuring for 28
actions, defining 171 location 28
condition statuses 166 CheckForUpdates
conditions, defining 166 described 43, 140
creating 165 Java example 199
defined 50, 265 returned properties 141
deleting 174
child (managed entity) 266
disabling 174
metric alarm expressions 166 childType property 48
state alarm expressions 170 client-Web service interactions 46
AlarmSetting 169 clone 266
AlarmTriggeringAction 172 CloneVM_Task 69
allocated disk 265 cloning virtual machines
annotation (property) 77 as a template (sample code) 224
CloneVM_Task 69
anti-affinity rule 91
ClusterComputeResource
Apache Axis
creating 89
described 23
defined 266
generating stubs 26
explained 37
API 265
clusters
architecture 18 configuring/reconfiguring 89
arrays, indexed and key-based 34 creating 89
AssignUserToGroup 182 DRS, enabling for 89
asynchronous operations DRS-enabled 37
enabled for both DRS and HA 40
317
HA, enabling for 89 explained 47
HA-enabled 37 renaming 112
more efficient resource usage 104 Datastore
moving hosts into 101 defined 266
removing hosts from 103 defining 77
ComputeResource explained 54
defined 266 datastore files
explained 37 deleting virtual machine files 66
renaming 112 unregistering virtual machines 66
standalone host, adding 100
datastore path 54
config.xml 30
datastores
configuration file and ComputeResource 37
ESX Server 30 debug mode, enabling 77
VirtualCenter Server 29
default power operations, defining 77
connecting hosts 103
Destroy_Task
console preferences 73
deleting a datacenter 67
counterId 60 deleting a folder 66
CPU DestroyChildren 95
allocating (resource pools) 92
destroying resource pools 95
allocation 73
Development environment 23
configuring processors 73
feature mask 74 deviceChange 75
overcommitting resources 39 disk usage (metric alarm condition) 166
usage (metric alarm condition) 166 DRS-enabled clusters
usage (resource pools), limiting 95 definition 37
cpuAffinity 73 resource pools 40
CreateAlarm 165 duplicate UUIDs 78
CreateCluster 89 E
CreateCollectorForEvents 49, 159 Email (alarm action) 172
CreateDatacenter 67 ending time 60
CreateFilter entities
described 43 moving into folders 68
Java example 199 entity (property) 95
CreateFolder 66 Environment, development 23
CreateGroup 182 escaped characters, returning 46
CreateResourcePool 91 ESX Server
CreateSnapshot_Task 84 configuration file 30
CreateUser 182 product description 17
CreateVM_Task 69 EventHistoryCollector
D latestPage property 159
retrieving historical information 50
data object 32, 266
retrieving items from 159
Data synchronization loop 199
EventManager 49
Datacenter
events
creating 67
catagories 49
deleting 67
www.vmware.com
318
defined 266 service console VNIC, adding 109
definition 49 service console VNIC, updating 109
formatting messages 160 updating in batch 109
retrieving historical information 50 VNIC, removing 109
Exception 215 host network policy, defining 110
F HostAccountSpec data object 182
farm 267 HostConnectSpec 101
fault 267 hostFolder
feature mask 74 as root of datacenter 67
the childType property 67
flags (property) 77
HostPortGroupSpec data object 108
folders
creating 66 hosts
defined 267 adding connected hosts 103
deleting 66 adding disconnected hosts 103
deleting folder and contents 66 adding to cluster 101
explained 47 and ComputeResource 37
Folder managed object 67 clusters, creating 89
managed object reference 66 conditions for moving 101
moving entities into 68 configuring networks 106
renaming 112 connecting 103
root host folder 67 defined 267
root virtual machine folder. 67 disconnecting 103
host network policy 110
G moving into cluster 102
green (resource pool state) 41 moving into clusters 101
GroupAlarmAction 172 recommending for virtual machines
groups 104
creating 182 reconnecting 103
creating (Java example) 201 removing from cluster 103
permissions 180 renaming 112
querying 184 restarting 105
removing from group 183 shutting down 105
standalone host, adding 100
groups, assigning users to 182
HostSystem
guest operating system
connecting 103
defined 267
defining the ID 78 disconnecting 103
reconnecting 103
guestId (property) 78
HostVirtualSwitchSpec data object 107
H
http protocol, configuring 29
HA-enabled clusters
https protocol, configuring 28
defintion 37
resource pools for 38 I
High Availability 272 IDL 267
History, performance data 59 indexed arrays 34
HistoryCollector 50 info.result 45
host agent 267 info.state 45
host network configuration instantiating an instance 63
319
interactions, client-Web service 46 allocating (resource pools) 92
inventory allocation 73
datacenters, creating 67 overcommitting resources 39
datacenters, deleting 67 usage (metric alarm condition) 166
defined 267 usage (resource pools), limiting 95
folders, creating 66 memory files 58
folders, deleting 66 memoryAffinity 73
J message data element 268
JAX-RPC 267 messages, event
K formatting 160
key-based arrays 34 formatting (sample code) 229
method action (alarm action) 172
L
metric alarm conditions 166
latestPage property 159
metric alarm expressions
limit 74
CPU usage 166
limit (property) 95 defining 166
locale, setting the 64 disk usage 166
localization 64 memory usage 166
log files 77 network usage 166
setting range and frequency 168
Logging into Web service (C#) 258
metricIds 60
Logging into Web service (Java) 198
Microsoft .NET Framework 23
logging on 61
Microsoft Visual Studio .NET
logging, enabling 77
described 23
LogUserEvent 49 generating proxy code 26
Loop, creating 199 migrating virtual machines 82
M migrating virtual machines (cold) 82
Managed Entity 268 migration 268
managed object reference migration, validating 83
defined 32 minimum available resources 73
obtaining 32
minimum resources, expanding 94
managed objects 32
MoveHostInto_Task 101
accessing on the server 32
defined 268 MoveIntoFolder_Task 68
getting property information 124 MoveIntoResourcePool 95
learning about contents 33 N
obtaining 32
NAS volume. See Network Attached
ManagedEntity 32 Storage (NAS) volume
obtaining 33
nested properties 35
ManagedEntity Inventory 35
network adapter, virtual 52
MarkAsTemplate 71
Network Attached Storage (NAS)
MarkAsVirtualMachine 71 volume 54
maximum allowed resource usage 74 Network Interface Card, Physical 52
maximum samples 60 Network Interface Card, Virtual (VNIC)
memory
www.vmware.com
320
see Virtual Network Interface Card merging (Java sample) 206
(VNIC) querying for all (Java sample) 207
network traffic, optimizing 77 querying for entity (Java) 207
network usage (metric alarm condition) querying for role permissions (Java)
208
166
removing 187
networks
removing (Java sample) 208
configuring for a host 106 resetting 186
host’s configuration, determining
setting 186
107
setting (Java sample) 205
port groups, adding 108 updating 186
virtual switch, adding 107
updating (Java sample) 205
networkShaper property 77 users and groups 180
nonpersistent mode 268 persistent mode 268
non-SSL, configuring for 29 physical devices 75
O Physical Network Interface Card (PNIC)
objectSet property 124 52
ObjectSpec data object 125 port 8085 30
operation port groups, adding 108
definition 268 PowerOffVM_Task 79
operations PowerOnVM_Task 79
privileges required for 176 privileges
required privileges for 301 and security management 176
OrAlarmExpression 168 defined 269
overcommitting 39 format 176
overcommitting resources 97 operations, required for 176, 301
properties, required for 177, 312
P
property
parent resource pool
definition 269
adding resource pools to 39 privileges and 177, 269
partialUpdates 142 property filter 141
performance counters 60 property information, getting 124
performance data property paths 35
collecting 59
PropertyCollector
counterIds 60
creating 124
ending time 60
maximum samples 60 defined 269
metricIds 60 PropertyFilterSpec 124
performance intervals 59 PropertySpec 124
starting time 60 propSet property 124
performance intervals 59 Q
performance metrics 60 quiesce 84
Permission data object 268
R
permissions
ReconfigVM_Task 44
and security management 178
reconnecting hosts
and sub-objects 178
and VirtualCenter 103
321
ReconnectHost_Task 103 RetrieveProperties operation 133
red (resource pool state) 42 RetrieveServiceContent
redo files 77 described 43
RelocateVM_Task 83 RetrieveUserGroups 184
RemoveAlarm 174 RevertToCurrentSnapshot_Task 86
RemoveServiceConsoleVirtualNic 110 RevertToSnapshot_Task 85
RemoveSnapshot_Task 87 revision history 315
Rename_Task 112 roles
and security management 177
RenameSnapshot 85
defined 269
reportingFrequency (alarms) 169
roles, authorization
reservation 73 adding 185
ResetVM_Task 79 root Folder 47
resource pools root Folder (host) 67
affinity rule 91
root Folder (virtual machine) 67
allocating CPU 92
allocating memory 92 root host folder 67
and computing power 37 root resource pool 38, 91
anti-affinity rule 91 root virtual machine folder 67
CPU resources, overcommitting 39
rui.crt 28
CPU usage, limiting 95
creating 91 run.bat 28
defined 269 S
deleting 95 scheduled tasks
DRS-enabled clusters 40 and task management 49
HA-enabled clusters 38 cancelling 156
memory resources, overcommitting defined 269
39 script (alarm action) 172
memory usage, limiting 95
SDK 269
minimum resources, expanding 94
moving into resource pools 95 selectSet property
reconfiguring 91 ObjectSpec 125
renaming 112 TraversalSpec 127
resources, overcommitting 97 service console VNIC
root resource pool 38, 91 restarting 110
shares 95 updating 109
standalone hosts 38 service console, configuring TCP/IP 106
states 41 ServiceInstance 63
subdividing 39 accessing 61
ResourceAllocationInfo 95 description 34
ResourceConfigSpec 92, 95 Services Control Panel Applet 30
resources, overcommitting 97 Session token 62
resume 269 shares 74, 95
RetrieceServiceContent skip
Java code example 198 ObjectSpec 125
RetrieveProperties TraversalSpec 126
described 43 snapshots
www.vmware.com
322
and memory files 58 virtual machines, marking as tem-
creating 84 plates 71
definition 56 Token, session 62
overview 56 toleranceRange (alarms) 169
removing 87
tools (property) 77
reverting to 85
snapshot files 77 ToolsConfigInfo 77
SNMP (alarm action) 172 ToolsUnavailable 276
SNMP traps, sending 49 TraversalSpec 126
SSL certificate Troubleshooting 215
configuring for 28 U
location 28 Universally Unique Identifier (UUID) 78,
standalone hosts 271
resource pools for 38 UnregisterAndDestroy 66
starting time 60 UnregisterAndDestroy_Task 66
state alarm expressions, defining 170 UpdateAuthorizationRole 185
state conditions 166 UpdateChildResourceConfiguration 92
states, resource pool 41 UpdateConfig 92
stubs UpdateUser 182
and the WSDL 22
UpgradeTools_Task
defined 270
cancelling 276
suspend files 77 Java (onevirtual machine) 277
SuspendVM_Task 79 Java example (batch) 281
Symmetric Multiprocessors 73 parameters 276
Syntax, datastore path 55 URL (VMware Infrastructure SDK Web
system roles 177 Service) 25
URL, Web service 63, 198
T
user session, opening 63
Task managed object
defined 271 user-defined roles 177
Task managed object reference users
operations that return 45 assigning to groups 182
TaskHistoryCollector creating 182
creating (Java example) 201
retrieving historical information 50
permissions 180
TaskInProgress 276
querying 184
tasks removing from group 183
cancelable 157 updating 182
cancelling 156
UUID
definition 49
see Universally Unique Identifier
retrieving historical information 50
V
TCP/IP Offloading, enabling 77
ValidateMigration 83
templates
cloning a virtual machine as 71 video acceleration, turning off 77
creating 71 VimService 258
marking as virtual machine 71 VimServiceLocator 63, 198
323
virtual devices, defining 75 product description 17
virtual machines VirtualCenter Server
and deleted resource pools 95 configuration file 29
changing from template 71 VirtualDeviceConfigSpec 75
cloning 69 VirtualMachineAffinityInfo 73
cloning as template 71
VirtualMachineCloneSpec 70
cold migration 82
configuration file 55 VirtualMachineConfigSpec 69
console preferences 73 VirtualMachineConsolePreferences 73
CPU allocation 73 VirtualMachineDefaultPowerOpInfo 77
CPU processors 73 VirtualMachineFileInfo 77
creating from scratch 69
VirtualMachineFlagInfo 77
default power operations, defining
77 VirtualMachineRelocationSpec 83
descriptions, providing 77 vlanId 108
disk files, moving 83 vmFolder
duplicate UUIDs 78 as root of datacenter 67
guest operating system ID, defining the childType property 67
78
VMFS volume 54
hot migration 82
VMFS. See VMware File System (VMFS)
log files 77
memory allocation 73 VMkernel
memory nodes 73 updating TCP/IP configuration 110
migration, validating 83 VMkernel, configuring TCP/IP 106
moving into resource pools 95 VMotion 17, 82
powering off 79
VmToolsUpgradeFaul 276
powering on 79
recommending hosts for 104 VMware DRS
defined 272
renaming 112
definition 37
resetting 79
snapshots 56 enabling 89
suspending 79 VMware File System (VMFS) 54
templates, creating 71 VMware HA
unregistering 66 and compute resources 37
virtual defices, defining 75 defined 273
virtual processors, defining 74 VMware Infrastructure SDK architecture
virtual network adapter 52 18
Virtual Network Interface Card (VNIC) VMware Infrastructure SDK client
adding 108 requirements 25
explained 52 setting up 25
service console VNIC, adding 109 setup procedure 25
service console VNIC, removing 109 VMware Infrastructure Web Service URL
virtual processors, defining 74 25
virtual switches VMware Tools 273
adding 107 VMware Tools, upgrading 275
port groups, adding 108 VMware VirtualCenter. See
VirtualCenter 17 VirtualCenter.
and reconnecting hosts 103
VNIC
www.vmware.com
324
adding 108
see Virtual Network Interface Card
(VNIC)
vpxd.cfg 29
W
WaitForUpdates
cancelling 142
described 43, 141
returned properties 141
Web service
definition 273
logging in (C# example) 258
logging in (Java example) 198
Web service development
environment 23
Web service URL 63, 198
Web Services Description Language.
See WSDL.
WSDE
see Web service development envi-
ronment
WSDL 273
Y
yellow (resource pool state) 41
325
www.vmware.com
326