0% found this document useful (0 votes)
66 views326 pages

Programming Guide 201

Uploaded by

mohamed elsawaf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
66 views326 pages

Programming Guide 201

Uploaded by

mohamed elsawaf
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 326

VERSION 2.0.

VMware Infrastructure SDK


Programming Guide
Please note that you will always find the most up-to-date technical documen-
tation on our Web site at http://www.vmware.com/support/.
VMware, Inc. The VMware Web site also provides the latest product updates.
Copyright © 1998-2006 VMware, Inc. All rights reserved. Protected by one or more of U.S. Patent Nos. 6,397,242,
6,496,847, 6,704,925, 6,711,672, 6,725,289, 6,735,601, 6,785,886, 6,789,156, 6,795,966, 6,880,022, 6,961,941,
3145 Porter Drive
6,961,806, and 6,944,699; patents pending. VMware, the VMware “boxes” logo and design, Virtual SMP and
Palo Alto, CA 94304 VMotion are registered trademarks or trademarks of VMware, Inc. in the United States and/or other
www.vmware.com jurisdictions. All other marks and names mentioned herein may be trademarks of their respective companies.
Revision 20060922 Version 2.0.1 Item: SDK-ENG-Q306-282
Table of Contents
Introducing the Programming Guide _____________________________ 13
How the Programming Guide Is Organized ___________________________14
Using This Programming Guide ____________________________________16
Intended Audience ___________________________________________16
Java and the Code Samples in this Guide __________________________16
Supported VMware Products ______________________________________17
VMware VirtualCenter _________________________________________17
VMware ESX Server ___________________________________________17
VMware Infrastructure Architecture _________________________________18
Accessing Hosts Through VirtualCenter ____________________________18
Accessing Hosts Without VirtualCenter ____________________________18
VMware Infrastructure SDK Package ______________________________19
Web Service Standards and the VMware Infrastructure SDK ____________19
Technical Support Resources ______________________________________20

Developing Client Applications _________________________________ 21


Connecting to the VMware Infrastructure Web Service __________________22
Overview ___________________________________________________22
Selecting a Development Environment ______________________________23
Apache Axis _________________________________________________23
Microsoft Visual Studio .NET and .NET Framework ____________________23
Setting up the VMware Infrastructure SDK Client _______________________25
Requirements ________________________________________________25
Setup Procedure _____________________________________________25
Generating Stubs with Microsoft Visual Studio .NET and .NET Framework _26
Generating Stubs with Apache Axis _______________________________26
Configuring for the https (SSL) Protocol ___________________________28
Configuring for the http (non-SSL) Protocol ________________________29

VMware Infrastructure SDK Key Concepts _________________________ 31


VMware Infrastructure SDK Terminology _____________________________32
Managed Objects and Data Objects ______________________________32
Managed Object References ____________________________________32
ServiceInstance ______________________________________________34
Indexed and Key-Based Arrays ___________________________________34
Nested Properties and Property Paths _____________________________35

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

Managing Inventory __________________________________________ 65


Managing Folders and Datacenters _________________________________66
Creating a Folder _____________________________________________66
Deleting a Folder _____________________________________________66
Creating a Datacenter _________________________________________67
Deleting a Datacenter _________________________________________67
Moving Entities into a Folder ____________________________________68
Creating a Virtual Machine ________________________________________69
Creating a Virtual Machine from Scratch ___________________________69
Cloning Virtual Machines _______________________________________69
Managing Virtual Machine Templates _______________________________71
Creating Templates ___________________________________________71
Changing a Template to an Active Virtual Machine ___________________71
Configuring a Virtual Machine _____________________________________73
Defining Console Preferences ___________________________________73
Configuring CPU and Memory Information _________________________73
Defining the Number of Virtual Processors _________________________74
Defining the Virtual Devices _____________________________________75
Defining File Information _______________________________________77
Naming the Virtual Machine ____________________________________77
Defining Network Shaping _____________________________________77
Defining Default Power Operations _______________________________77
Setting Flags on the Virtual Machine ______________________________77
Defining Tools Information _____________________________________77
Defining or Removing a Description ______________________________77
Defining IDs for Guest Operating System and Configuration File Location _78
Defining the Universally Unique Identifier (UUID) ____________________78
Performing Power Operations on a Virtual Machine _____________________79
Powering On a Virtual Machine __________________________________79
Powering Off a Virtual Machine __________________________________79
Suspending a Virtual Machine ___________________________________79
Resetting a Virtual Machine _____________________________________79
Migrating Virtual Machines ________________________________________81
Enabling Migration ___________________________________________81

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

Getting Information and Updates ______________________________ 123


Getting Property Information _____________________________________124
Defining the Information Retrieval Process ________________________124
Defining a Simple PropertyFilterSpec (No Traversal) _________________127
Defining a PropertyFilterSpec with TraversalSpec Objects _____________128
Retrieving Property Information ________________________________133
Finding Entities Using a Property Value _____________________________135
Differences Between the SearchIndex API and the PropertyCollector ____135
Finding a ManagedEntity by InventoryPath ________________________135
Finding a Virtual Machine by Datastore Path _______________________136
Finding a Virtual Machine or Host by DNS Name ____________________136
Finding a Virtual Machine or Host by UUID ________________________137
Finding a Virtual Machine or Host by Its IP Address __________________137
Searching the Immediate Children of a ManagedEntity ______________138
Getting Updates on Properties ____________________________________140
Getting Updates with RetrieveProperties __________________________140
Checking or Waiting for Updates ________________________________140
Creating a Property Filter ______________________________________141
Cancelling a Wait for Updates __________________________________142
Setting the partialUpdates Flag _________________________________142

Monitoring Performance Data _________________________________ 145


Configuring Intervals for Statistics _________________________________146
Creating Performance Intervals _________________________________146
Updating Performance Intervals ________________________________146
Removing Performance Intervals ________________________________147

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

Managing Events, Tasks, and Alarms ____________________________ 151


Logging a User-Defined Event ____________________________________ 152
Managing Tasks _______________________________________________ 153
Creating a Scheduled Task _____________________________________ 153
Configuring and Reconfiguring a Scheduled Task ___________________ 153
Cancelling a Task ____________________________________________ 156
Deleting a Scheduled Task _____________________________________ 157
Retrieving the Scheduled Tasks on an Entity _______________________ 157
Monitoring Operations with Managed Object Properties _____________ 157
Retrieving Historical Information __________________________________ 159
Retrieving Historical Event Information ___________________________ 159
Retrieving Historical Task Information ____________________________ 161
Using a History Collector ______________________________________ 162
Deleting a Collector __________________________________________ 164
Managing Alarms ______________________________________________ 165
Creating Alarms _____________________________________________ 165
Configuring or Reconfiguring an Alarm ___________________________ 165
Getting a List of Alarms _______________________________________ 173
Getting the Overall Status of Alarm ______________________________ 173
Deleting an Alarm ___________________________________________ 174
Disabling an Alarm ___________________________________________ 174

Managing Users _____________________________________________ 175


Security Management __________________________________________ 176
Privileges, Roles, and Permissions _______________________________176
Permissions and Sub-Objects __________________________________ 178
Permissions and Complex Entities _______________________________180
Users, Groups, and Permissions _________________________________ 180
Adding and Maintaining Users and Groups (ESX only) __________________ 182
Querying for Users and Groups ___________________________________ 184
Adding and Maintaining Authorization Roles _________________________ 185
Setting and Maintaining Permissions on an Entity _____________________186

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

Creating a Simple Java Client Application ________________________ 191

Java Code Examples for Basic Operations ________________________ 197


Logging On to the Web Service ___________________________________198
Basic Data Synchronization Loop __________________________________199
Handling Permissions and Roles ___________________________________201
Creating Users and Groups ____________________________________201
Adding, Updating, and Removing Authorization Roles _______________203
Adding or Updating Permissions ________________________________205
Merging Permissions _________________________________________206
Querying for Permissions ______________________________________207
Removing a Permission _______________________________________208
Getting Information About Properties ______________________________210
Defining a PropertyFilterSpec with Recursion ______________________210
Getting Updates on an Inventory Object ____________________________214
Handling Exceptions in the Data Synchronization Loop _________________215
Testing ______________________________________________________216

Java Code Examples for Advanced Operations ____________________ 217


Creating and Configuring a Virtual Machine __________________________219
Creating a Template ____________________________________________224
Cloning a Virtual Machine as a Template __________________________224
Marking an Existing Virtual Machine as a Template __________________225
Performing Power Operations on a Virtual Machine ____________________226
Monitoring Tasks _______________________________________________227
Formatting Event Messages ______________________________________229
Resetting a Virtual Machine ______________________________________234
Moving Virtual Machines Across Hosts ______________________________236
Migrating a Virtual Machine ____________________________________236
Moving a Virtual Machine’s Virtual Disks __________________________238
Responding to Virtual Machine Questions ___________________________241

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

C# Code Examples for Basic Operations _________________________ 257


Logging On to the Web Service ___________________________________ 258

Troubleshooting with the Managed Object Browser _______________ 259


Accessing the Managed Object Browser ____________________________ 260
Viewing Task Information with the Managed Object Browser ____________ 262

Glossary ____________________________________________________ 265

Upgrading VMware Tools _____________________________________ 275


Invoking UpgradeTools_Task _____________________________________ 276
Failure Mode _______________________________________________ 276
Cancelling the Operation ______________________________________ 276
Upgrading VMware Tools for a Single Virtual Machine – Java Example _____ 277
Upgrading VMware Tools in Batch – Java Example _____________________281

Performance Counters ________________________________________ 287


Counter Information Categories ___________________________________ 288
Most Useful Performance Counters ________________________________ 289
CPU Usage (Group: cpu) ______________________________________ 289
Disk Performance (Group: disk) _________________________________ 289
Memory Performance (Group: mem) _____________________________ 290
Network Performance (Group: net) ______________________________ 290
System Performance (Group: sys) _______________________________291

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

Privileges ___________________________________________________ 301


Privileges and Properties _________________________________________312

Revision History _____________________________________________ 315

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

How the Programming Guide Is Organized


The VMware Infrastructure SDK Programming Guide is organized in three sections: general concepts,
management concepts, and code samples.
The general concepts related to the VMware Infrastructure SDK are described in the following
chapter:
• VMware Infrastructure SDK Key Concepts on page 31
This chapter introduces you to the key concepts you should know before building a client
application. In later chapters, the guide elaborates on these concepts in relation to actual
operations used to perform actions in the VMware Infrastructure SDK.
The following chapters describe the operations used to perform actions in the VMware
Infrastructure SDK as well as any information specific to invoking these operations. These chapters
include:
• Logging On on page 61
This chapter describes the task of logging on, as well as the process of creating and
managing users, groups, and permissions.
• Managing Inventory on page 65
This chapter describes the tasks involved in managing inventory objects. These tasks include
the following:
• managing folders and datacenters
• creating, configuring, and re-configuring virtual machines
• performing power operations on virtual machines
• migrating virtual machines
• taking snapshots of virtual machines
• managing clusters and resource pools
• managing hosts
• configuring networks for a host
• managing datastores
• Getting Information and Updates on page 123
This chapter describes getting information about properties of managed objects in the
object model. This information can include obtaining managed object references, retrieving
the property values of managed objects, and finding out which properties have been
updated.

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

Using This Programming Guide


This VMware Infrastructure SDK Programming Guide is a companion book to the VMware
Infrastructure SDK Reference Guide and the VMware Infrastructure SDK Getting Started Guide. This
guide includes a description of VMware Infrastructure SDK concepts and discusses the operations
you can use to write your applications, including the effects of invoking those applications. The
remaining chapters contain a simple client application as well as code sample snippets that
illustrate various operations.
Note: The VMware Infrastructure SDK Documentation Roadmap provides a guide to usage of the
documentation included with the VMware Infrastructure SDK.
The VMware Infrastructure SDK Reference Guide contains a description of the datatypes as well as a
comprehensive description of all the Web service operations, including their input parameters,
results, and any Faults thrown by the operations.
The VMware Infrastructure SDK Porting Guide shows you how to port your Virtual Infrastructure SDK
1.x applications to the VMware Infrastructure Web Service 2.0. The guide contains a list of all the
legacy SDK 1.x operations, and their 2.0 equivalents. Each list includes a snippet of code to show
you how to port the legacy operation to 2.0. In some cases, the sample code combines several
operations, to illustrate a common user task.

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.

Java and the Code Samples in this Guide


Java is the programming language used for the code. Except for the simple client application in
Creating a Simple Java Client Application on page 191, the sample code snippets represent a small
portion of code and are designed to show the basic logic and programming constructs needed to
use the VMware Infrastructure SDK effectively. You cannot compile them. The
\SDK\Samples_2_0 directory contains a complete list of samples which you can compile and
run.

www.vmware.com
16
C H A P T E R 1 Introducing the Programming Guide

Supported VMware Products


In this release, the VMware Infrastructure SDK supports VMware VirtualCenter 2.0, and ESX Server
3.0.

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

VMware ESX Server


VMware ESX Server is VMware Infrastructure software for partitioning, consolidating, and
managing systems in mission-critical environments. ESX Server and VMware Infrastructure Nodes
provide a highly scalable virtual machine platform with advanced resource management
capabilities, which can be managed by VMware VirtualCenter.

17
VMware Infrastructure SDK Programming Guide

VMware Infrastructure Architecture


The VMware Infrastructure architecture depends on whether you are accessing the hosts through
VirtualCenter. The following two figures illustrate the architecture.

Accessing Hosts Through VirtualCenter


ISV
Management
Server ESX01.vmware.com

VMware Host Agent


VMware VirtualCenter
ESX02.vmware.com
Web
Services
SOAP/HTTPS Interface

Management VMware
VMware Host Agent
Server DB Proprietary
VMware Protocol ESX03.vmware.com
Proprietary
Protocol

VMware Host Agent


VirtualCenter DB
VMware VirtualCenter
Client GUI

Accessing Hosts Without VirtualCenter


ISV Management
Server

ESX01.vmware.com
SOAP/HTTPS
Management VMware
Server DB Proprietary
Protocol VMware Host Agent

ESX Client GUI VMware VMware ESX02.vmware.com


Proprietary Proprietary
Protocol Protocol

VMware VMware Host Agent


Proprietary
ESX Client GUI Protocol
ESX03.vmware.com

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

VMware Infrastructure SDK Package


Obtain the VMware Infrastructure SDK package on the Web at http://www.vmware.com/support/
developer/. This page includes information on what is contained in the package and the
instructions for downloading this package.

Web Service Standards and the VMware Infrastructure SDK


VMware Infrastructure SDK strives to conform to the Web Services Interoperability organization
(WS-I) Basic Profile 1.0. The WS-I organization has a wide industry following with 127 members (see
www.ws-i.org).
The mission of WS-I is to promote interoperability of Web services across platforms, operating
systems, and programming languages. Conforming to the WS-I Basic Profile ensures that the
VMware Infrastructure SDK can be used from within the widest range of development
environments.
A WS-I profile is a prescription for the use of a set of existing standards at specific versions. For
example, the WS-I Basic Profile 1.0 covers XML Schema 1.0, SOAP 1.1, WSDL 1.1, and UDDI 2.0. In
addition to prescribing these standards, the profile also narrows these standards by specifying best
practices and excluding optional or loosely specified features.
The WS-I basic profile is expressed as a set of assertions about the format and sometimes the
interpretation of SOAP messages and the WSDL document. The verification of most of these
assertions can be done automatically by examining artifacts (SOAP messages and the WSDL file)
exchanged between a Web service client and server. The WS-I organization has published tools
that do this verification. VMware, Inc. uses these tools on a regular basis to test the conformance of
the VMware Infrastructure SDK to the WS-I Basic Profile 1.0.
In addition to WS-I, VMware, Inc. actively monitors the evolution of other Web Services standards
that might be relevant to its domain.
• DMTF – www.dmtf.org
• W3C – www.w3.org

19
VMware Infrastructure SDK Programming Guide

Technical Support Resources


Refer to the following for additional information.
• VMware Infrastructure SDK – www.vmware.com/support/developer
• VMware ESX Server – www.vmware.com/products/server/esx_features.html
• VMware GSX Server – www.vmware.com/products/server/gsx_features.html
• VMware VirtualCenter – www.vmware.com/products/vmanage/vc_features.html
• W3C SOAP 1.1 Specifications – www.w3.org/TR/SOAP/
• XML Schema – www.w3.org/2001/XMLSchema
• HTTPS (SSL v3) – wp.netscape.com/eng/ssl3/ssl-toc.html
• WSDL 1.1 – www.w3.org/TR/wsdl
• HTTP 1.1 – www.ietf.org/rfc/rfc2616.txt
• XML 1.0 – www.w3.org/TR/REC-xml
• Perl – www.cpan.org
• Java – java.sun.com
• C# - msdn.microsoft.com/vcsharp/programming/language
• C/C++ - www.research.att.com/~bs/C++.html

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

Connecting to the VMware Infrastructure Web


Service
To connect to the VMware Infrastructure Web Service, a client application needs to know how to
send and receive data from the Web service. In particular, the client needs to know about the Web
service’s data types, its parameters, return types, location, and transmission details of the VMware
Infrastructure Web Service. The Web Services Description Language (WSDL) is an XML-based
language that describes these Web service interface details. The WSDL also describes how the
interface is tied to a transport protocol (in this case, secure HTTP) and encoding (in this case,
SOAP). From the WSDL, you can generate a stub.

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.

Client Development HTTP/S Web


Stub runtime service
environment

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

Selecting a Development Environment


A Web service development environment (WSDE) facilitates the building of Web service servers
and clients. Axis from Apache is a popular example of such an environment for Java. The Web
service development environments are also integrated into the more popular integrated
development environments (IDEs).
The Web service development environments support a variety of capabilities such as generating
server code, generating WSDL from other language APIs, generating client code, and so on. While
server side development is the typical emphasis of Web service development environments, the
environment is required to generate client code from the WSDL file provided in the SDK. We
provide the Web service server.

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.

Microsoft Visual Studio .NET and .NET Framework


The .NET framework is a runtime environment for running .NET applications. It is similar to the
C-runtime library, although it has many more components than a single DLL. To run a .NET
application, you must first install the appropriate version of the .NET framework (for VMware
Infrastructure SDK this is version 1.1 or 2.0). Unlike a typical run-time library, the .NET framework is
not distributed together with the applications that use it. Instead, users must install it. The .NET
framework is available at msdn.microsoft.com/downloads/.
Microsoft Visual Studio .NET is a development environment for building a variety of Windows
applications, including .NET applications. It also includes extensive support for building .NET-based
Web Services applications, such as Web service server and Web service client applications. While
Microsoft Visual Studio .NET is necessary to develop and debug a .NET application, it is not required
to run a released version of such an application. Only the .NET framework is needed. To obtain a
copy of Microsoft Visual Studio .NET, you can either purchase it directly from Microsoft or receive it
as part of the MSDN subscription.
For more information about Visual Studio and the .NET Framework, click on their links in the
Developer Centers section of msdn.microsoft.com.

VMware Infrastructure SDK Applications Developed with .NET


The C# sample applications contained in the VMware Infrastructure SDK package are developed
using Microsoft Visual Studio .NET 2003 and 2005 and .NET framework (version 1.1 and 2.0).

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

Setting up the VMware Infrastructure SDK


Client
See the VMware Infrastructure Installation and Upgrade Guide for information about installing and
configuring the VMware Infrastructure SDK server.

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.

Generating Stubs with Apache Axis


Once you have downloaded the Apache Axis SDK (from ws.apache.org/axis), perform the following
steps:
1. Set the JAVAHOME variable to either JDSE 1.4 or 1.5.
For example, C:\apps\Java\J2SDK.
2. Set the AXISHOME variable to the path to the Apache Axis directory.
For example, C:\apps\apache\axis-1_2_1.
3. Include the following .jar files in your CLASSPATH:

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;

4. Include the following directories in your PATH variable:


%AXISHOME%\bin\;
%JAVAHOME%\bin\;

5. Generate the stub files by typing:


java org.apache.axis.wsdl.WSDL2Java -O-1
-Nurn:vim2Service=com.vmware.vim -Nurn:vim2=com.vmware.vim
-o . vimservice.wsdl

The first argument to WSDL2Java (-Nurn:vim2Service=com.vmware.vim


-Nurn:vim2=com.vmware.vim) specifies a namespace translation from the Web service
namespace to the Java namespace. All the stub code classes are generated into the package,
com.vmware.vim.
The second argument (-o .) specifies where the stub code is generated (into the current
directory). Specifically, the stubs are generated into the directory %SDKHOME%/com/
vmware/vim.
The third argument (vimservice.wsdl) is the name of the WSDL file provided by
VMware. If the file is not present in the current directory, type the complete path to the file.
If this command works correctly, you will see a large number of java and class files in the
directory, %SDKHOME%\samples_2_0\Axis\java\com\vmware\vim.
6. Add vim.jar to your classpath.
%SDKHOME%\samples_2_0\Axis\java\vim.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

Configuring for the https (SSL) Protocol


For communication, ESX Server uses a self-generated SSL certificate located at:
/etc/vmware/ssl/rui.crt. VirtualCenter Server uses a self-generated SSL certificate
located at: C:\Documents and Settings\All Users\Application
Data\VMware\VMware VirtualCenter\SSL\rui.crt. You must install these
certificates into a certificate store on the client machine.
1. Copy the certificate file(s) from the server(s) to a directory on the client machine.
2. Create the samples.
For .NET applications or .NET samples, see Creating .NET Applications or Running .NET
Samples on page 28.
For Java applications or Java samples, see either Creating Java Applications or Running Java
Samples (Windows) on page 28 or Creating Java Applications or Running Java Samples
(Linux) on page 29.

Creating .NET Applications or Running .NET Samples


To create .NET Applications and to run .NET samples:
1. In Windows Explorer right click on the certificate file and select Install Certificate.
2. Follow the instructions, accepting the default selections.

Creating Java Applications or Running Java Samples (Windows)


The run.bat file is configured to use a certificate store located at
C:\VMware-Certs\vmware.keystore. To create this certificate store:
1. Open a command prompt.
2. Create the C:\VMWare-Certs directory.
3. Make sure the Java SDK tools are in your path.
4. Change to the C:\VMware-Certs directory
5. Import a certificate.
a. Enter the keytool command.
keytool -import -file <certificate-filename>
-alias <server-name> -keystore vmware.keystore

For example:
keytool -import -file vc-server1.cer -alias vc-server1
-keystore vmware.keystore

b. Enter a password for the keystore.

www.vmware.com
28
C H A P T E R 2 Developing Client Applications

c. Enter yes to import the certificate.


6. Repeat the last step for each certificate you wish to import.

Creating Java Applications or Running Java Samples (Linux)


The run.sh file is configured to use a certificate store located ~/vmware-certs/
vmware.keystore. To create this certificate store:
1. Create the ~/vmware-certs directory.
2. Make sure the Java SDK tools are in your path.
3. Change to the ~/vmware-certs directory.
4. Import a certificate.
a. Enter the keytool command.
keytool -import -file <certificate-filename>
-alias <server-name> -keystore vmware.keystore

For example:
keytool -import -file vc-server1.cer
-alias vc-server1 -keystore vmware.keystore

b. Enter a password for the keystore.


c. Enter yes to import the certificate.
5. Repeat the last step for each certificate you wish to import.

Configuring for the http (non-SSL) Protocol


To use the http protocol to access to the VirtualCenter Web Service, you must edit the
configuration file.
Note: You should do this only in a test or development environment.

Editing the Configuration File (VirtualCenter Server)


The vpxd.cfg file is located at C:\Documents and Settings\
All Users\Application Data\VMware\VMware VirtualCenter\vpxd.cfg.
1. Locate the <proxyDatabase> tag within the <http> tag.
2. Within the <proxyDatabase> tag, add the following text:
<server id="1">
<namespace> /sdk </namespace>
<host> localhost </host>
<port> -2 </port>
</server>

29
VMware Infrastructure SDK Programming Guide

3. Restart the VMware VirtualCenter Server service. This can be done by using the Services
Control Panel Applet.

Editing the Configuration File (ESX Server)


The config.xml file is located at: /etc/vmware/hostd/config.xml.
1. Locate the <proxyDatabase> tag within the <http> tag.
2. Within the <proxyDatabase> tag, add the following text:
<server id="1">
<namespace> /sdk </namespace>
<host> localhost </host>
<port> 8085 </port>
</server>

3. Remove the following text:


<redirect id="2"> /sdk </redirect>

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

VMware Infrastructure SDK Terminology


The concepts defined in this section are used throughout this guide and the VMware Infrastructure
SDK Reference Guide. Familiarize yourself with this terminology to enhance your use of the VMware
Infrastructure SDK.

Managed Objects and Data Objects


The VMware Infrastructure SDK comprises two types of objects: managed objects and data
objects. A managed object represents either a physical item in inventory (such as a VirtualMachine
or a HostSystem), an inventory location (such as a Folder or Datacenter), or a service (such as a
PropertyCollector or SessionManager). A ManagedEntity is a managed object that represents the
inventory items or location.
A data object represents information about the managed object. For example, a PropertyFilterSpec
represents a specification that defines a PropertyFilter managed object. Both the managed object
and data object are instances of composite object types.
Managed objects and data objects have the following qualities:
• Managed object types are not present in the WSDL schema.
• Managed objects exist only on the server and are passed by reference in the WSDL data
stream. The term “managed object reference” denotes a reference to a server-side object that
can be accessed only indirectly by the client.
• Data objects are serialized into the WSDL data stream. This allows them to be passed by value
between the client and the Web service.
Refer to the VMware Infrastructure SDK Reference Guide for a list of the managed object types.

Managed Object References


Managed object types are server side objects. They are not present in the WSDL schema, because
they are never passed in their entirety between client and server. Either the client works with a
reference to a managed object, or the client works with data objects that represent parts of the
managed object.

Obtaining a Managed Object Reference


You can obtain a managed object reference in the following ways:
• Construct a managed object reference
You construct a managed object reference only when you need a reference to the
ServiceInstance object. See Logging On to the Web Service on page 198 for an example in
Java and C#,

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

ManagedObjectReference pCollector = sic.getPropertyCollector();

• Use a property collector


You usually use a property collector when you want to find a managed entity in the inventory
tree (such as virtual machines or hosts) or managed object references that are properties of
another object. See Getting Property Information on page 124.

Learning About the Contents of a Managed Object


After you have obtained a managed object reference, you can learn about the managed object’s
content in one of the following ways:
• An operation associated with the managed object can report its properties. For example, the
operation CurrentTime on the ServiceInstance managed object returns the current time on
the server.
• An operation associated with the managed object returns a data object contained by the
managed object. For example, the operation RetrieveServiceContent on the service instance

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.

Indexed and Key-Based Arrays


An array property is any property whose type is an array. The Web service data structures have two
categories of array properties: indexed arrays and key-based arrays.
Indexed arrays are accessed in the usual manner with an index integer. They are used for arrays of
data types where the position in the array does not change. For example, the roleList property of
the AuthorizationManager managed object is an array of autorization roles. If a new role is added
to the array, the position of the other elements does not change.
Key-based arrays refer to properties with either of the following characteristics:
• Its type is an array and the base type of the array has a key property.
• Its type is an array of managed object references.
The contents of a key-based array property are accessed by the value of either the key property or,
in the case of a managed object reference, its value property. The value of these fields is unique
across all the components of an array. The key-based array is used for information whose position
might change in the array. For example, the latestPage property of the TaskCollector managed
object represents the items in the viewable latest page. As new items are added to the collector,
they are appended at the end of the page. The oldest item is removed from the collector
whenever there are more items in the collector than allowed. Because the position of the elements
in the array might change, it is more efficient to use the key, a unique, unchanging value, to access

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.

Nested Properties and Property Paths


Certain objects in the VMware Infrastructure SDK require you to specify nested properties. When
you specify a property with a property path string in the form a.b, you are specifying a property
named a which is a reference to a complex data type (either a managed object or a data object)
containing a property named b. The property b is called a nested property.
Properties can nest to several levels, such as a.b.c. In this example, property b is a complex data
type containing a property named c. The property c might be a simple (built-in) type, or it might
be another complex type. If the final property in the property path string is a complex type, you
get back an instance of the data type of the last property mentioned. For example, by specifying
a.b.c, if c is a integer, then you get an integer. If c is a data object type, then you get an instance
of that type. If c is a ManagedOjbectReference, you get an instance of a ManagedObjectReference.
Nested properties can also refer to properties that are key-based arrays. For example,
a.b.c["xyz"] refers to the property c that has the key value of xyz. See Indexed and Key-
Based Arrays on page 34 for more information.

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

Folder Folder Folder

Datacenter

vmFolder hostFolder

VirtualMachine VirtualMachine VirtualMachine VirtualMachine ComputerResource ComputeResource ClusterComputeResource ComputeResource

ResourcePool Host ResourcePool Host ResourcePool Host Host ResourcePool Host

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

ComputeResource and ClusterComputeResource


A ComputeResource managed object represents either a single host or, as extended by the
ClusterComputeResource managed object, a cluster of hosts available for backing virtual
machines.
A ComputeResource managed object can contain:
• One or more hosts.
• Datastores available to the hosts.
• Network objects available to the hosts.
• Basic runtime information about the compute resource (a ComputeResourceSummary data
object).
• EnvironmentBrowser object that allows the client to browse files on datastores, HardwareInfo
objects, and ConfigOption objects.
• Reference to the root ResourcePool object. See ResourcePool on page 37.
Some installations support extending the concept of a ComputeResource to include more than
one host. When that happens, the ComputeResource managed object is extended to become a
ClusterComputeResource managed object.
You can enable A ClusterComputerResource for VMware HA, VMware DRS, for both or neither.

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.

Resource Pools for Standalone Hosts


When you add a standalone host, a root resource pool is automatically added with the host, as
shown in the following example.

Datacenter

vmFolder hostFolder

ComputeResource

Resource
Host
Pool

Resource Pools for HA-Enabled Clusters


When you create a HA-enabled cluster, a single root resource pool is created for the cluster. The
HA-enabled cluster does not support hierarchical resource pools. Every time you add a host to the
cluster, the host’s resources are added to the single resource pool. You cannot associate a specific
resource pool with a particular virtual machine. All virtual machines associated with hosts in the
cluster are associated with the same root resource pool. In the following example shown above,

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

Folder Folder Folder Folder ClusterComputeResource (DAS)

VirtualMachine VirtualMachine VirtualMachine VirtualMachine Host Host Host Host


ResourcePool

Resource Pool Subdivisions


For standalone hosts and DRS-enabled clusters, you can divide the root pool among child resource
pools. You can further subdivide these child resource pools to arbitrary depths. This allows the
flexibility to implement complex resource allocation policies between competing needs.
You add resource pools to a parent resource pool in two ways:
• Create a resource pool (Creating Resource Pools on page 91).
• Move a resource pool to another parent (Moving Resource Pools and Virtual Machines Into a
Resource Pool on page 95).
In either case, an exception is thrown when the sum of the configured minimum available
resources (the reservation property of the ResourceAllocationInfo object) of the child resource
pools exceeds its parent.
Note: The sum of the reservation properties should never equal the resources of the parent.
An inconsistency in this rule can happen through an action on the cluster, such as when a host is
removed. This results in one of the states described in Resource Pool States on page 41.
The following figure shows two virtual machines associated with a standalone host where the
resource pool has been sub-divided.

39
VMware Infrastructure SDK Programming Guide

Datacenter

vmFolder hostFolder

Folder Folder Folder Folder ComputeResource

VirtualMachine VirtualMachine VirtualMachine VirtualMachine Host


ResourcePool
10 GB

ResourcePool ResourcePool
2 GB 6 GB

Notice that the sum of the minimum available resources is less than the the parent resource pool.

Resource Pools and DRS-Enabled Clusters


When you create a DRS-enabled cluster, a single root resource pool is created for the cluster. Unlike
the HA-enabled cluster, however, the DRS-enabled cluster supports hierarchical resource pools, as
shown in the following figure.

ClusterComputeResource (DRS)

Host Host
ResourcePool

Resource Resource
Pool Pool Resource
Pool

Resource Resource Resource


Pool Pool Pool

Clusters Enabled for Both DRS and HA


You can configure a cluster to be both DRS-enabled and HA-enabled. The advantage is that, if the
attempt to power on in the original resource pool fails admission control (not enough resources in
the resource pool), the virtual machine will power on in the root resource pool.

www.vmware.com
40
C H A P T E R 3 VMware Infrastructure SDK Key Concepts

Resource Pool States


The states modify the tree’s behaviour and the enforcement of the admission control policies. A
resource pool can be in one of three states:
• GREEN – A tree that's in a good state. As shown in the following figure, for every node, the
minimum configured resources available for a resource pool or virtual machine are greater
than the sum of the minimum configured resources for its children.

ClusterComputeResource (DRS)

Host Host Host

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

Commonly Used VMware Infrastructure SDK


Operations
This section gives a brief overview of four of the most common operations.

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.

CreateFilter, CheckForUpdates, and WaitForUpdates


To get updates on properties, you create a PropertyFilterSpec to search for the managed object
with the properties whose updates you want to check.
• The CreateFilter operation takes as its arguments a PropertyCollector managed object
reference, a PropertyFilterSpec, and a partialUpdates boolean property. The operation returns
a PropertyFilter managed object reference. The filters created with this operation exist as long
as the client session continues and are deleted as soon as the client session ends (logout).
See Getting Information and Updates on page 123 for more information about the
PropertyFilterSpec.
• The CheckForUpdates operation takes as its arguments a PropertyCollector managed object
reference and an optional version string. This operation examines any filters created during
this session and returns an UpdateSet consisting of an array of the filters and their updates.

43
VMware Infrastructure SDK Programming Guide

• The WaitForUpdates operation is similar to the CheckForUpdates operation. Unlike


CheckForUpdates, this method waits until updates are available before it completes.

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

Operations That Return a Task


A number of operations in the VMware Infrastructure SDK have _Task in their operation name (for
example, CreateVM_Task, AddHost_Task, and so on). These operations are asynchronous. These
operations return a Task managed object reference.
Each Task object contains an info property of the TaskInfo data object type. The info.state property
determines if the task has completed successfully. If the task completes successfully, you can find
the return value in the info.result property.
For example, when you invoke CreateVM_Task, the operation returns a Task managed object
reference. After the task completes successfully (info.state = “success”), you can find the
VirtualMachine managed object reference in the info.result property, which you can retrieve using
a PropertyCollector. For information about using the PropertyCollector, see Getting Property
Information on page 124.

45
VMware Infrastructure SDK Programming Guide

Client-Web Service Interactions


The primary interaction between the client and the Web service involves obtaining managed
object references, obtaining information about these managed objects, checking the managed
objects for updates when their values change, or invoking operations on these objects.
Clients obtain information about the managed object by issuing the RetrieveProperties call to the
Web service passing in two parameters: a PropertyCollector managed object reference and a
PropertyFilterSpec. The PropertyFilterSpec defines the information for which the client is searching:
one or more managed objects and one or more properties of each. The operation returns an array
with the information collected.
A client can ask for updates or changes to a managed object by invoking either the
CheckForUpdates or WaitForUpdates operation. The updates are returned as an array of UpdateSet
data objects that describe only the changes to the object, thus avoiding the need to return the
entire new object to the client.
Note: Only the latest updates are returned to the client from a CheckForUpdates or
WaitForUpdates call. All intermediate updates are lost. For example, if one application changes the
memory size of a virtual machine from 1GB to 2GB, and then immediately changes it back to 1GB,
it is possible that another application may never realize that this change occurred.
By managing these objects, the clients can implement various kinds of application functionality
based on VMware virtual machine technology.

Returning Escaped Characters


For any name or path property sent from the Web service to SDK clients, any / (slash), \ (backslash),
character is escaped. The % (percent) character is escaped, unless it is used to start an escape
sequence. The characters are escaped using standard URL notation. A slash is escaped as %2F or
%2f. A backslash is escaped as %5C or %5c, and a percent is escaped as %25.

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.

Datacenter Folder rootFolder


childType = {Folder, Datacenter}

Folder Folder Folder

Virtual Machine Folder Host Folder


childType = {Folder, VirtualMachine} Datacenter childType = {Folder, ComputeResource}

vmFolder hostFolder

VirtualMachine VirtualMachine VirtualMachine VirtualMachine ComputerResource ComputeResource ComputerResource ComputeResource

ResourcePool Host ResourcePool Host ResourcePool Host Host ResourcePool Host

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.

The childType Property


Within the virtual machine folder, the value of the childType property lets you create folders and
virtual machines. These folders are called virtual machine folders. Within the host folder, the
property value lets you create folders and computeresources. These folders are called host folders.
By prescribing acceptable childType values, the system encourages a logical organization of
objects and relationships. For example, root folders have childType values of Folder and
Datacenter. This allows the root folder to contain other folders and data centers, but it prevents
objects such as those of type ComputeResource or VirtualMachine, which should not exist outside
of data centers, from being created there. Refer to the Folder managed object in the VMware
Infrastructure SDK Reference Guide for a complete description of the childType property.

www.vmware.com
48
C H A P T E R 3 VMware Infrastructure SDK Key Concepts

Events, Tasks, and Alarms


Event management consists of events, tasks, and alarms.

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.

The EventManager Managed Object


The EventManager managed object comprises all the operations and properties needed to
manage events. One of these properties, latestEvent, contains the latest event that occurred on the
server. The maxCollector property describes, for each client, the maximum number of event
collectors that can exist simultaneously.
The operations include the following:
• CreateCollectorForEvents – This operation lets you retrieve historical information about
events. See Retrieving Historical Information on page 159 for more information
• LogUserEvent – This operation lets you create a user-defined event. See Logging a User-
Defined Event on page 152 for more information.
The EventManager object is accessed from the ServiceInstance through the ServiceContent data
object. The ServiceContent data object is returned by the RetrieveServiceContent operation.

Tasks
There are two types of tasks in the VMware Infrastructure SDK: scheduled tasks and active tasks.

Scheduled and Active Tasks


Scheduled tasks are actions that you define on an entity in the inventory tree according to a
schedule. These actions can include invoking operations, sending email, running a script, or
sending an SNMP trap. Using various objects, you can schedule tasks to fit any time constraints. For
more information, see Defining the Task Schedule on page 154.

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.

States of Active Tasks


Active tasks have four states: error, queued, running, and success. When there are too many tasks
for threads to handle, the tasks are queued. When the busy thread is freed from its current task by
finishing the task, it picks a queued task to run. The queued tasks are marked as running.

Task and ScheduledTask Managed Objects


Tasks are represented by two managed objects: Task and ScheduledTask. The Task managed object
reference lets you monitor and potentially cancel long running operations. The ScheduledTask
managed object reference lets you define actions (such as invoking an API operation) based on a
schedule.

Using a History Collector for Historical Task Information


Two managed objects let you retrieve historical information for events and tasks: the
EventHistoryCollector and the TaskHistoryCollector. These objects extend the properties and
operations of the HistoryCollector managed object.
To retrieve historical information about an event or task, you create a history collector. The items in
a history collector are always listed by date and time of creation. Item properties normally include
this time stamp. Based on this time stamp, the items in the collector are listed from oldest to
newest. You view information from the collector based on a page-by-page view from the current
position in the list. You define the number of items in a page when you invoke the read operation.
By default, when the history collector is created, the current position is set to the oldest item in the
list.
See Retrieving Historical Information on page 159 for more information.

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

The conditions that can trigger alarms include:


• Power state of a virtual machine.
• Network connection state of a host.
• Resource usage metrics that exceed a defined limit.
When an alarm triggers an API operation, it produces an event for the event history database. The
action triggered by the alarm may also leave event history.

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.

HostNetworkSystem and the Network Managed Objects


The HostNetworkSystem describes the networking configuration for a host. This managed object
comprises operations and data objects that define the host’s IP address, gateway, DNS
configuration, offload capabilities, and so on. This information must be enabled for migration,
iSCSI, and Network Attached Storage (NAS).
The Network managed object represents a network accessible by either hosts or virtual machines.
This can be a physical network or a logical network, such as a VLAN. Networks are created
automatically, either when you add a host to VirtualCenter or when you add a virtual machine to a
host or to VirtualCenter.

PhysicalNic and VirtualNic


The Virtual Network Interface Card (VNIC) describes a virtual network adapter representing an
adapter that connects to a virtual switch. A VirtualNic differs from a PhysicalNic in that the latter
corresponds to a physical device that is connected to the physical network. The former is a virtual
device that is connected to a virtual switch. A VirtualNic accesses the external network through a
virtual switch that is bridged through a PhysicalNic to a physical network. The VMkernel uses these
network adapters for features such as migration, NAS, iSCSI, and remote MKS connections.

Port Groups and Virtual Switches


A port group aggregates multiple ports under a common configuration and provides a stable
anchor point for virtual machines connecting to labelled networks. Each port group is associated
with one or more virtual switches. The virtual switch is a software entity to which multiple virtual
network adapters can connect to create a virtual network. Through a Host Network Policy, the port
group can be bridged to a physical network.
You can define a host network policy on either a port group or a virtual switch. Any policy defined
on the port group takes precedence over policy settings on the virtual switch.

The Port Group and Migration


When you configure a virtual machine, you always provide backing information, that is,
information about the physical devices represented by the virtual devices. One of the physical
devices is the ethernet card. When you configure this device, you provide a deviceName property
value. This value corresponds to the name of a port group on the associated host. You can migrate

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)

Local File System


A datastore that is backed by a local file system volume uses a host native local file system such as
NTFS or ext3. The datastore is created by identifying a file path for a directory in which virtual
machine data will be stored. When the datastore is deleted, the mapping from the datastore to the
file is deleted. The contents of the directory are not deleted.

Network Attached Storage (NAS) Volume


A datastore that is backed by a network-attached storage device is created by specifying the
required data needed to attach the volume to the host. Destroying the datastore detaches the
volume from the host.

VMware File System (VMFS)


A datastore that is backed by a VMware File System (VMFS) is created by specifying a disk with
unpartitioned space, the disk partition format on the disk, and some VMFS attributes.
An ESX Server system automatically discovers the VMFS volume on attached Logical Unit Numbers
(LUNs) on startup and after re-scanning the host bus adapter. The VMFS discovered volumes are
added in VirtualCenter as datastores. The datastore label is based on the VMFS volume label. A
conflict with an existing datastore is made unique by appending a suffix. The VMFS volume label
will be unchanged.
On an ESX Server host, each VMFS volume is represented as a datastore. The name of the datastore
is the VMFS label.

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>

In this syntax, <datastore_path> is equivaluent to one of the following


'[' <datastore_name> ']'
'[]' | # empty. <filepath> is host local path
'' | # empty. <filepath> is relative - implied by
| # context.

Note the following:


• Datastore paths always use the / separator. (The \ separator is converted on Windows
systems.)
• When creating a virtual machine or virtual disk, clients can specify just the datastore. The file
path is automatically assigned based on the standard file-naming convention.
• If the datastore portion is empty, ‘[]’, then the file is not located on a datastore, and the
Web service shows the host-local path. (This typically happens only for a virtual machine that
has an invalid configuration.)
These examples to illustrate the datastore name format:
[QA-SAN] X.vmdk # The X.vmdk disk on the shared QA-SAN
[EXIT14-DS] home/abc/Y.vmdk # Disk Y.vmdk on home/abc relative to the
# EXIT14-DS shared datastore.
[QA-SAN] # Root directory of the QA-SAN shared datastore.
/path/to/x.vmdk # A relative path. The base datastore needs to
# be defined from the context.
[] /vmfs/foo.vmdk # An absolute host local path. Useful on Linux.
[] g:/path/to/x.vmdk # An absolute host local path. Useful on Windows.
x.vmdk # Disk x.vmdk relative to the virtual machine's
# configuration file
[] [] # A relative filename []

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.

Memory Files and Snapshots


If you create a snapshot of a virtual machine that is powered on, a file is created that contains the
memory contents of the virtual machine at that time. Memory snapshots consume time and
resources, and thus take longer to create. You can set an option, however, that suppresses this
behavior.

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

CounterIds and MetricIds


Performance information is divided into performance counters and performance metrics. A
performance counter describes information collected, while a performance metric is the actual
information collected.
A performance counter is identified by a CounterId. For the entities in question (for example, a host
or virtual machine), there might be multiple instances of the device for which the same
performance counter can be collected. Each instance is a performance metric. For example, CPU
Usage is a performance counter for hosts (represented as host.cpu.usage), while Usage collected
for CPU #1 for a host is a performance metric (represented as host.cpu.usage@1).
A performance metric is identified by MetricId, which includes the Performance Counter Id and the
instance number of the device from which the metric is collected.
See PerformanceManager in the VMware Infrastructure SDK Reference Guide for more detailed
information about performance counters and performance metrics.
The query operations described in the following sections each take a MetricId as one of its
arguments. The QueryAvailablePerfMetric operation returns a list of the MetricIds. From this list,
you select the MetricId that you want to use.

Starting Time/Ending Time/Maximum Samples


When you invoke the QueryPerf operation, you can specify the starting and/or ending time for the
query, as well as the maximum number of samples to be returned. The times specified should
correspond to the server time. When the starting time is omitted, the returned metrics start from
the first available metric in the system. When the ending time is omitted, the returned result
includes up to the most recent metric value. The optional maxSample specifies the maximum
number of samples to be returned by the query. If no startTime or endTime is specified, but if a
maxSample is specified, the query returns the most recent maxSample number of samples.

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

Instantiating an Instance and Opening a User


Session
To perform these actions, use the following steps:
1. Create a new managed object reference in your client code.
Set the type to ServiceInstance and the name to ServiceInstance.
ManagedObjectReference _svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
_svcRef.setValue("ServiceInstance");

2. Create the code that references the Web service URL.


VimServiceLocator _locator = new VimServiceLocator();
_locator.setMaintainSession(true);
_service = _locator.getVimPort(new URL("https://<your_server>/sdk"));

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

Setting the Locale


The Login operation includes an optional locale parameter that lets you define the language. This
string is a two-character ISO-639 language ID (like "en") with an optional two-character ISO 3166
country ID (like "US") appended. Other examples are "de", "fr_CA", "zh", "zh_CN", and "zh_TW". When
the optional parameter is not provided, the operation uses the server default locale.
You can also use the SetLocale operation to set the locale.

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

Managing Folders and Datacenters


As described in Inventory Management on page 47, the inventory tree comprises Folder and
Datacenter managed objects.

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.

Deleting the Folder and Unregistering the Virtual Machines


You invoke the UnregisterAndDestroy_Task operation on a Folder managed object reference to
delete the Folder object and its children. This operation recursively unregisters all virtual machines
and destroys all child virtual machine folders.
Note: This operation applies only to VirtualMachine folders.
When you unregister a virtual machine, you are removing the object from the VirtualCenter
inventory. The virtual machine files remain in the Datastore.

Deleting a Folder and Its Contents Completely


The Destroy_Task operation lets you completely delete the Folder object and its contents. This
operation takes as its only parameter the Folder ManagedEntity managed object reference that
you want to delete.
This operation deletes the parent Folder and all child Folder or Datacenter objects. If the Folder
object contains virtual machines, this operation deletes any associated files in the datastore. The
HostSystem managed objects are removed from VirtualCenter management.
This operation applies to all Folder objects.

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.

Moving Entities into a Folder


The MoveIntoFolder_Task operation lets you move a set of ManagedEntity objects into a folder.
This operation takes the following parameters:
• Folder managed object reference – The folder into which you are moving the ManagedEntity
objects.
• list – An array of objects to be moved into the Folder.
The objects that can be moved into a folder depend on the folder's childType property value. (For
a description of the types of folders, see The childType Property on page 48.) Only datacenters and
datacenter folders can be moved into a datacenter folder. Only virtual machines and virtual
machine folders can be moved into a virtual machine folder. Only ComputeResource,
ClusterComputeResource and host folder objects can be moved into a host folder.
For information about specific entities, see the appropriate sections later in this chapter.

www.vmware.com
68
C H A P T E R 5 Managing Inventory

Creating a Virtual Machine


You can create a virtual machine in one of two ways:
• Create a virtual machine from scratch.
• Clone an existing virtual machine.

Creating a Virtual Machine from Scratch


The CreateVM_Task operation lets you create the virtual machine and takes the following
parameters:
• Folder managed object reference – This is the folder where you want to locate the virtual
machine.
• config – A VirtualMachineConfigSpec data object type. This object contains all the
configuration information for the virtual machine. See Configuring a Virtual Machine on
page 73 for information about configuring.
• pool – A reference to a ResourcePool managed object. It represents the resource pool with
which the virtual machine is associated.
• host – A HostSystem managed object reference. It represents the target host on which to run
the virtual machine. This must specify a host that is a member of the ComputeResource
indirectly specified by the pool . For a stand-alone host or a cluster with VMware DRS, you can
omit this parameter and let the system select a default.
For DRS-enabled clusters in manual mode, you invoke the RecommendHostsForVms
operations to obtain a list of recommended HostSystems managed object references based
on resource usage. You use one of the resulting managed object references for this
parameter. For more information, see Recommending Hosts for Virtual Machines on
page 104.
Note: All objects must be located in the same datacenter.

Cloning Virtual Machines


You use the CloneVM_Task operation to clone virtual machines with the following parameters:
• VirtualMachine managed object reference – The source virtual machine used for the clone.
Note: The source virtual machine can be either an active virtual machine or a template,
depending on the template setting in the configuration information of the source virtual
machine. See Creating Templates on page 71 for more information.
• Folder managed object reference – The folder in which you want to locate the new virtual
machine.

69
VMware Infrastructure SDK Programming Guide

• name – The name of the newly cloned virtual machine.


• spec – A VirtualMachineCloneSpec object that specifies how to clone the virtual machine.
This object contains properties that define the virtual machine:
• config – (optional) This VirtualMachineConfigSpec object specifies changes to the virtual
hardware. For example, this can be used to (but not limited to) reconfigure the networks
the virtual switches are hooked up to in the cloned virtual machine.
• customization – (optional) This CustomizationSpec object specifies any customization,
including encryption keys, network identities, and so on.
• location – This VirtualMachineRelocateSpec object defines the datastore location for the
virtual machine and the target host. You can locate the virtual disks in separate datastore
locations, so this spec includes a property that specifies the datastore location for each
virtual disk.
• powerOn – Whether or not to power on (deploy) the virtual machine after it is created.
• template – This boolean specifies whether or not the new virtual machine should be
marked as a template.

www.vmware.com
70
C H A P T E R 5 Managing Inventory

Managing Virtual Machine Templates


Templates let you create a virtual machine with a basic configuration that you can use to deploy
other, active virtual machines.

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.

Marking an Existing Virtual Machine as a Template


You change an existing virtual machine to a template.
1. Find the virtual machine you want to use as a template
You can either create a property collector or use one of the operations associated with the
SearchIndex managed object. See Getting Information and Updates on page 123.
2. Invoke the MarkAsTemplate operation.
This operation takes as its only parameter the reference to the specific virtual machine that
you want to change.

Cloning an Existing Virtual Machine


You use this process if you want to keep a specific virtual machine as a virtual machine, but still
want to use its copy of as a template.
1. Find the virtual machine you want to use as a template.
You can create a property collector to find the VirtualMachine managed object reference. See
Getting Information and Updates on page 123.
2. Clone the virtual machine.
See Cloning Virtual Machines on page 69. The VirtualMachineCloneSpec data object includes
a boolean property called template. To make the clone a template, set this boolean property
to true.

Changing a Template to an Active Virtual Machine


As described earlier, a virtual machine can either be an active virtual machine or a template. You
can change a template to an active virtual machine in one of two ways.
• Invoke the MarkAsVirtualMachine operation on the template. This clears the boolean
property that defines the virtual machine as a template and reassociates the virtual machine
with a resource pool and host. However, the template no longer exists.

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

Configuring a Virtual Machine


When you create (CreateVM_Task), clone (CloneVM_Task) or reconfigure (ReconfigVM_Task) a
virtual machine, you use the VirtualMachineConfigSpec data object and its properties to define or
modify the configuration.

Defining Console Preferences


The VirtualMachineConsolePreferences data object lets you define how the VMware Virtual
Machine Console application behaves during various virtual machine power states. This object
comprises three boolean properties:
• closeOnPowerOffOrSuspend –The console application is closed when the virtual machine is
powered off or suspended.
• enterFullScreenOnPowerOn – The console application enters full-screen mode when the
virtual machine is powered on.
• powerOnWhenOpened – A virtual machine is automatically powered on when it is opened
in the console.

Configuring CPU and Memory Information


A number of properties of the VirtualMachineConfigSpec let you set CPU and memory
information.

Specifying CPU Processors and Memory Nodes


If your virtual machine is on an ESX server and if you have a license which supports Symmetric
Multiprocessors (SMP), then you can configure the virtual machine to have multiple virtual CPUs.
Two properties let you specify CPU and memory: cpuAffinity and memoryAffinity. Both properties
are VirtualMachineAffinityInfo data objects. This object contains a single property, affinitySet. With
this array property, you define a set of integers that represents the processors (for CPU) and NUMA
nodes (for memory). If you are reconfiguring the affinity setting and leave the array empty, then
any existing affinity is removed.

Allocating CPU and Memory Resources


To allocate resources, you use two properties: cpuAllocation and memoryAllocation. For these
properties, the ResourceAllocationInfo data object specifies four properties:
• reservation – The minimum available resources. The amount of resource that is guaranteed
available to the virtual machine or resource pool. Reserved resources are not wasted if they
are not used. If the utilization is less than the reservation, the resources can be utilized by
other running virtual machines. Units are MB for memory, MHz for CPU.

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.

Defining the CPU Feature Mask


The cpuFeatureMask property is an array that provides processor identification information
through its data object type and its info property. The HostCpuIdInfo data object specifies the
values of the eax, ebx, ecx, and edx registers of each level of the CPUID.
Normally, you will not need to configure this information when you create a virtual machine. These
bit types are used to identify whether or not a virtual machine can be powered on or migrated
with VMotion to a particular host. For more information, see the HostCpuIdInfo property in the
VMware Infrastructure SDK Reference Guide.

Specifying the Amount of Memory


You set the memoryMB property to the size of the virtual machine’s memory (in megabytes).

Defining the Number of Virtual Processors


The numCPUs property lets you set the number of virtual processors in a virtual machine.

www.vmware.com
74
C H A P T E R 5 Managing Inventory

Defining the Virtual Devices


The deviceChange property is an array property that defines the set of virtual devices in the
configuration. For each virtual device you want to add to the virtual machine, you create a
VirtualDeviceConfigSpec data object. This object consists of several properties:
• device – This property is a VirtualDevice data object. This object, its extended objects, and
properties let you define information about the backing device, and connection information
about the device. It also includes key and unit number information. See Defining the Physical
Device on page 75.
• fileOperation – The type of operation being performed on the physical device backing the
specified virtual device. This property is optional. If no file operation is specified, then any
backing filenames in the VirtualDevice must refer to files that already exist. The property can
have the following values:
• create – Specifies the creation of the device backing, for example, the creation of a virtual
disk or floppy image file.
• destroy – Specifies the destruction of a device backing.
• replace – Specifies the deletion of the existing backing for a virtual device and the creation
of a new backing.
• operation – The type of operation being performed on the specified virtual device. This is
optional. Its values can be add, edit, or remove.

Defining the Physical Device


Every virtual device associated with a virtual machine must have a corresponding backing device,
that is, the physical device backing the virtual device. The following code snippet shows the
definition for a CD-ROM passthrough device:
VirtualDevice vd = new VirtualDevice();
vd.setBacking(vcpbi);
vd.setConnectable(vdci);
vd.setControllerKey(257);
vd.setDeviceInfo(vddesc);
vd.setKey(2);
vd.setUnitNumber(25);

Each property is explained in the following list:


• Backing Information
The backing property is a VirtualDeviceBackingInfo data object. Its sub-class
VirtualDeviceDeviceBackingInfo is extended by several data objects, each representing a
possible device. The following code snippet adds a CD-ROM passthrough device:

75
VMware Infrastructure SDK Programming Guide

VirtualCdromPassthroughBackingInfo vcpbi = new


VirtualCdromPassthroughBackingInfo();
// Does the virtual device have exclusive access to the CD-ROM device?
vcpbi.setExclusive(false);
// This specifies the device name.
vcpbi.setDeviceName('cdrom0');

• 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.');

Configuring the Virtual Machine for Migration


When you provide the backing information (as described in the previous section) for the ethernet
card, set the deviceName property to a port group name on the host. If the host’s network is
configured, you can migrate this virtual machine to other hosts that have a port group of the same
name.
Note: Both source and target hosts must be on the same physical network and must have access
to the same storage/VMFS volume(s) that the virtual machines utilize. For more information, see
Configuring Networks for a Host on page 106.
VirtualEthernetCardNetworkBackingInfo vecnbi = new
VirtualEthernetCardNetworkBackingInfo();

www.vmware.com
76
C H A P T E R 5 Managing Inventory

// This specifies the device name.


vecnbi.setDeviceName('portGroup1');

Defining File Information


The files property, through the VirtualMachineFileInfo, lets you define the datastore information.
You can set the directories for storing the log files, as well as the suspend, redo, and snapshot files.
If these files are not specified, this defaults to the same directory as the configuration file.

Naming the Virtual Machine


Any % (percent) character used in this name parameter must be escaped, unless it is used to start
an escape sequence.
If you are associating the virtual machine with a host on an ESX 2.x server, do not include spaces in
the name if you want to take snapshots. See Creating Snapshots and ESX 2.x Server on page 85.

Defining Network Shaping


You can optimize network traffic by using the networkShaper property. The
VirtualMachineNetworkShaperInfo data object comprises properties that define the average and
peak bandwidth (in bits per second), as well as the burst size. You can also set a boolean property
that will enable a network shaper to set network information automatically.

Defining Default Power Operations


The powerOpInfo property, through the VirtualMachineDefaultPowerOpInfo data object, lets you
define whether the power off, reset, or suspend operation will be soft (initiated by the guest) or
hard. You can also define standby behavior.

Setting Flags on the Virtual Machine


The flags property, through the VirtualMachineFlagInfo data object, lets you set flags for the virtual
machine. The flags include whether or not to enable logging, to run in the debug mode, or to use
TOE (TCP/IP Offloading). The flags also let you turn off video acceleration for a virtual machine
console window.

Defining Tools Information


The tools property, through the ToolsConfigInfo data object, lets you define how scripts are run in
relation to power operations.

Defining or Removing a Description


The annotation property lets you provide a description of the virtual machine. To remove an
annotation for a virtual machine, you must set the value of the property to an empty string.

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.

Defining the Universally Unique Identifier (UUID)


In most cases, you do not need to set this property. The VMware Infrastructure environment
assigns a UUID when the virtual machine is created or cloned. VirtualCenter tries to ensure that the
UUIDs of all virtual machines being managed are unique, changing the UUID of conflicting virtual
machines if necessary.
Note: In rare cases, such as a manual copy of a virtual machine, you might have two virtual
machines with the same UUID. VirtualCenter cannot change the UUID of a running (or suspended)
virtual machine because applications running inside the virtual machine could already know the
UUID, and might fail if it changes. As a result, if a newly added host contains a running or
suspended virtual machine whose UUID is the same as an existing running or suspended virtual
machine, VirtualCenter cannot resolve the conflict because it cannot change the UUID of either
virtual machine.

www.vmware.com
78
C H A P T E R 5 Managing Inventory

Performing Power Operations on a Virtual


Machine
You use several operations to perform power operations on a virtual machine. Each operation
requires a reference to the specific VirtualMachine managed object on which you want to perform
the power operation. You can obtain this managed object reference either by creating a property
collector (Getting Property Information on page 124) or by using a searchIndex operation (Finding
Entities Using a Property Value on page 135).

Powering On a Virtual Machine


The PowerOnVM_Task operation lets you power on a virtual machine. The operation takes as its
parameters a reference to the VirtualMachine managed object that will be powered on. If the
virtual machine is suspended, this operation resumes execution from the suspend point.
As an optional parameter, the operation can take a reference to the host where the virtual machine
is to be powered on. If you do not specify a host, the host that is currently associated with the
virtual machine is used. This field can be specified only for a virtual machine that is part of a cluster.
Also, the specified host must be part of the same cluster as the ResourcePool with which the
virtual machine is currently associated.

Powering Off a Virtual Machine


To perform a “hard” shutdown (without shutting down the guest operating system), you invoke
the PowerOffVM_Task operation on the virtual machine.
To perform a soft shutdown, you determine if the guest operating system is running by checking a
property called guestHeartbeatStatus. If the operating system is running, you invoke the
ShutdownGuest operation to shut down the guest operating and power off the virtual machine.

Suspending a Virtual Machine


The SuspendVM_Task operation lets you suspend operation of the virtual machine, referenced as
the sole parameter of the operation.

Resetting a Virtual Machine


The ResetVM_Task operation initiates the process of resetting a virtual machine, which also resets
the virtual hardware. (A reset operation is equivalent to pushing the Reset button on a physical
machine.)
The ResetVM_Task operation lets you power off, then power on a virtual machine. If the current
state is poweredOn, then this operation first invokes the PowerOffVM_Task operation for a hard

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

Migrating Virtual Machines


You can migrate a virtual machine from one host to another. You can either migrate a powered-on
virtual machine (a hot migration, called VMotion) or a powered-off virtual machine (a cold
migration).

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.

Enabling the VMotion Feature


You use the EnableFeature operation to enable VMotion on a host. This takes the following
parameters:
• LicenseManager managed object reference – You can obtain this managed object reference
through the ServiceContent data object. See Obtaining a Managed Object Reference on
page 32.
• HostSystem managed object reference – The host system on which you are enabling
VMotion. Because a HostSystem is a managed entity, you can use the inventory path to the
object to derive the managed object reference. See Finding Entities Using a Property Value
on page 135.
• featureKey – The string that indicates the feature being enabled. See EnableFeature in the
VMware Infrastructure SDK Reference Guide for a list of entries.

81
VMware Infrastructure SDK Programming Guide

Updating the VMotion IP Configuration


The UpdateIpConfig operation lets you reconfigure the IP information associated with the Virtual
NIC associated with VMotion on the host. The operation takes the following parameters:
• HostVmotionSystem managed object reference – Obtain by using a property collector for
configManager.vMotionSystem of the HostSystem managed object. See Getting Property
Information on page 124.
• ipConfig – The HostIpConfig data object. This object contains the information to reconfigure
the IP information.

Migrating a Powered-On Virtual Machine (VMotion)


MigrateVM_Task lets you migrate a virtual machine in any state: powered-on, powered-off or
suspended. However, this operation changes only the HostSystem association. The disk files are
not migrated. See Moving Files on page 83 for information on moving the disk files.
To ensure the state of the virtual machine being migrated, you can specify the power state as a
parameter. The parameters for MigrateVM_Task are:
• VirtualMachine managed object reference – The virtual machine to be migrated.
• pool – A reference to a ResourcePool managed object. The target resource pool for the virtual
machine. If this parameter is left unset, the virtual machine stays assigned to its existing
resource pool. You must specify a host within the same compute resource.
• host – A reference to a HostSystem managed object. The target host to run the virtual
machine. This must specify a host that is a member of the ComputeResource object indirectly
specified by the pool. For a stand-alone host or a cluster with VMware DRS, it can be left unset
and the system selects a default from the same ComputeResource object as the
ResourcePool specified by the pool parameter.
• priority – The priority of the migration task.
• state – If this parameter is specified, the virtual machine is migrated only if its state matches
the specified state.

Migrating a Powered-Off Virtual Machine


The MigrateVM_Task operation, described in the last section, migrates a virtual machine in either a
powered-on, powered-off, or suspended state. You can also use the RelocateVM_Task operation to
move a virtual machine in the powered off state. The difference between the two operations is
that MigrateVM_Task only changes the host association of the virtual machine. MigrateVM_Task
does not move the disk files. RelocateVM_Task not only changes the host association, but also
moves the disk files. See Moving Files on page 83 for information about the RelocateVM_Task
operation.

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

Managing Virtual Machine Snapshots


Snapshots on page 56 describes the concept of using snapshots to preserve a virtual machine at a
particular point in time, the state of the data on all the virtual machine’s disks, memory, and
devices, and whether the virtual machine was powered on, powered off or suspended.
By using various operations in the VMware Infrastructure SDK, you can build a snapshot tree, such
as the one shown in the following figure.

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.

Creating Snapshots and ESX 2.x Server


On virtual machines associated with a host on an ESX 2.x server, you can only create one snapshot
of a virtual machine. You can invoke CreateSnapshot_Task, then invoke RemoveSnapshot_Task to
remove the snapshot, then invoke CreateSnapshot_Task. However, you cannot invoke
CreateSnapshot_Task consecutively.
In addition, to invoke CreateSnapshot_Task, the virtual machine must be powered-on, have no
spaces in its name, and only have disks in persistent mode.

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

Obtaining a VirtualMachineSnapshot Managed Object Reference


Many snapshot operations require a VirtualMachineSnapshot managed object reference as a
parameter. You can obtain a VirtualMachineSnapshot managed object reference by creating a
property collector that collects specific properties of the VirtualMachine managed object. Each
virtual machine has a snapshot property which is a VirtualMachineSnapshotInfo data object. This
data object has a rootSnapshotList property that consists of an array of
VirtualMachineSnapshotTree data objects. Each element in the array contains a snapshot property
that is the VirtualMachineSnapshot managed object reference for that snapshot.
You can define a PropertySpec that collects these properties:
PropertySpec pspec = new PropertySpec();
setType("VirtualMachine");
setAll(Boolean.FALSE);
setPathSet(new String[] "snapshot.rootSnapshotList.snapshot");

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

Managing Clusters and Resource Pools


You can manage hosts either as single-host compute resources or you can group hosts together
into a cluster for load balancing as well as for high availability. By clustering hosts, you can take
advantage of failover capacities. Standalone hosts are associated with a ComputeResource.
Clustered hosts are grouped within a ClusterComputeResource managed entity.

Creating a Cluster of Hosts


You create a cluster of hosts in two stages:
1. Create a ClusterComputeResource.
You use the CreateCluster operation to create a ClusterComputeResource and a root
ResourcePool managed object.
2. Add hosts to the cluster.
For this you use either the AddHost_Task or MoveInto_Task operation. For information about
these operations, see Adding a Host to a Cluster on page 101.
The CreateCluster operation takes the following parameters:
• Folder managed object reference – The location in the inventory tree within which you want
to locate the cluster. You can use a property collector to find the specific managed object
reference. See Getting Information and Updates on page 123 for more information about
using a property collector.
The folder you select must be a host folder within a datacenter. See Inventory Management
on page 47 for an explanation of the inventory tree.
• spec – A ClusterConfigSpec data object. This object contains information about the cluster,
including whether this cluster is enabled for VMware HA or VMware DRS. See Configuring or
Reconfiguring a Cluster on page 89.
• name – The name for the new cluster.

Configuring or Reconfiguring a Cluster


The ClusterConfigSpec data object lets you configure a new cluster (CreateCluster) or reconfigure
an existing cluster (ReconfigureCluster_Task).

Enabling a Cluster for VMware DRS or VMware HA


For an explanation of these services and how they affect clusters and resource pools, see
ComputeResource and ClusterComputeResource on page 37 and ResourcePool on page 37.
You use the following four properties to enable the cluster. All the properties are optional. You can
enable VMware DRS, VMware HA, neither or both.

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.

Defining a Set of Rules


You can configure the cluster to define which virtual machines can run on the same host, and
which virtual machines must run on different hosts. You do this with the rulesSpec property of the
ClusterConfigSpec. This property is an array of ClusterRuleSpec data objects. Each element in the
array represents either an affinity rule or an anti-affinity rule for a specified VirtualMachine
managed object reference. Each rule defines the virtual machines that can run on the same host
(affinity rule) or must run on different hosts (anti-affinity).

Creating Resource Pools


A ComputeResource or a ClusterComputeResource always has one root resource pool. As
described in Resource Pool Subdivisions on page 39, you can create children of root resource pools
and their children for a ComputeResource or a DRS-enabled ClusterComputeResource. The
minimum available resources of the parent must always be equal to or greater than the sum of its
immediate children.
You create a resource pool using the CreateResourcePool operation. This operation takes the
following parameters:
• ResourcePool managed object reference – This is the parent resource pool.
• name – The name you want for the new resource pool.
• spec – A ResourceConfigSpec data object. This contains all the property information for
defining the resources in the resource pool. For more information, see Configuring Resource
Pools with the ResourceConfigSpec on page 92.

Reconfiguring Resource Pools


You can reconfigure one resource pool, or you can reconfigure the children of a parent resource
pool.

91
VMware Infrastructure SDK Programming Guide

Reconfiguring a Single Resource Pool


You use the UpdateConfig operation to reconfigure a single resource pool. This operation takes the
following parameters:
• ResourcePool managed object reference – The specifc resource pool you want to
reconfigure.
• name – Optional. The new name for the resource pool.
• config – The ResourceConfigSpec data object. The new configuration for the resource pool.
For more information, see Configuring Resource Pools with the ResourceConfigSpec on
page 92.
Note: To invoke this operation, you must have the Resource.EditPool privilege on the
ResourcePool managed object you are reconfiguring as well as on the resource pool’s parent
entity.

Reconfiguring a Set of Resource Pools


You can use the UpdateChildResourceConfiguration operation to perform bulk modifications of
some or all of the direct children (virtual machines and resource pools) of a resource pool.
This operation takes the following parameters:
• ResourcePool managed object reference – The resource pool whose children are being
modified.
• spec – An array of ResourceConfigSpec data objects. Each element of the array represents the
reconfiguration for the resource pool or virtual machine designated by the entity property.
For more information, see Configuring Resource Pools with the ResourceConfigSpec on
page 92.
Note: To invoke this operation, you must have the Resource.EditPool privilege on the
ResourcePool managed objects you are reconfiguring as well as on their parent entity.
Bulk modifications are not transactional. Each modification is made individually. The changes are
made to the first element in the spec parameter, then the next, and so on. If a failure is
encountered while applying the changes, then the processing stops, meaning at least one and as
many as all of the changes are not applied.

Configuring Resource Pools with the ResourceConfigSpec


You configure or reconfigure resource pools using the ResourceConfigSpec data object as a
parameter.

Allocating CPU and Memory


Two properties, cpuAllocation and memoryAllocation, let you configure CPU and memory. Both
properties use the ResourceAllocationInfo data object and its properties.

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)

Host Host Host

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)

Host Host Host

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.

Expanding the Minimum Resources


Resource pool resources are considered reserved if a running virtual machine uses them or if a
child resource pool has reserved them. All other resources are considered unreserved. The
expandableReservation property of the ResourceAllocationInfo data object enables the
reservation on a resource pool to grow beyond the specified value. If expandableReservation is
true, then the resource pool is allowed to grow its reservation dynamically by borrowing
unreserved resources from its parent resource pool.
For example, suppose a parent resource pool has 6 Ghz with one running virtual machine that uses
1 Ghz. You create a child pool with a reservation of 2 Ghz and the expandableReservation property
set to true. If you try to power on 2 virtual machines with 2 Ghz each on the child resource pool,
the first can take the resources directly from the child. Since expandableReservation is true, the
second takes the resources from the parent which has 3 Ghz available (6 - 1 for its running virtual
machine - 2 for its child resource pool).
This property is ignored for virtual machine configuration.

www.vmware.com
94
C H A P T E R 5 Managing Inventory

Setting a Limit to Memory/CPU Usage


The limit property of the ResourceAllocationInfo data object lets you specify that the usage will not
exceed a certain amount, even if resources are available. 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.

Specifying the Entity for the Configuration


The entity property of the ResourceConfigSpec lets you specify the resource pool for which this
resource configuration applies. This property is optional and useful only with the
UpdateChildResourceConfiguration operation, where you reconfigure a set of children of a parent
resource pool.

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.

Destroying the Children of a Resource Pool


The DestroyChildren operation destroys all the children of a resource pool recursively. The
operation takes a single parameter, a reference to the parent ResourcePool managed object whose
children you want to destroy. Any virtual machines associated with the children are re-assigned to
the parent.
Note: To invoke this operation, you must have the Resource.DeletePool privilege on the
ResourcePool managed object as well as on the resource pool’s children ebing destroyed.

Moving Resource Pools and Virtual Machines Into a Resource Pool


Sometimes you might want to move a resource pool and its children within a resource pool
hierarchy, or you might want to associate virtual machines with a different resource pool. For
example, the figure below shows two resource pool hierarchies that you want to move from one
parent to another, in this case, to the root resource pool. To do this, you invoke the
MoveIntoResourcePool operation.

95
VMware Infrastructure SDK Programming Guide

ClusterComputeResource (DRS)

Host Host Host

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

The MoveIntoResourcePool operation takes the following parameters:


• ResourcePool managed object reference – The resource pool into which you want to move
the resource pools. In the figure above, this parameter is a reference to the root resource pool
managed object.
• list – An array consisting of the ResourcePool or VirtualMachine managed object references
that you want to move. To move a resource pool hierarchy, you need to include only the
parent in the array. For example, in the figure above, you include only the 4 gigabyte and 10
gigabyte resource pools in the array. The children are automatically included.
Note: You cannot move a root resource pool. Also, you cannot move resource pools or
virtual machines between compute resources.
The figure below shows the result of the move from the last figure.

www.vmware.com
96
C H A P T E R 5 Managing Inventory

ClusterComputeResource (DRS)

10 GB
Resource

Host Host Host

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)

RP1 Host Host Host


12 GB
20 GB ResourcePool
Res ool 55 GB
10 GB

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

Host Host Host

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.

Adding a Standalone Host


You use the AddStandaloneHost_Task operation to add a new, single-host compute resource to
the inventory tree. (See Inventory Management on page 47 for an explanation of the inventory
tree.) The operation takes the following parameters:
• Folder managed object reference – The location in the inventory tree within which you want
to locate the host. You can use a property collector to find the managed object reference. See
Getting Information and Updates on page 123 for more information about using a property
collector.
• spec – A HostConnectSpec data object. This object contains the host name, port, and
passwords for the host to be added.
• addConnected – This flag specifies whether or not the host should be connected as soon as
it is added. If a connection attempt is made and fails, the AddStandaloneHost_Task operation
succeeds but the host is not connected. See Connecting and Disconnecting Hosts on
page 103 for more information.
When you add a standalone host to a folder, the operation automatically creates a compute
resource that contains both a HostSystem and a ResourcePool.

Datacenter

vmFolder hostFolder Single-host compute resource

...
ClusterComputeResource ComputeResource

ResourcePool Host Host ResourcePool Host


multi-host cluster computer resource
ResourcePool ResourcePool

www.vmware.com
100
C H A P T E R 5 Managing Inventory

Adding a Host to a Cluster


You use the AddHost_Task operation to add a host to a cluster. This operation takes the following
parameters:
• ClusterComputeResource managed object reference – The compute resource with which
you want to associate the host. You can use a property collector to find the managed object
reference. See Getting Information and Updates on page 123 for more information about
using a property collector. If necessary, you can also use CreateCluster to create a cluster. See
Creating a Cluster of Hosts on page 89.
• spec – A HostConnectSpec data object. This object contains the host name, port, and
passwords for the host to be added.
• asConnected – This flag specifies whether or not the host should be connected as soon as it
is added. See Connecting and Disconnecting Hosts on page 103 for more information.
• resourcePool – (optional) This parameter lets you specify a resource pool in the target cluster.
If you specify this parameter, the host’s original resource pool hierarchy is appended to the
specified resource pool and the virtual machines remain in the host’s original resource pool
hierarchy. If you do not specify this parameter, the virtual machines are moved to the cluster’s
root resource pool and the original hierarchy is discarded.

Moving Hosts Into a Cluster


You use one of two operations to move an existing host into a cluster:
• MoveHostInto_Task – to move a single host.
• MoveInto_Task – to move a set of hosts.

Conditions for Moving Existing Hosts


An existing host can be moved into a cluster only under the following conditions:
• The host is part of the same datacenter.
• The host is part of a ClusterComputeResource and is in maintenance mode, or the host is part
of a ComputeResource.

Moving a Single Host Into a Cluster


Subject to the Conditions for Moving Existing Hosts on page 101, you use the MoveHostInto_Task
operation to move a single host. The MoveHostInto_Task operation takes the following
parameters:
• ClusterComputeResource managed object reference – The cluster compute resource with
which you want to associate the set of hosts.
• host – A HostSystem managed object reference that you want to move into the cluster.

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.

Moving a Set of Hosts Into a Cluster


Subject to the Conditions for Moving Existing Hosts on page 101, you use the MoveInto_Task
operation to move a set of hosts. The MoveInto_Task operation takes the following parameters:
• ClusterComputeResource managed object reference – The cluster compute resource with
which you want to associate the set of hosts.
• host – A set of HostSystem managed object references that you want to move into the
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.

Moving Existing Hosts into a Folder


You use the MoveIntoFolder_Task operation to move one or more existing, clustered hosts into a
folder. Each host being moved becomes a standalone host in the target folder.
To move a host into a folder, the HostSystem must meet the following conditions:
• The host must be part of a ClusterComputeResource.
• The host must be in maintenance mode.
For each host being moved, the MoveIntoFolder_Task operation creates a ComputeResource with
a single root resource pool and a stand-alone host. The name of the standalone host is the DNS or
IP address of the host. This operation moves the (physical) host resources out of a cluster. It does
not move or change the ResourcePool configuration that is part of the ClusterComputeResource
with which the host was associated.

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.

Removing Hosts from a Cluster


To remove hosts from a cluster, you can use one of the following operations:
• MoveHostInto_Task or MoveInto_Task – To remove a host from one cluster and move the
host into another. See Moving Hosts Into a Cluster on page 101.
• MoveIntoFolder_Task – To remove a host from a cluster and make it a standalone host. See
Moving Existing Hosts into a Folder on page 102.
• Destroy_Task – Removes the host from inventory. Note that in order to invoke this operation
on a HostSystem managed object, you must have the
Host.Inventory.RemoveHostFromCluster privilege on the HostSystem as well as on the parent
Folder.

Connecting and Disconnecting Hosts


You can add a host in either a connected or a disconnected state. When you add the host, using
either of the operations described in Managing Hosts on page 100, you determine its state by
setting a boolean property, either asConnected (AddHost_Task) or addConnected
(AddStandaloneHost_Task). When either of these booleans is set to true, the host is added in the
Connected state.
When a host is in the connected state, you can disconnect the host with the DisconnectHost_Task
operation. This operation takes as its only parameter the reference to the HostSystem managed
object from which you want to disconnect.

Reconnecting to a Disconnected Host


When a host is in the Disconnected state, you use the Reconnect_Task operation to reconnect the
host to VirtualCenter. The Reconnect_Task operation takes one mandatory parameter, the
managed object reference to the HostSystem that will be reconnected. An optional parameter,
cnxSpec, is a HostConnectSpec data object. This object contains the parameters to use (including
user name and password) when reconnecting to the host. If this parameter is not specified, the
default connection parameters (defined during the AddHost_Task operation) are used.
The Reconnect_Task operation reinstalls agents and reconfigures the host, if it has gotten out of
date with VirtualCenter. The reconnection process goes through many of the same steps as
AddHost_Task: ensuring the correct set of licenses for the number of CPUs on the host, ensuring

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.

Recommending Hosts for Virtual Machines


When you associate a virtual machine with one of the hosts in a cluster, you can determine which
hosts would be most appropriate for the association. The RecommendHostsForVm operation
considers resource usage on the hosts in a cluster.
Note: This operation is valid only for DRS-enabled clusters.
The operation takes two parameters::
• ClusterComputeResource managed object reference – This is the cluster that contains the
potential target hosts for the association.
• VirtualMachine managed object reference – The virtual machine you want to associate with
one of the hosts in the cluster.

Achieving A More Efficient Resource Usage for Clusters (DRS Only)


You can achieve a more efficent resource usage in a cluster by invoking the
ApplyRecommendation operation.
When a cluster is DRS-enabled, the VMware DRS service determines optimum resource usage and
prepares a list of recommendations in the background. The DRS service stores them in the
drsRecommendation property of the ClusterComputerResource managed object. To view these
recommendations, you can create a PropertyCollector and retrieve the contents of the
ClusterComputeResource managed object. See Getting Information and Updates on page 123.
To apply a recommendation, you invoke the ApplyRecommendation operation with a reference to
the specific ClusterComputeResource managed object and a key property. The key property is a
string representing the recommendation you want to apply.

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.

Shutting Down or Restarting a Host


The ShutdownHost_Task operation lets you shutdown a host. If the command is successful, the
host has been shut down. The client never receives an indicator of success in the returned task if
connected directly to the host.
Not all hosts can support this operation. The HostSystem managed object includes a capability
property. This HostSpec data object type includes a shutdownSupported boolean property. When
set to false, the ShutdownHost_Task operation is not supported.
Note: In the case of VirtualCenter, the shutdown operation issues a shutdown request to the host
and returns immediately. If the command is successful, it does not mean that the host was
shutdown. It means that the request was issued successfully. The client can check whether the
shutdown was successful by monitoring the connect status of the host.

105
VMware Infrastructure SDK Programming Guide

Configuring Networks for a Host


In the VMware Infrastructure SDK, you perform a number of functions when you configure
networks.
• Configure the service console when you install ESX Server or VirtualCenter to enable remote
management. See Configuring the Service Console TCP/IP on page 106.
• Configure TCP/IP on the VMkernel to enable migration, software iSCSI, and Network Attached
Storage (NAS). See Configuring TCP/IP on the VMkernel on page 106.
• Update the network information on the host after you have configured. See Updating the
Host’s Network Configuration on page 109.

Configuring the Service Console TCP/IP


You configure the service console TCP/IP during ESX Server or VirtualCenter installation. For
information about configuring the service console, see the appropriate installation guide. You can
reconfigure the service console TCP/IP using one of the following operations:
• UpdateServiceConsoleVirtualNic
• AddServiceConsoleVirtualNic
• RemoveServiceConsoleVirtualNic
• RestartServiceConsoleVNic
For more information, see Updating the Host’s Network Configuration on page 109.

Configuring TCP/IP on the VMkernel


To enable migration, software iSCSI, or NAS, at least one of each of the following must be
configured on the VMkernel: a port group (with virtual switch), a virtual Network Interface Card
(NIC) associated with the port group, and a gateway.
To configure these items, you perform one or more of the following steps:
1. Determine the current configuration.
This tells you how much, if any, of the information is already configured., and which of the
following steps you need to perform. You must have at least one port group (with virtual
switch), one virtual NIC associated with the port group, and one gateway. However, you can
configure as many as you want, depending on the network topology you want. See
Determining the Host’s Network Configuration on page 107.
2. Use the AddVirtualSwitch operation to add one or more virtual switches.
See Adding a Virtual Switch on page 107.

www.vmware.com
106
C H A P T E R 5 Managing Inventory

3. Use the AddPortGroup operation to add a port group to a virtual switch.


See Adding a Port Group to a vSwitch on page 108.
4. If necessary, add a Virtual Network Interface Card (VNIC).
If you are configuring for software iSCSI or NAS, use AddVirtualNic. See Adding a Virtual NIC
(VNIC) on page 108.
5. If you are enabling VMotion, select a VNIC.
Use the SelectVNic operation to select the VNIC. This operation takes the following
parameters:
• HostVmotionSystem managed object reference – Obtained by using a property collector
for configManager.vMotionSystem of the HostSystem managed object. See Getting
Property Information on page 124.
• device – The name that uniquely identifies the VirtualNic.
If necessary, you can add a virtual NIC using AddVNic (see Adding a Virtual NIC (VNIC) on
page 108), then use SelectVNic to select it.
6. Use UpdateIpRouteConfig to configure a gateway.

Determining the Host’s Network Configuration


You can use a property collector to find information about the host’s network configuration.
The HostNetworkSystem managed object has a number of properties that give you a view into the
configuration. For example, the networkInfo property describes everything from the array of
physical and virtual NICs to DNS configuration information. Using a property collector (as
described in Getting Property Information on page 124) lets you retrieve the property information
belonging to this managed object.

Adding a Virtual Switch


The AddVirtualSwitch operation lets you add a virtual switch. This operation takes the following
parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem to
which you are adding the virtual switch. See Obtaining the HostNetworkSystem Managed
Object Reference on page 111.
• vSwitchName – The name of the virtual switch.
• spec – (optional) The HostVirtualSwitchSpec data object. This object contains the following
properties:
• bridge – The HostVirtualSwitchBridge data object. This object specifies how physical
network adapters can be bridged to a virtual switch. For the current release, only bond

107
VMware Infrastructure SDK Programming Guide

bridge is supported. A bond bridge provides network adapter teaming capabilities


through the use of a list of physical devices and, optionally, a beacon probe to test
connectivity with physical adapters.
• numPorts – The number of ports that this virtual switch is configured to use.
• policy – The HostNetworkPolicy data object. See Defining the Host Network Policy on
page 110.

Adding a Port Group to a vSwitch


After you have the virtual switches you want (Adding a Virtual Switch on page 107), you use the
AddPortGroup operation to add a port group to a switch. This operation takes the following
parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem to
which you are adding the port group. See Obtaining the HostNetworkSystem Managed
Object Reference on page 111.
• portgrp – The HostPortGroupSpec data object. This object has the following properties:
• name – The name of the port group. If you want to create a network of hosts, specify the
same name as the port group of another host in the Datacenter.
• policy – The HostNetworkPolicy data object. See Defining the Host Network Policy on
page 110.
• vlanId – The VLAN ID for ports using this port group. Although this parameter is required,
you can set its value to zero to indicate the port group is not associated with a VLAN. A
value of 4095 specifies a trunk port connection.
• switchName – The identifier of the switch on which this port group is located.

Adding a Virtual NIC (VNIC)


You use the AddVirtualNic operation to add the VNIC. This operation takes the following
parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem to
which you are adding the VNIC. See Obtaining the HostNetworkSystem Managed Object
Reference on page 111.
• 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.
To add a port group, see Adding a Port Group to a vSwitch on page 108.

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.

Updating the Host’s Network Configuration


You can either update the configuration in batch, or you can update individuals parts of the
configuration.

Updating the Network Configuration in Batch


You can use the UpdateNetworkConfig operation to change the network configuration in batch
for the host. This operation takes the following parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem
managed object. See Obtaining the HostNetworkSystem Managed Object Reference on
page 111.
• config – A HostNetworkConfig data object. This object specifies the network configuration
for the host. The information includes the physical and virtual NIC configurations, the port
switch configurations, the port group configurations, the DNS configuration, and the
gateway information.
• changemode – The value of this string can be either “modify” or “replace”. In “modify” mode,
only the changes that are specified are made. In “replace” mode, any values present in the
previous configuration but not in the update specification become unspecified.

Updating the Service Console VNIC


After installation, to reconfigure the Console TCP/IP configuration, you use the
UpdateServiceConsoleVirtualNic operation. This operation takes the following parameters:
• HostNetworkSystem managed object reference – A reference to the network to which you
are updating the VNIC. See Obtaining the HostNetworkSystem Managed Object Reference
on page 111.
• device – The name of the service console VNIC you are updating.
• 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 (Media Access Control)
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.

Restarting the Service Console VNIC


If necessary, you can restart the service console VNIC by invoking RestartServiceConsoleVirtualNic.
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 restarting.

Updating the TCP/IP Configuration on the VMkernel


You can use the UpdateVirtualNic operation to update the configuration. This operation takes the
following parameters:
• HostNetworkSystem managed object reference – A reference to the HostNetworkSystem
that contains the TCP/IP configuration. See Obtaining the HostNetworkSystem Managed
Object Reference on page 111.
• device – The name that uniquely identifies the VirtualNic.
• 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.

Defining the Host Network Policy


When you configure host networks (see Configuring Networks for a Host on page 106), you can
define specific policies for the network. The HostNetworkPolicy data object type describes
network policies for both virtual switches and port groups. The policy settings on the port group

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.

Obtaining the HostNetworkSystem Managed Object Reference


The operations you use to configure and maintain networks on the host require a
HostNetworkSystem managed object reference. The easiest way to obtain this managed object
reference is to use a property collector on the HostSystem managed entity that is referenced by
your operation. The HostSystem managed object has a property called configManager which
comprises the configuration for the host, including the references to the HostNetworkSystem
managed objects belonging to the HostSystem. For more information on using a property
collector, see Getting Property Information on page 124.

111
VMware Infrastructure SDK Programming Guide

Renaming Managed Entities


To rename a ComputeResource, Datacenter, Folder, HostSystem, ResourcePool, or VirtualMachine,
you use the Rename_Task operation. The operation takes the following parameters:
• ManagedEntity managed object reference – A reference to the managed entity whose name
you are changing.
• newName – The new name. You must escape any / (slash), \ (backslash), character used in
this name element. Similarly, you must escape any % (percent) character, unless the character
is used to start an escape sequence. A slash is escaped as %2F or %2f. A backslash is escaped
as %5C or %5c, and a percent is escaped as %25.

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.

Creating an NAS-Backed Datastore


The CreateNasDatastore operation lets you create a datastore backed by an NAS server. The
operation takes the following parameters:
• A HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• name – The name you want for the datastore. The name must be unique within the
datacenter where the HostSystem is located.
• spec – A HostNasVolumeSpec data object. This data object comprises the following
properties:
• localPath – The path on the host where the file system is mounted. For ESX Server, this path
is always off the /vmfs/volumes subdirectory.
• remoteHost – The host that runs the NFS server.
• remotePath – The remotePath of the NFS mount point.
This operation returns a Datastore managed object reference.

Creating a VMFS-Backed Datastore


The CreateVmfsDatastore operation lets you create a VMFS-backed datastore. Before you invoke
this operation, you can invoke the QueryVmfsDatastoreCreateOptions operation to query your
options for creating the datastore. See Determining Options for Creating a New VMFS Datastore on
page 116.
This operation takes the following parameters:
• HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• name – The name you want for the datastore. The name must be unique within the
datacenter where the HostSystem is located.
• spec – See Configuring a VMFS-Backed Datastore on page 115.
This operation returns a Datastore managed object reference.

Extending a VMFS Datastore Across Multiple Disks


The ExtendVmfsDatastore operation lets you extend an existing VMFS datastore across multiple
disks. The operation takes the following parameters:

113
VMware Infrastructure SDK Programming Guide

• HostDatastoreSystem managed object reference – See Obtaining Managed Object


References for Storage Operations on page 121.
• Datastore managed object reference – A reference to the VMFS datastore that you want to
extend. You can obtain this reference in a number of ways. See Getting Property Information
on page 124 for more information about creating a PropertyFilterSpec.
• spec – A HostVmfsDatastoreExtendSpec data object. This data object comprises two
properties:
• extent – A HostScsiDiskPartition data object. This object identifies the disk and the
partition for the extent. See Defining the HostScsiDiskPartition on page 116.
• partition – A HostDiskPartitionInfoSpecification data object.

Determining Options for Extending a VMFS-Backed Datastore


Before you extend a VMFS-backed datastore (Extending a VMFS Datastore Across Multiple Disks on
page 113), you can invoke the QueryVmfsDatastoreExtendOptions operation to determine the
options. The operation takes the following parameters:
• HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• Datastore managed object reference – You can obtain this reference with a property
collector. See Getting Property Information on page 124.
• devName – The SCSI disk device name to which you want to extend the datastore.
This operation returns an array of HostVmfsDatastoreOption data objects.

Searching for Available Disks for Extending VMFS Datastores


The QueryAvailableDisksForVmfs operation returns a list of disks that can be used to contain VMFS
datastore extents. The operation takes the following parameters:
• HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• Datastore managed object reference – If you supply this optional parameter, the operation
returns a list of disks that can be used to contain extents for a VMFS datastore identified by
the supplied parameter. Otherwise, the operation retrieves disks that can be used to contain
new VMFS datastores.
This operation returns an array of HostScsiDisk data objects.
This operation filters out disks that are currently in use by an existing VMFS unless the VMFS using
the disk is one being extended. It will also filter out management LUNs and disks that are
referenced by RDMs. These disk LUNs are also unsuited for use by a VMFS.

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.

Removing and Deleting Datastores


You can either remove an association between a datastore and a host, or you can delete the
datastore.
The RemoveDatastore operation removes an association between the datastore and a host. The
operation takes the following parameters:
• HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• Datastore managed object reference – The reference to the datastore that you want to
remove from the host. There are a number of ways to obtain the managed object reference.
See Obtaining a Managed Object Reference on page 32.
The DestroyDatastore operation removes a datastore from the system. A datastore can be removed
only if it is not currently used by any host or virtual machine. This operation takes the Datastore
managed object reference for the datastore that you want to destroy.

Configuring a VMFS-Backed Datastore


To configure a VMFS-backed datastore, you use a HostVmfsDatastoreCreateSpec data object
(extends HostVmfsDatastoreSpec). You can supply a diskId that identifies the disk ID of the SCSI
disk on which the VMFS datastore is located.

Configuring Extended Datastores


You can extend a datastore across multiple disks by using the ExtendVmfsDatastore operation (see
Extending a VMFS Datastore Across Multiple Disks on page 113). During configuration, as an
option, you can extend the datastore across multiple partitions within the disk with which the
datastore is associated.
To extend during configuration, you use the extent property of the HostVmfsDatastoreCreateSpec.
The extent property is a HostScsiDiskPartition data object., an array of extents to append to VMFS.
See Defining the HostScsiDiskPartition on page 116 for an explanation of this data object.

Specifying a Partition Table


The partition property of the HostVmfsDatastoreCreateSpec lets you describe the disk partition
table specification used to configure the partitions on a disk. To do this, you use the
HostDiskPartitionInfoSpecification data object. See Defining the HostDiskPartitionInfoSpecification
on page 117.

115
VMware Infrastructure SDK Programming Guide

Specifying the VMFS Datastore


The vmfs property of the HostVmfsDatastoreCreateSpec lets you provide VMFS creation
specification information. This HostVmfsSpec data object comprises the following properties:
• blockSizeMb – The block size of VMFS in megabytes (MB). Determines the maximum file size.
If this optional property is not set, the maximum file size defaults to the maximum file size for
the platform. In VMFS2, the valid block sizes in units of megabytes are: 1, 2, 4, 8, 16, 32, 64, 128,
256. In VMFS3, the only valid block size is 1MB.
• extent – A HostScsiDiskPartition data object. The head extent of VMFS. The head extent
identifies the VMFS. However, the head extent should not be used to identify the VMFS across
host reboots. The actual identifier is specified in "vmhbaI:T:L" format which is not guaranteed
to be stable across reboots. Define a volume name that is unique to the host and use it to
refer to the VMFS. Alternatively, the immutable UUID of the VMFS can be used after it is
created. See Configuring Extended Datastores on page 115 for an explanation of the
properties of the HostScsiDiskPartition data object.
• lockMode – The lock mode for the datastore. This can be either cluster or distributed. If the
value is cluster, because cluster software ensures proper synchronization, turn off VMFS
distributed locking.
• majorVersion – Major version number of VMFS. This can be changed if the VMFS is upgraded,
but this is an irreversable change.
• volumeName – The volume name of VMFS.

Determining Options for Creating a New VMFS Datastore


Before you create an VMFS datastore (Creating a VMFS-Backed Datastore on page 113), you can
invoke the QueryVmfsDatastoreCreateOptions operation. This operation determines your options
for creating a VMFS datastore on a disk from SCSI disk device name that you supply. This operation
takes the following parameters.
• HostDatastoreSystem managed object reference – See Obtaining Managed Object
References for Storage Operations on page 121.
• devName – The SCSI disk device name.
This operation returns an array of HostVmfsDatastoreOption data objects.

Defining the HostScsiDiskPartition


The HostScsiDiskPartition data object lets you define extents when you create or extend a VMFS
datastore. This data object comprises the following properties:
• id – The ID of the SCSI disk on which a VMware File System (VMFS) extent resides. This ID field
should match the ID field of the ScsiDisk.

www.vmware.com
116
C H A P T E R 5 Managing Inventory

• partition – The partition number of the partition on the ScsiDisk.

Defining the HostDiskPartitionInfoSpecification


When you create or extend a VMFS datastore, this object represents the fundamental data needed
to specify a partition table:
• chs – The Disk dimensions expressed as cylinder, head, sector (CHS) coordinates. The
HostDiskDimensionsChs data object comprises three properties specifying the number of
cylinders, the number of heads per cylinder, and the number of sectors per head.
• partition – HostDiskPartitionInfoPartition data object. The information about a single disk
partition.
• totalSectors – Disk dimensions expressed in total number of 512-byte sectors.

Configuring iSCSI Initiators


To configure iSCSI:
1. Determine the Host Bus Adapter you want to configure.
2. Determine the HBA ID.
3. Determine the iSCSI Host Bus Adapter’s (HBA) capabilities.
4. Configure the initiator.
• For a hardware initiator, configure the IP address.
• For a software initiator, enable the software initiator.
5. Configure the iSCSI name and alias.
6. Configure Target Discovery.
7. Set the authentication information. (Skip this step if you are not using CHAP.)
8. Configure access to the targets.
9. Issue a rescan on the HBAs.
Each step is explained in the following sections.

Determining the Host Bus Adapter


You can obtain this information by creating a property collector acting on the HostSystem
managed object that contains the HBA.
Note: You can use a number of operations to obtain the HostSystem managed object reference.
See Finding Entities Using a Property Value on page 135.
The property collector should select for the config.storageDevice.hostBusAdapter property of the
HostSystem. The hostBusAdapter property is an array of the HBAs available on the host. You can

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.

Determining the HBA ID String


Most of the operations that you use to configure iSCSI initiators require the string that identifies the
adapter you are configuring for iSCSI.
After you have determined the HBA you want to configure (Determining the Host Bus Adapter on
page 117), the HBA contains a key property that uniquely identifies the HBA. This key property is
the string you use to identify the adapter in the operation.

Determining the iSCSI Host Bus Adapter’s Capabilities


You can use several properties of the HostInternetScsiHba data object (extends
HostHostBusAdapter) to determine the capabilities of the HBA.
• authenticationCapabilities – The HostInternetScsiHbaAuthenticationCapabilities data object.
This object comprises boolean properties, each determining whether or not the four
authentication types are settable. Currently, only CHAP authentication is supported, so the
CHAP boolean is set to true.
• discoveryCapabilities – The HostInternetScsiHbaDiscoveryCapabilities data object. This
object comprises boolean properties that specify whether or not changing discovery targets
is supported. Currently, only send and static discovery targets are configurable.
• ipCapabilities – The HostInternetScsiHbaIPCapabilities data object. This object comprises
boolean properties that determine whether or not IP properties are configurable.
Each property tells you the steps you need to follow in this section.

Configuring the IP Address (Hardware Initiator)


If you are using a hardware initiator, you must configure the IP address information. To do this, you
invoke the UpdateInternetScsiIpProperties operation. This operation takes the following
parameters:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• 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.
• ipProperties – The HostInternetScsiHbaIPProperties data object. With this object, you provide
the IP information including a dhcpConfigurationEnabled boolean property that determines
whether or not the HBA uses Dynamic Host Configuration Protocol (DHCP) to fetch the IP
address. In addition, the information can include the IP address, the primary and alternate

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.

Enabling the Software Initiator (Software Initiator)


The first step is to enable VMotion and IP storage. See Configuring TCP/IP on the VMkernel on
page 106.
By default, the software initiator is disabled in the ESX Server and reflected in the VMware
Infrastructure SDK. After you configure the VMkernel, you must enable the software initiator. To
enable a software initiator, you must invoke the UpdateSoftwareInternetScsiEnabled operation.
This operation takes two parameters:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• enabled – Set this boolean to TRUE to enable the software initiator.

Configuring the iSCSI Name and Alias


For both hardware and software initiators, you must specify an iSCSI name. A default name is
already configured, but you can change the name using the UpdateInternetScsiName operation.
The iSCSI alias is optional. You can specify the alias using the UpdateInternetScsiAlias operation.
For both operations, the first two parameters are:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• 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.
For the third parameter, the UpdateInternetScsiName operation takes the iSCSI name, while the
UpdateInternetScsiAlias operation takes the iSCSI alias.
Note: The iSCSI name must be in a specific format, as described in the VMware Infrastructure
Server Configuration Guide. The iSCSI alias is free-form text.

Setting the Authentication Information


If you are using Challenge-Handshake Authentication Protocol (CHAP), you configure
authentication using the UpdateInternetScsiAuthenticationProperties operation. This operation
takes the following parameters:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.

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.

Configuring Target Discovery


Before you can configure targets, you configure how the targets are discovered using the
UpdateInternetScsiDiscoveryProperties operation. Typically, you can skip this step because send
and static targets discovery are the only supported target discovery and are enabled by default.
This operation takes the following parameters:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• iScsiHbaDevice – The string that identifies the Host Bus Adapter. If you have not identified
this string, see Determining the HBA ID String on page 118.
• discoveryProperties – The HostInternetScsiHbaDiscoveryProperties data object. This object
contains four boolean properties that must be set:
• sendTargetsDiscoveryEnabled – Currently, this property defaults to TRUE.
• staticTargetDiscoveryEnabled – Currently, this property defaults to TRUE.
• slpDiscoveryEnabled – Must be set to FALSE. The VMware Infrastructure SDK does not
support SLP for the current release.
• iSnsDiscoveryEnabled – Must be set to FALSE. The VMware Infrastructure SDK does not
support iSNS for the current release.

Configuring Access to Targets


You configure send or static targets depending on the setting of the sendTargetDiscoveryEnabled
and staticTargetDiscoveryEnabled properties in the HostInternetScsiHbaDiscoveryProperties data
object.
If the sendTargetDiscoveryEnabled property is set to true, add the send targets using the
AddInternetScsiSendTargets operation. This operation takes the following arguments:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• 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.

www.vmware.com
120
C H A P T E R 5 Managing Inventory

• targets – An array of HostInternetScsiHbaSendTarget data objects, each object consisting of


the IP address or hostname of the storage device and the TCP port of the storage device. If
the port is not specified, the standard default of 3260 is used.
If the staticTargetDiscoveryEnabled property is set to true, add the static targets using the
AddInternetScsiStaticTargets operation. This operation takes the following parameters:
• HostStorageSystem managed object reference – See Obtaining Managed Object References
for Storage Operations on page 121.
• 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.
• targets – An array of HostInternetScsiHbaStaticTarget data objects, each object consisting of
the IP address or hostname of the storage device, the iSCSI name of the storage device, and
the TCP port of the storage device. If the port is not specified, the standard default of 3260 is
used.

Issuing a Rescan on the HBAs


After you complete the steps described in the previous sections, the last step in configuring the
iSCSI HBAs is to issue a rescan on the HBAs. This enables the HBAs to discover the new storage
devices. You can either issue a rescan for a single HBA using the RescanHba operation with the
HBA ID as a parameter or issue a rescan on all HBAs using RescanAllHba.

Obtaining Managed Object References for Storage Operations


The operations you use to manage storage frequently require either a HostDatastoreSystem or
HostStorageSystem managed object reference. Each of these is the value of a property of the
HostConfigManager data object: datastoreSystem (for the HostDatastoreSystem) and
storageSystem for the HostStorageSystem).
To obtain these managed object references, you can create a PropertyFilterSpec that filters for
HostSystem managed objects and the appropriate property. Getting Property Information on
page 124 describes how to create a PropertyFilterSpec. The PropertySpec data object (the object
that defines the objects being filtered) for a PropertyFilterSpec that filters for the
HostDatastoreSystem managed object reference looks like this:
PropertySpec pspec = new PropertySpec();
pspec.setType("HostSystem");
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {"configManager.datastoreSystem"});

121
VMware Infrastructure SDK Programming Guide

A PropertySpec that filters for the HostStorageSystem looks like this:


PropertySpec pspec = new PropertySpec();
pspec.setType("HostSystem");
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {"configManager.storageSystem"});

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

Getting Property Information


To collect property information from one or more managed objects, you create a
PropertyFilterSpec. After you define the PropertyFilterSpec, you use the RetrieveProperties
operation to retrieve the information. There are two uses for this information:
• Retrieving the current values of the properties.
• Getting updates on the properties. For more information, see Getting Updates on Properties
on page 140.
This section describes the parts of a PropertyFilterSpec and contains code sample snippets
illustrating the concepts.

Defining the Information Retrieval Process


To define the information you want to retrieve and the retrieval process, you create one or more
PropertyFilterSpec data objects. You use these as the specSet parameter described in Retrieving
Property Information on page 133. This data object contains two properties:
• propSet – A set of PropertySpec data objects. A set of specifications that defines the data to
be retrieved: the references to the managed objects you want to retrieve and the properties
of the selected managed objects. See Defining the Properties with a PropertySpec on
page 124.
• objectSet – A set of ObjectSpec data objects. This array defines the process of collecting the
information specified by the associated propSet property. See Defining the Property
Collection with an ObjectSpec on page 125.

Defining the Properties with a PropertySpec


The PropSet property of the PropertyFilterSpec object comprises a list of PropertySpec objects.
Each object identifies properties to be returned from a designated managed object. The
PropertySpec data object comprises the following properties:
• type – Identifies the type of managed object being collected. The valid values are listed in the
description of the PropertySpec in the VMware Infrastructure SDK Reference Guide.
• all – If set to true, this boolean property specifies that you want to retrieve all the properties of
the managed object identified by the type property.
• pathSet – A list of comma-separated property names identifiying specific properties of the
managed object. Setting this property is optional. You can specify the properties you want
from the managed object in one of three ways:
• If you want all the properties of the managed object, set the “all” property of the
PropertySpec object to true and do not set the pathSet property.

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.

Defining the Property Collection with an ObjectSpec


The ObjectSet property of the PropertyFilterSpec object comprises a set of ObjectSpec data
objects. Each ObjectSpec data object contains the following properties:
• obj – This property defines the managed object reference at which collection begins.
• skip – This boolean property specifies whether or not the object defined by the obj property
will be selected for property retrieval. When set to true, the properties of the obj property are
not read, even if its type is specified in the PropertySpec.
• selectSet – This optional property comprises one or more SelectionSpec data objects. Each
SelectionSpec object comprises a list of TraversalSpec objects. This causes the
PropertyCollector to traverse through managed objects that are properties of the managed

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.

Traversing Managed Object Properties with a TraversalSpec


As described in Defining a Simple PropertyFilterSpec (No Traversal) on page 127, the simplest use
of an ObjectSpec omits the skip and selectSet properties. In this case, the collection process selects
only properties from the single starting object. The program collects property information from no
additional objects.
Sometimes, however, you are collecting properties of managed objects that are one or more levels
below the starting managed object. For example, several operations return a Task managed object
reference. Suppose you want information about recent tasks. The TaskManager managed object
has a property called recentTasks, an array of Task managed object references, each of which
contains an info property (a TaskInfo data object) with the information you want.
To traverse additional managed objects, you use the selectSet property with the ObjectSpec data
object. As described earlier, the selectSet property comprises an array of SelectionSpec data
objects. The SelectionSpec data object is extended by the TraversalSpec data object.
A TraversalSpec data object comprises the following properties:
• type – The type of object to which the TraversalSpec applies. The program checks whether
the current managed object is of this type. The valid type values are listed in the description
of the TraversalSpec in the VMware Infrastructure SDK Reference Guide.
• path – The name of a property containing a reference to another object. The traversal
proceeds to the other object by this reference.
• skip – A boolean property that determines whether the referenced object should be
included in the set of objects monitored by the property collector or used as a step in
traversing a tree of objects. This field is relevant only if the PropertyFilterSpec contains a

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.

Defining a Simple PropertyFilterSpec (No Traversal)


In the following sample code snippet, you have a specific Task managed object reference as the
starting object for the collection. You want to find specific information about this task.
/* The PropertySpec defines the type of managed objects
/ for which you are looking and the property of those
/ managed objects, in this case info.state.
*/
PropertySpec pSpec = new PropertySpec();
pSpec.setAll(false);
pSpec.setType(“Task”);
pSpec.setPathSet(new String[] {“info.state”});

/* The ObjectSpec defines the starting point for the


/ collection, in this case the specific Task managed
/ object reference whose information you want. Notice
/ that the skip property is set to false. This means
/ that the program checks the starting object to see if
/ it is the managed object type defined in the PropertySpec.
/ Because the code contains no selectSet property, this is the only object
/ that is checked.
*/
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(taskMoRef);

127
VMware Infrastructure SDK Programming Guide

// Constructing the PropertyFilterSpec


PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
pfSpec.setPropSet(new PropertySpec[] { pSpec });

// Retrieve the results of the collection.


// pCollector is a PropertyCollector managed object reference
// obtained from the ServiceContent data object with an accessor
// method. See Obtaining a Managed Object Reference on page 32.
ObjectContent[] objs = vimService.retrieveProperties(pCollector,
new PropertyFilterSpec[] { pfSpec });
if (objs == null)
return null;
DynamicProperty[] dProps = objs[0].propSet;
if (dProps == null)
return null;
return dProps[0].val;

Defining a PropertyFilterSpec with TraversalSpec Objects


As described in Traversing Managed Object Properties with a TraversalSpec on page 126, to collect
managed object properties, you need to traverse levels of managed object properties. This section
contains examples of PropertyFilterSpecs that use TraversalSpec objects. The examples progress
from the simplest, using only one TraversalSpec object, to the more complex.

Defining with a Single TraversalSpec Object


Sometimes you are interested only in the immediate children of a managed object for which you
already have a reference. For this, you need only a single TraversalSpec object.
For example, suppose you want to monitor the free space for all datastores within a known
datacenter. The Datacenter managed object has a property called datastore, which is an array of
references to the Datastore managed objects associated with the datacenter. Each Datastore
managed object has a summary property (DatastoreSummary data object). The
DatastoreSummary object has the freeSpace property.
The following sample code snippet illustrates this example:
public PropertyFilterSpec[] createPfSpecFreespace(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.
*/

www.vmware.com
128
C H A P T E R 6 Getting Information and Updates

PropertySpec[] pspec = new PropertySpec();


pspec.setType("Datastore");
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {"summary.freeSpace"});

/*
/ 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});

// Now define the PropertyFilterSpec.


PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] {pspec});
pfSpec.setObjectSet(new ObjectSpec[] {ospec});

// Now return the PropertyFilterSpec for use.


return new PropertyFilterSpec[]{pfSpec};
}

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.
*/

ManagedObjectReference pCollectorRef = _sic.getPropertyCollector;


ObjectContent[] objs = _service.retrieveProperties(pCollectorRef,
new PropertyFilterSpec[] {pfSpec});
if (objs == null)
return null;
DynamicProperty[] dProps = objs[0].propSet;
if (dProps == null)
return null;
return dProps[0].val;

Defining with a Fixed Number of Traversals


If you know the structure of the hierarchy you want to traverse, you can extend the traversal to as
many levels as needed, by nesting TraversalSpec objects. As long as the number of traversal steps is
fixed, you do not need recursion. Extend each TraversalSpec array with another level of
TraversalSpec arrays.
For example, suppose you want to collect the UUIDs of all the virtual machines in a Datacenter in
the following hierarchy.

www.vmware.com
130
C H A P T E R 6 Getting Information and Updates

rootFolder

Folder Folder Folder

Datacenter

vmFolder

VirtualMachine VirtualMachine VirtualMachine VirtualMachine

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

TraversalSpec dcenterTSpec = new TraversalSpec();


dcenterTSpec.setType("Datacenter");
dcenterTSpec.setPath("vmFolder");
dcenterTSpec.setSkip(Boolean.TRUE);
dcenterTSpec.setSelectSet(new SelectionSpec[]{folderTSpec});

/*
/ 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

ospec.setSelectSet(new SelectionSpec[] {dcenterTSpec});

// Now define the PropertyFilterSpec.


PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] {pspec});
pfSpec.setObjectSet(new ObjectSpec[] {ospec});

// Now return the PropertyFilterSpec for use.


return new PropertyFilterSpec[]{pfSpec};
}

Defining TraversalSpec Objects with Recursion


If you need to traverse a tree to an unknown depth, you can use recursive TraversalSpec objects to
follow a repeating traversal pattern. Often you can do this with two levels of selectSet arrays linked
to your ObjectSpec. The first level, ObjectSpec.selectSet[], contains a list of TraversalSpec objects
that is general enough to apply to the starting managed object and to any subsequent traversal
steps. The second level of selectSet arrays contains a list of SelectionSpecs that tell the property
collector which TraversalSpec object to use for the next step in the traversal.
The first level of selectSet objects contains named TraversalSpecs, with one TraversalSpec for each
type of object that you could encounter at any stage of the traversal. The names allow the
TraversalSpecs to be referenced at the second level. When control is transferred to a named
TraversalSpec, that is called (in this context) recursion.
For a code sample of recursion, see Defining a PropertyFilterSpec with Recursion on page 210.

Retrieving Property Information


You retrieve information by invoking the RetrieveProperties operation. This operation takes two
parameters:
• PropertyCollector managed object reference – The PropertyCollector managed object is a
property of the ServiceContent data object. You can obtain a reference to this managed
object using an accessor method as specified in Obtaining a Managed Object Reference on
page 32. The following code snippet illustrates this:
ManagedObjectReference sir = new ManagedObjectReference();
sir.setType("ServiceInstance");
sir.setValue("ServiceInstance");

// Call retrieveServiceContent()
ServiceContent sic = vimService.retrieveServiceContent(sir);

ManagedObjectReference pcr = sic.getPropertyCollector();

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

Finding Entities Using a Property Value


As described in the Getting Property Information on page 124, you can use a PropertyCollector to
read property values for managed objects. In some situations, however, you might have a specific
value of a property and want to find the managed object referenced by the property value. In this
situation, you can invokes one of the SearchIndex operations. These operations enable a client to
efficiently query inventory for a specific managed entity based on the values of certain attributes
such as UUID.
Note: These operations return a single managed entity. If multiple entities are found that match
the parameter, only the first managed entity found is returned.

Differences Between the SearchIndex API and the PropertyCollector


A PropertyCollector reads property values from managed objects, while the SearchIndex API finds
a managed object given a value for one of its properties. Other differences are:
• The results returned by the PropertyCollector are exhaustive for the given criteria. In contrast,
the SearchIndex API returns the first match it finds, so if the search criteria was ambiguous,
only one managed object would be retrieved.
• The property collector is generic and will work with any managed objects and properties. In
contrast, the SearchIndex API works for a specific set of managed object types and specific
set of properties.
• The SearchIndex API is convenient to use because is specific with respect to the managed
objets and properties with which it works.
You can build your own SeachIndex API functionality on top of the property collector functionality.
You can use the property collector to read a collection of objects and properties and then search
the resulting list to find the object whose property value matches the target property value. Doing
so, however, would require transmitting a lot of data over the network just so it can be thrown
away after it has been found. To avoid burdening the communication channel unnecessarily, the
operations in this API anticipate the common search operations that the user would use and let
the server do the work.

Finding a ManagedEntity by InventoryPath


The FindByInventoryPath operation lets you find any ManagedEntity based on its location in the
inventory. The parameters are:
• A SearchIndex 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.

135
VMware Infrastructure SDK Programming Guide

• inventoryPath – The inventory path to the ManagedEntity. The path is separated by


slashes (“/”). For example, a path should be of the form "MyFolder/MyDatacenter/
DiscoveredVM/VM1". A leading slash or trailing slash is ignored. The following paths all
represents the same object: "a/b", "/a/b", "a/b/", and “/a/b/”.

Finding a Virtual Machine by Datastore Path


The FindByDatastorePath lets you return a VirtualMachine managed object reference using a
Datacenter managed object reference and a datastore path. The FindByDatastorePath takes the
following parameters::
• SearchIndex 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.
• Datacenter managed object reference – The datacenter to which the datastore path belongs.
You can obtain this managed object reference in a number of ways:
• Create a PropertyFilterSpec. See Getting Property Information on page 124.
• Invoke the FindByInventoryPath operation. See Finding a ManagedEntity by InventoryPath
on page 135.
• Invoke the FindChild operation. See Searching the Immediate Children of a ManagedEntity
on page 138.
• path – A datastore path to the .vmx file for the virtual machine.

Finding a Virtual Machine or Host by DNS Name


The FindByDnsName operation lets you find a virtual machine or host using the DNS name. This
operation takes the following parameters:
• SearchIndex 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.
• Datacenter managed object reference– Optional. If specified, restricts the query to virtual
machines or hosts in a particular datacenter. If not specified, the entire inventory is searched.
You can obtain this managed object reference in a number of ways:
• Create a PropertyFilterSpec. See Getting Property Information on page 124.
• Invoke the FindByInventoryPath operation. See Finding a ManagedEntity by InventoryPath
on page 135.
• Invoke the FindChild operation on the rootFolder. See Searching the Immediate Children
of a ManagedEntity on page 138.

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.

Finding a Virtual Machine or Host by UUID


The FindByUuid operation lets you find a virtual machine or host using the entity’s Universally
Unique IDentifier (UUID). The operation takes the following parameters:
• SearchIndex 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.
• Datacenter managed object reference– Optional. If specified, restricts the query to virtual
machines or hosts in a particular datacenter. If not specified, the entire inventory is searched.
You can obtain this managed object reference in a number of ways:
• Create a PropertyFilterSpec. See Getting Property Information on page 124.
• Invoke the FindByInventoryPath operation. See Finding a ManagedEntity by InventoryPath
on page 135.
• Invoke the FindChild operation on the rootFolder. See Searching the Immediate Children
of a ManagedEntity on page 138.
• uuid – A string representing the UUID of the entity for which you are searching.
• vmSearch – A boolean. If true, the operation returns only a virtual machine. If false, the
operation returns only a host.

Finding a Virtual Machine or Host by Its IP Address


The FindByIp operation lets you return a VirtualMachine or HostSystem managed object reference
from an IP address. The parameters are:
• SearchIndex 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.
• Datacenter managed object reference– Optional. If specified, restricts the query to virtual
machines or hosts in a particular datacenter. If not specified, the entire inventory is searched.
You can obtain this managed object reference in a number of ways:
• Create a PropertyFilterSpec. See Getting Property Information on page 124.

137
VMware Infrastructure SDK Programming Guide

• Invoke the FindByInventoryPath operation. See Finding a ManagedEntity by InventoryPath


on page 135.
• Invoke the FindChild operation on the rootFolder. See Searching the Immediate Children
of a ManagedEntity on page 138.
• ip – A string representing the IP address of the host or virtual machine. the IP address is in
dot-notation. For example, 10.17.12.12. The IP address for a virtual machine is the one
returned from VMware tools.
• vmSearch – A boolean. If true, the operation returns only a virtual machine. If false, the
operation returns only a host.
Note: If called directly on an ESX server and with vmSearch set to false, the result is always
empty.

Searching the Immediate Children of a ManagedEntity


The FindChild operation returns a ManagedEntity managed object reference based on the name
of the ManagedEntity. The operation searches only among the immediate children of a managed
entity. For a Datacenter, the host and vm folders are considered children. For a ComputeResource,
the hosts and root ResourcePool are considered children.
For example, in the figure below, the vmFolder and the hostFolder are the immediate children of
the Datacenter. Therefore, if you use the Datacenter as the base entity for the search, the vmFolder
and hostFolder only (and not their children) are considered for a match. If the designated entity is
anything other than a Folder managed entity, the search will return a null result.
Likewise, if you use the ClusterComputeResource as the base entity for the search, the search
returns a null result for any designated entity other than either its HostSystem or its root
ResourcePool.

www.vmware.com
138
C H A P T E R 6 Getting Information and Updates

rootFolder

Folder Folder Folder

Datacenter
Immediate child of Immediate child of
Datacenter Datacenter

vmFolder hostFolder

VirtualMachine VirtualMachine VirtualMachine VirtualMachine ComputerResource ComputeResource ClusterComputeResource

ResourcePool Host ResourcePool Host ResourcePool Host Host

ResourcePool ResourcePool
Immediate children of
ComputeResource

139
VMware Infrastructure SDK Programming Guide

Getting Updates on Properties


You can use one of three operations to get updates on properties:
• RetrieveProperties
• CheckForUpdates
• WaitForUpdates

Getting Updates with RetrieveProperties


Retrieving Property Information on page 133 describes the usage of the RetrieveProperties
operation. As described there, this operation retrieves all the information for the properties
specified in a PropertyFilterSpec. Often, however, a single use of RetrieveProperties is not enough.
If the values of the properties change frequently, and the client needs to refresh the information,
the changes need to be transmitted to the client continually.
You can invoke RetrieveProperties repeatedly to get the most recent values of the properties
specified in the PropertyFilterSpec, but this is the least efficient way to get updated information.
Rather than fetch all the properties each time, you can reduce network traffic by invoking
CheckForUpdates or WaitForUpdates. These operations return only the updated values, using
network bandwidth more efficiently.

Checking or Waiting for Updates


Instead of invoking RetrieveProperties repeatedly, you can invoke either the CheckForUpdates
operation or the WaitForUpdates operation. These operations poll for updates on properties
specified by the union of all current property filters (as described in Creating a Property Filter on
page 141). CheckForUpdates returns immediately, even if there are no changes. WaitForUpdates
returns only if there are changes to the properties.

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.

Creating a Property Filter


The CheckForUpdates and WaitForUpdates operations check the union of all the current
PropertyFilter objects. A PropertyFilter defines a filter that controls the properties a collector
retrieves and observes for changes. If the current filters do not contain the properties you want to
observe for changes, you must create one with the CreateFilter operation. A PropertyFilter
managed object is created based a PropertyFilterSpec data object, which specifies the objects of
interest and the properties to be collected from them.
The CreateFilter operation includes the following parameters:

141
VMware Infrastructure SDK Programming Guide

• 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.
• spec – A PropertyFilterSpec data object. See Getting Property Information on page 124 for
information about creating a PropertyFilterSpec.
• partialUpdates – See Setting the partialUpdates Flag on page 142.

Cancelling a Wait for Updates


WaitForUpdates does not complete until an update occurs, rather than returning an empty
UpdateSet data object. You can cancel a WaitForUpdates operation by invoking the
CancelWaitForUpdates operation. This operation takes only one parameter, a PropertyCollector
managed object reference. The PropertyCollector managed object reference is 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. The following code
snippet illustrates this:
ManagedObjectReference sir = new ManagedObjectReference();
sir.setType("ServiceInstance");
sir.setValue("ServiceInstance");

// Call retrieveServiceContent()
ServiceContent sic = vimService.retrieveServiceContent(sir);

ManagedObjectReference pcr = sic.getPropertyCollector();

Setting the partialUpdates Flag


If the final property in the property path string is a complex type, and you request notification of
property updates to that property, you get back changes to any of its constituent properties. For
instance, specifying a.b.c would result in notification of changes to a.b.c.d or a.b.c.e or
any other nested property at that level. You can control whether these change notifications are
sent individually using the partialUpdates flag.
The partialUpdates flag offers another way to minimize network traffic. In cases where a requested
property is a data object type rather than a built-in type, the requested property contains
properties of its own. These are nested properties, but the client may not have specified them in
the PropertyFilterSpec. The partialUpdates flag allows the user to retrieve only the nested property
that changed, rather than all the properties of the data object.
For example, suppose a client creates a property filter that specifies the
summary.guest.guestState property of a virtual machine. When the client invokes
CheckForUpdates or WaitForUpdates, a change to the guestState property is returned in a

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

Configuring Intervals for Statistics


As described in Perf Intervals on page 59, there are default performance intervals and user-defined
intervals. You can create, change, or delete user-defined intervals.

Creating Performance Intervals


The CreatePerfInterval operation lets you create an interval (in seconds) that is used to gather
information for all the managed entities. The operation takes two parameters: a managed object
reference for the PerformanceManager and a PerfInterval object. The PerfInterval object defines
three properties:
• name - The user-defined name for the interval.
• length - An integer that defines (in seconds) the length of time that information is kept in the
database..
• samplingPeriod - An integer that defines (in seconds) the interval of the sample. For example,
a samplingPeriod of 300 would sample every five minutes (60x5).

Updating Performance Intervals


You can use the UpdatePerfInterval operation to change existing intervals. This operation takes the
same parameters as the CreatePerfInterval operation. In this case, the samplingPeriod represents
the unique interval identifier of the interval. The length and name properties are optional and
contain the values to be changed.
For example, suppose you have a perf interval of five minutes for one hour and you want to
change the length from one hour to two hours. You invoke the UpdatePerfInterval operation with
the following parameters:
PerfInterval interval = new PerfInterval();
interval.samplingPeriod = 300;
interval.length = 7200;
UpdatePerfInterval(pmMor, interval);

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

Removing Performance Intervals


The RemovePerfInterval lets you delete an interval. This operation takes two arguments: the
managed object reference to the PerformanceManager and the samplingPeriod. The number of
seconds in the samplingPeriod provides the Interval ID and identifies the specific interval to be
removed. For example:
RemovePerfInterval(pmMor, 300);

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.

Querying Information for an Entity and Its Children


The QueryPerfComposite operation lets you query for performance statistics for an entity and the
breakdown for its child entities. The client can limit the returned information by specifying a list of
metrics, and a suggested sample interval ID. The server accepts either the refreshRate property or
one of the historical intervals as input interval. For example, you can use this operation to retrieve
statistics for a host and all of its registered virtual machines for the given time period. This
operation does only one level breakdown. For a resource pool, it breaks only down to its direct
child resource pools and virtual machines.

www.vmware.com
148
C H A P T E R 7 Monitoring Performance Data

Querying Performance Provider Information


The QueryPerfProviderSummary operation retrieves information about a performance provider in
the form of the PerfProviderSummary data object type. A performance provider is a
ManagedEntity that can supply real-time and/or historical statistics. The PerfProviderSummary
data object type describes capabilities of a performance provider. The summary indicates whether
real-time (current) and historical (summarized) stats are supported. For providers with the
currentSupported property set to true, clients can call the QueryPerf operation with the interval set
to the provider's refreshRate to retrieve real-time stats. If the summarySupported operation is true,
clients can call QueryPerf with the interval set to one of the historical intervals configured in the
system to retrieve historical statistics for the entity.

149
VMware Infrastructure SDK Programming Guide

Querying Metadata Information


As described earlier in CounterIds and MetricIds on page 60, performance counter information is
identified by a CounterId. The QueryPerfCounter operation lets you retrieve Counter information
by passing in one or more CounterIds. For example, suppose you want to find all the counter
information related to the group “CPU”. You define a helper function to find all the CounterIds
related to CPU and then return an array of these CounterIds. You use this array of CounterIds as an
argument to the QueryPerfCounter operation. The QueryPerfCounter operation also requires a
reference to a PerformanceManager managed object:
ManagedObjectReference sir = new ManagedObjectReference();
sir.setType("ServiceInstance");
sir.setValue("ServiceInstance");

ServiceContent sic = vimService.retrieveServiceContent(sir);


ManagedObjectReference pmMor = sic.getPerformanceManager();

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

Logging a User-Defined Event


The LogUserEvent operation lets you create a user-defined event. You create a user-defined event
associated with a particular managed entity such as a VirtualMachine. You can use this event to
add historical information about the managed entity to supplement any predefined events. You
can also use this event to provide markers when browsing event history.
The LogUserEvent operation takes the following parameters:
• EventManager managed object reference – See The EventManager Managed Object on
page 49 for information about this object.
• ManagedEntity managed object reference – The entity against which the event is logged.
The entity must be the root folder, a DataCenter, a VirtualMachine, a HostSystem, or a
ComputeResource.
• msg – A string. The message to be logged.

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.

Creating a Scheduled Task


You create a scheduled task by invoking the CreateScheduledTask operation. This operation takes
three parameters:
• ScheduledTaskManager managed object reference – You obtain this managed object
reference by invoking an accessor method on the scheduledTaskManager property of the
ServiceContent data object type. See Obtaining a Managed Object Reference on page 32 for
more information about using accessor methods.
• ManagedEntity managed object reference – The managed entity (or entities) for which the
scheduled task triggers an action. You can scheduled tasks on any managed entity. If the
scheduled task is associated with a leaf node in the inventory tree, it applies only to a single
entity (VirtualMachine or HostSystem). If the task is associated with 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 ScheduledTaskSpec data object type. The specification that defines the alarm. See
Configuring and Reconfiguring a Scheduled Task on page 153.
This operation returns a reference to a ScheduledTask managed object.

Configuring and Reconfiguring a Scheduled Task


When you create (CreateScheduledTask) or reconfigure (Reconfigure) a scheduled task, one of the
parameters for each operation is the ScheduledTaskSpec data object type. Through this
specification, you define the following properties of the scheduled task:
• action – Through the Action data object type and its extended objects, you define the action
(or actions) that occur after the scheduled task is triggered.
• scheduler – The TaskScheduler data object type and its extended objects let you define when
the action occurs.
• enabled – This boolean property defines whether the scheduled task is enabled or disabled.
• name, description – The name and description of the scheduled task.
• notification – The email notification. If not set, this property is set to empty string, indicating
no notification.
See the following sections for a further explanation of these properties.

153
VMware Infrastructure SDK Programming Guide

Choosing an Action or Set of Actions


The action property of the ScheduledTaskSpec determines the action that occurs when the
scheduled task is run. The Action data object type lets you define a single action that will fire at the
scheduled time defined by the scheduler property (Defining the Task Schedule on page 154). You
define the action through MethodAction data object type. 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 argument is an array consisting of the arguments
for the operation.
If the action 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 a scheduled task defined on a Folder entity.
// Task action...
// Power off all virtual machines in a certain folder.
MethodAction meAction = new MethodAction();
meAction.setName("PowerOffVM_Task");

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.

Defining the Task Schedule


You use the scheduler property of the ScheduledTaskSpec to define the times at which the task
actions will be triggered. The properties of the TaskScheduler data object type and its extended
objects let you set the time.
The base type, TaskScheduler, has two properties, activeTime and expireTime. The activeTime
property lets you define the time the scheduled task takes effect. If this property is not set, the time
defaults to the time the scheduled task was submitted. The expireTime property lets you define
the time the scheduled task expires. If this property is not set, the scheduled task does not expire.
The TaskScheduler object has the following sub-types:
• AfterStartupTaskScheduler – You can schedule a task to start as soon as the VirtualCenter
server is started or at a defined time after startup. You use the minute property to specify the
number of minutes. The value must be zero (task triggered at startup) or higher.
// Run the task 10 minutes after startup
AfterStartupTaskScheduler asts = new AfterStartupTaskScheduler();
asts.setMinute(10);

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

• MonthlyByWeekdayTaskScheduler – You schedule a task to run every month (or every


specified number of months) on a specified week, weekday, hour and minute. You can also
set the interval property to run the task after a specified number of months.
// On the last Wednesday of every month, at 30 minutes
// past the noon hour
MonthlyByWeekdayTaskScheduler mbwts =
new MonthlyByWeekdayTaskScheduler();
mbwts.setOffset(WeekOfMonth.last);
mbwts.setWeekday(DayOfWeek.wednesday);
mbwts.setHour(12);
mbwts.setMinute(30);

Constructing the ScheduledTaskSpec


The following code snippet shows the ScheduledTaskSpec for the code in the previous sections.
ScheduledTaskSpec tSpec = new tSpec();
tSpec.setName("SendEmail");
tSpec.setDescription("Sends an email twice a week");
tSpec.setEnabled(true);
tSpec.setScheduler(mbdts);
tSpec.setAction(emailAction);
tspec.setNotification(“ewacker@cnmail.com”);

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.

Cancellable and Non-Cancellable Tasks


You cannot cancel a task that is not running or has finished. Also, you cannot cancel tasks that are
not cancellable, as specified by the cancelable boolean property of the TaskInfo data object.

Deleting a Scheduled Task


To delete a scheduled task, you use the RemoveScheduledTask operation. This operation takes
only one parameter: the reference to the ScheduledTask managed object you want to delete.

Retrieving the Scheduled Tasks on an Entity


The RetrieveEntityScheduledTask operation lets you retrieve all the scheduled tasks associated
with a specified managed entity. The parameters for the operation are:
• ScheduledTaskManager – ScheduledTaskManager managed object reference. To obtain this,
you use an accessor method on the scheduledTaskManager property of the ServiceContent
object. See Obtaining a Managed Object Reference on page 32.
• entity – A reference to the ManagedEntity managed object. This is the entity whose tasks you
are retrieving. This parameter is optional. If you do not include this parameter, the operation
returns all scheduled tasks for visible entities.
Note: A “visible” entity is one for which you have permission. For more information about
permissions, see Managing Users on page 175.

Monitoring Operations with Managed Object Properties


You can use several properties to monitor tasks in the VMware Infrastructure SDK.

Using the info Property


Many operations (such as PowerOnVM_Task) return a Task managed object reference. Each
reference has an info property of the TaskInfo data object type. Using a PropertyCollector, you can
retrieve information from this data object type (see Getting Information and Updates on
page 123), such as:
• Whether or not the task can be cancelled. Some operations cannot be cancelled.
• Whether or not the client requested cancellation.
• The time stamp when the task entered, respectively, the queued state and running state.
• The time stamp when the task completed (whether success or error).
• The runtime status of the task: error, queued, running, or success.
• The progress of the task in percentage (0-100).

157
VMware Infrastructure SDK Programming Guide

Using the recentTask Property


The recentTask property of the TaskManager managed object comprises an array of Task managed
object references that completed recently (within the last ten minutes), are currently running, or
are queued to run. As described above, each Task managed object reference in the array contains
an info property (the TaskInfo data object type) that you can use to get information about the task.
Note: This list of recent tasks contains only tasks visible to the client. Visibility depends on the
client having permissions to access the task's managed entity.

www.vmware.com
158
C H A P T E R 8 Managing Events, Tasks, and Alarms

Retrieving Historical Information


You can retrieve historical information for events and tasks.

Retrieving Historical Event Information


As described in Using a History Collector for Historical Task Information on page 50, a history
collector lets you collect events based on certain criteria you select through a filter you create.

Creating a Collector for Events


The CreateCollectorForEvents operation filters events from the entire database of past events. The
operation takes two parameters:
• EventManager managed object reference – You obtain this by running
RetrieveServiceContent to return the ServiceContent data object type. The eventManager
property is one of the ServiceContent properties.
• EventFilterSpec – The specification for creating the event filter. The properties in this
specification let you select events during a specific time range, according to a specific event
category, belonging to a particular user, or associated with other objects, such as alarms.
Alarm objects are explained at Managing Alarms on page 165.

Reading the Items in the EventHistoryCollector


You can retrieve items from the EventHistoryCollector in one of three ways:
• Use the latestPage property
The EventHistoryCollector managed object includes a latestPage property. You can retrieve
the contents of the latest page by creating a PropertyCollector to select this property. See
Getting Information and Updates on page 123 for more information about creating a
PropertyCollector.
• Invoke the ReadNextEvents operation
This operation lets you retrieve the next page of items in the collector based on your current
position in the list. See Modifying the Current Position on page 163 for an explanation of
current position.
When you invoke this operation, you include the following parameters: the
EventHistoryCollector managed object reference and maxCount (the maximum number of
items you want in the scrollable view).
• Invoke the ReadPreviousEvents operation
This operation lets you retrieve the previous page of items in the collector based on the
current position in the list. See Modifying the Current Position on page 163 for an explanation
of current position.

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.

Formatting Event Messages


Event objects have specialized content that depends on the source of the event. For example, a
fault event contains a reference to the fault that caused it, while a scheduled task event contains a
reference to the responsible scheduled task and the managed entity associated with the
scheduled task. Scheduled tasks are explained at Managing Tasks on page 153.
All event objects have properties to connect them to an associated host, virtual machine,
datacenter, and compute resource. They also contain a time stamp, an event ID, and a formatted
message describing the event. Message strings can be localized. The localized strings used to
create events are stored in the EventManager’s description array.
To format an event message, you can use a pre-defined string or you can format a message string
that’s appropriate when viewed from a specific context. To use the pre-defined string, you obtain
the value of the Event object’s fullFormattedMessage property. For example, a powering on event
has the following value for its fullFormattedMessage property:
"{vm.name} on {host.name} in {datacenter.name} is powered on"

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"

• formatOnDatacenter – A string that’s appropriate in the context of a specific Datacenter. For


example, a renaming event in this context produces the following string:
"Renamed {vm.name} from {oldName} to {newName}"

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.

Retrieving Historical Task Information


A HistoryCollector managed object lets you collect information about events and tasks. See Using
a History Collector for Historical Task Information on page 50 for basic information about a history
collector. A TaskHistoryCollector managed object extends the HistoryCollector managed object
and lets you retrieve historical information about tasks based on specific information you provide
as a filter. The tasks collected refer to the Task managed object references returned by the API
operations.

Creating a Collector for Tasks


The CreateCollectorForTasks operation lets you retrieve historical task information based on a filter
you define. You provide two parameters for this operation:
• TaskManager managed object reference – You obtain this reference using an accessor
method for the taskManager property of the ServiceContent data object. See Obtaining a
Managed Object Reference on page 32.
• filter – This is the TaskFilterSpec data object. Within this object, you define the information
that will specify the tasks you want to collect.
This operation returns a TaskHistoryCollector managed object reference.

Reading the Items in the TaskHistoryCollector


You can retrieve items from the TaskHistoryCollector in one of three ways:
• Use the latestPage property
The TaskHistoryCollector managed object includes a latestPage property. You can retrieve the
contents of the latest page by creating a PropertyCollector to select this property. See
Getting Information and Updates on page 123 for more information about creating a
PropertyCollector.
• Invoke the ReadNextTasks operation
This operation lets you retrieve the next page of items in the collector based on your current
position in the list. See Modifying the Current Position on page 163 for an explanation of
current position and how to modify it.

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.

Using a History Collector


After you create an event or task history collector, you can invoke a number of operations to
manage the collector.

Setting the Viewable Latest Page


The items collected always include a viewable latest page. These items are a subset of all the items
collected and are the most recent items based on the time stamp. The default size of the latest
page is 1000 items, but you can set this page size using the SetCollectorPageSize operation. This
operation takes two parameters: a reference to the history collector and the maxCount, the
maximum number of items you want to include in the latest page size.

Updating the History Collector


After a collector is created, the collector receives updates when the server appends new data to
the collection. New items are appended to the end of the latest page. The oldest item is removed
from the latest page as illustrated below.

Two Items
Added

Two Items
Oldest Removed Newest
{

Viewable Latest Page


Latest Page Size = 100
{
500 Tasks

www.vmware.com
162
C H A P T E R 8 Managing Events, Tasks, and Alarms

Modifying the Current Position


The page of viewable items depends on your current position in the list of items in the collector.
When a history collector is created, the current position is automatically set to the beginning of the
list, that is, to the oldest item in the list. You read items in the list using either a ReadNext operation
(ReadNextEvents, ReadNextTasks) or a ReadPrevious operation (ReadPreviousEvents,
ReadPreviousTasks). These operations include a parameter for defining the maximum number of
items in the page. Each time you read the next or previous page, the current position is moved to
the beginning of the next newer page.
The following illustration shows a collection of tasks just after creation, where the collection totals
500 tasks and the latest page size has been set to 100 tasks. Notice that the current position is at
the beginning of the collection.

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.

Configuring or Reconfiguring an Alarm


When you create (CreateAlarm) or reconfigure (ReconfigureAlarm) an alarm, one of the parameters
for each operation is the AlarmSpec data object type. Through this specification, you define the
following properties of the alarm:
• expression – Through the AlarmExpression and its extended objects, you define the
conditions that will trigger the alarm. If there are multiple conditions, you can define a trigger
to occur when all conditions are satisfied (an AndAlarmExpression object) or when any
condition is satisfied (an OrAlarmExpression object). See Defining the Triggering Conditions
on page 166.
• action – Through the AlarmAction data object type and its extended objects, you define the
action (or actions) that occur after the alarm is triggered. See Choosing an Action or Set of
Actions on page 171.

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.

Defining the Triggering Conditions


You use the expression property of the AlarmSpec to define the conditions to be monitored. These
conditions can be either a metric (CPU usage, disk usage, memory usage, or network usage) or a
state. For a virtual machine, the state can be powered-on, powered-off, or suspended. For a host,
the state can be connected, disconnected, or not responding.
See Defining a Metric Alarm Expression on page 166 for more information about testing for
metrics. See Defining a State Alarm Expression on page 170 for more information about testing the
state of a virtual machine or host. See Handling Multiple Conditions on page 168 for information
about testing for multiple conditions.

Defining a Metric Alarm Expression


In the VMware Infrastructure SDK, when the condition involves a metric, an entity can be in one of
four overall condition statuses:
• gray – The status is unknown.
• red – The entity has a problem.
• yellow – The entity might have a problem.
• green – The status is OK. When an entity’s status is neither yellow not red, it is considered
green.
When you test for metrics, you must define a transition point into each state, that is, the points at
which the condition changes from one state to the next. For example, the following illustration
shows the CPU usage for a virtual machine with transition points:

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

PerfMetricId cpuMetric = new PerfMetricId();


cpuMetric.setCounterId(cpuCounter);
cpuMetric.setInstance(cpuInstance);

MetricAlarmExpression alarmExpression = new MetricAlarmExpression();


alarmExpression.setType(“VirtualMachine”);
alarmExpression.setOperator(MetricAlarmOperator.isAbove);
alarmExpression.setMetric(cpuMetric);

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.

Handling Multiple Conditions


You might need to apply multiple conditions to an entity. If the logic to trigger the alarm requires a
combination of conditions, you can decide whether or not to trigger when all conditions are
satisfied (AndAlarmExpression) or when any condition is satisfied (OrAlarmExpression).
The following code snippet uses an OrAlarmExpression object. When either the CPU or memory
usage passes a certain transition point, an action is triggered.
// Multiple Alarm expressions: Red = CPU > 90, Yellow = CPU > 75
// Red = Memory < 100, Yellow = Memory < 200

PerfMetricId cpuMetric = new PerfMetricId();


cpuMetric.setCounterId(cpuCounter);
cpuMetric.setInstance(cpuInstance);

PerfMetricId memMetric = new PerfMetricId();


memMetric.setCounterId(memCounter);
memMetric.setInstance(memInstance);

MetricAlarmExpression alarmExpressionCpu = new MetricAlarmExpression();


alarmExpression.setType(“VirtualMachine”);
alarmExpression.setOperator(MetricAlarmOperator.isAbove);
alarmExpression.setMetric(cpuMetric);
alarmExpression.setRed(90);
alarmExpression.setYellow(75);

MetricAlarmExpression alarmExpressionMem = new MetricAlarmExpression();


alarmExpressionMem.setType(“VirtualMachine”);
alarmExpressionMem.setOperator(MetricAlarmOperator.isBelow);
alarmExpressionMem.setMetric(memMetric);
alarmExpressionMem.setRed(100);
alarmExpressionMem.setYellow(200);

OrAlarmExpression orRelation = new OrAlarmExpression();


orRelation.setExpression(new AlarmExpression[]{alarmExpressionCpu,
alarmExpressionMem});

Setting the Range and Frequency of a Metric Expression


In some cases, the transition point can be crossed numerous times, causing the alarm to be
triggered again and again. By using the setting property of the AlarmSpec object, you can control

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

Defining a State Alarm Expression


You can use the running state of either a virtual machine or a host as the condition that triggers an
alarm. To do this, you use the StateAlarmExpression object. This object includes the following
properties:
• type – This string property defines the object (VirtualMachine or HostSystem) whose state is
being checked. Its value is one of the values of the type property of the
ManagedObjectReference data object.

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.

Choosing an Action or Set of Actions


The action property of the AlarmSpec determines the action that occurs when the alarm is
triggered. The AlarmAction data object type is extended by the AlarmTriggeringAction and the
GroupAlarmAction data object types.

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

// Trigger for action


AlarmTriggeringAction alarmAction = new AlarmTriggeringAction();
alarmAction.setAction(seAction); // send this email
alarmAction.setGreen2Yellow(true); // trigger on green->Yellow
alarmAction.setYellow2Red(true); // trigger on yellow->red

Constructing the AlarmSpec


The following code snippet shows the AlarmSpec for the alarm created in the previous sections.
// Spec for the whole thing
AlarmSpec alarmSpec = new AlarmSpec();
alarmSpec.setName("VM CPU");
alarmSpec.setDescription("Red = CPU > 90, Yellow = CPU > 75");
alarmSpec.setEnabled(true);
alarmSpec.setExpression(alarmExpression);
alarmSpec.setAction(alarmAction);

Getting a List of Alarms


You can use the GetAlarm operation to get a list of the references to all the Alarm managed objects
currently defined for a specific ManagedEntity. The parameters for the operation are a reference to
the AlarmManager object and an optional reference to the ManagedEntity object. If you don’t
include the optional ManagedEntity reference, the operation returns the alarms on all the visible
entities.

Getting the Overall Status of Alarm


You use the GetAlarmState operation to find out the overall status of the alarms on an entity. This
operation takes as its parameters a reference to an AlarmManager managed object and a reference
to the ManagedEntity object associated with the alarms. The operation returns an array of
AlarmState data objects. The AlarmState set includes information about each alarm including the
entity on which the alarm is instantiated, a unique key, and the overall status.
The overall status of an alarm can be one of the following:
• gray – The status is unknown.
• green – The status is OK.
• red – The entity has a problem.
• yellow – The entity might have a problem.

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, Roles, and Permissions


Privileges define basic rights. Roles are aggregations of privileges. You associate privileges with a
user or a group when you create a permission.

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

Privileges and Operations


Privileges can be required to invoke operations and to perform actions on a managed object. Each
operation in the VMware Infrastructure SDK Reference Guide includes the list of privileges required to
invoke that operation. Operations associated with a managed object that is not a managed entity
generally require the necessary privileges on the root folder. For example, AddAuthorizationRole is
associated with the AuthorizationManager managed object.
Operations associated with a managed entity (for example, CreateVM_Task is associated with the
Folder managed entity) require the necessary privileges on a specific entity. For example, to create
a virtual machine, a user must hold the VirtualMachine.Inventory.Create privilege on the folder
where the virtual machine will be located. In addition, a user must hold the
Resource.AssignVMToPool privilege on the resource pool entity with which the virtual machine will
be associated.
See Privileges on page 301 for a list of operations and the privileges required to invoke them.

Operations That Require Privileges on an Entity and Its Parent


Operations invoked to delete or modify a managed entity require the necessary privilege on the
specific entity being deleted/modified. In addition, however, these operations require that you
have the same privilege on the entity’s parent. This includes the following operations:
• Destroy_Task
• DestroyChildren
• UnregisterAndDestroy

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.

Privileges and Properties


A user also requires privileges to read certain properties of certain managed objects. For example,
to read the perfCounter property of the AuthorizationManager managed object, a user must have
the System.View privilege on the root folder. Properties on a ManagedEntity (or related entity)
generally require System.Read on the entity. Properties on a managed object generally require
System.View on the root folder. See Privileges and Properties on page 312 for a list of the properties
and their privileges.

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.

Permissions and Sub-Objects


A propagation flag specifies whether or not the rule applies to sub-objects of the managed entity.
In the VMware Infrastructure SDK, authorization is always granted “down”, never “up” in the
ManagedEntity inventory. For example, consider the following inventory tree.

www.vmware.com
178
C H A P T E R 9 Managing Users

rootFolder (N)

Folder (N) Folder Folder

Datacenter (N)

vmFolder (Yes) hostFolder

VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) ComputerResource ComputeResource ComputerResource ComputeResource

ResourcePool Host ResourcePool Host ResourcePool Host Host ResourcePool Host

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

Permissions and Complex Entities


A complex entity is aggregation of certain managed entities in the inventory tree. The complex
entity is formed with the parent entity when the parent entity is a Datacenter, a ComputeResource,
or a ClusterComputeResource. Complex entities comprise three types:
• A Datacenter, its root virtual machine folder, and its root host folder
• A ComputeResource, its root ResourcePool, and its HostSystem
• A ClusterComputeResource and its root ResourcePool
The following figure illustrates the three complex entity types in a VirtualCenter hierarchy.

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.

Users, Groups, and Permissions


A ManagedEntity can have multiple permissions, but only one permission per user or group. When
a user logs on, if the user has both a user permission and a group permission (as a group member)
for the same entity, then the user-specific permission takes precedent. If the user has no user
permission, and the user is a member of more than one group that has group permissions on the
entity, then the privileges are the union of the specified roles associated with the permissions.
If the user has permissions on a virtual machine that are defined both by its resource pool and its
folder, the user gets the union of the permissions on the virtual machine in that case as well. This is

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

Adding and Maintaining Users and Groups


(ESX only)
The VMware Infrastructure SDK comprises individual users and groups to which those users
belong. Users, Groups, and Permissions on page 180 describes how authorization is handled when
a user has authorization both as an individual user and as a member of a group. To manage users
and groups, you use the following operations:
• CreateUser and UpdateUser
The CreateUser operation takes as its arguments a reference to a HostLocalAccountManager
managed object and a HostAccountSpec data object. The specification object includes a
description, an ID for the specified account, and a password. The description and the
password need not be set. However, the user needs a password to log on, so you include the
password as a parameter. You can also add the password later by invoking the UpdateUser
operation.
Note: The format of the ID and password must follow whatever rules are configured for your
system.
The UpdateUser operation lets you change user information after the user is created. The
operation takes as its arguments the same parameters as CreateUser. The HostAccountSpec
data object contains the properties that let you change information about the user. The id
property is required and identifies the user whose information you want to change.
• CreateGroup and AssignUserToGroup
You can create groups of users who perform the same operations. This lets you assign
authorization to a group of users.
To create a group, use the CreateGroup operation. This operation takes two parameters: a
reference to a HostLocalAccountManager managed object and the HostAccountSpec data
object. This specification comprises a required id property to identify the specified group
account and an optional description. You do not need to set a password for a group account.
Note: The form of the ID and password must follow whatever rules are configured for your
system.
The AssignUserToGroup operation lets you assign individual users to a group. The parameters
for this operation include a HostLocalAccountManager managed object reference, the ID of
the user being assigned, and the ID of the group to which the user is being assigned.
• UnAssignUserFromGroup

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

Querying for Users and Groups


You use the RetrieveUserGroups to get users and groups. For VirtualCenter on Windows, a search is
restricted to the given domain. If the domain is omitted, then the search is performed on local
users and groups. On ESX Server (or Linux systems), with the exception of systems configured with
Network Information System (NIS), only local users and groups are searched. For NIS-configured
systems, NIS domain users and groups are also searched.The operation includes the following
parameters:
• A UserDirectory managed object reference. See Obtaining a Reference to the
AuthorizationManager on page 189.
• The domain that will be searched. This is optional and, if left unset, only the local machine is
searched.
• A case-insensitive search-string. This matches on both the login and full name for users, and
on both the name and description for groups. Leave this blank to match all users.
• An optional group name (not supported in VirtualCenter). If present, only users or groups that
directly belong to the specified group are returned. Users or groups that have indirect
membership are not returned.
• An optional user name (not supported in VirtualCenter). If present, only groups that directly
contain the specified user are returned. Groups that indirectly contain the user will not be
returned.
• A boolean that, if set to true, indicates the search string passed should match a user or group
name exactly.
• A boolean that, if set to true, indicates users should be included in the result.
• A boolean that, if true, indicates groups should be included in the result.

www.vmware.com
184
C H A P T E R 9 Managing Users

Adding and Maintaining Authorization Roles


To assign privileges to users, you define authorization roles. As described in Roles on page 177, a
role is an aggregation of privileges.
You use the following operations to manage authorization roles.
• AddAuthorizationRole and UpdateAuthorizationRole
The AddAuthorizationRole operation lets you add any authorization roles you need. This
operation takes the following parameters: a reference to the AuthorizationManager managed
object, the name of the role, and a set of the privileges associated with the role. The
operation returns the ID associated with the role.
The UpdateAuthorizationRole operation lets you change the name of a role or the set of
privileges associated with the role. In addition to these items, the operation takes as a
parameter the ID of the role that is being updated. When you update an authorization role,
any privileges in the parameter replace existing privileges for the role.
Note: Each privilege in the set of privileges you use as a parameter takes the following
format:
<group>[.<group>].privilege
See the VMware Infrastructure SDK Reference Guide for the privileges associated with an
operation or required to perform operations on an entity.
• RemoveAuthorizationRole
Use this operation to remove any role from the system. This operation takes three parameters:
the reference to the AuthorizationManager managed object, the ID associated with the role
you want to remove, and a boolean flag that determines whether or not you want to remove
this role if the role is used by any permissions. If the boolean is set to true, the role is not
removed if the role is associated with any permissions.

185
VMware Infrastructure SDK Programming Guide

Setting and Maintaining Permissions on an


Entity
The Permission data object associates a user or group with a role (which is an aggregation of
privileges. When you set entity permissions, you are associating one or more Permission data
objects with a ManagedEntity. You use the following operations to manage Permissions:
SetEntityPermissions, ResetEntityPermissions, and RemoveEntityPermission.

Setting, Updating, or Resetting Entity Permissions


To set or update permissions on an entity, you use the SetEntityPermissions operation. To
completely replace the current permissions with a new set of permissions, you use the
ResetEntityPermissions operation.
Note: You can only set permissions on the parent entity in a complex entity. The permissions are
propogated to the child entities. If you try to set permissions on a child entity, an exception is
thrown. See Permissions and Complex Entities on page 180 for a description of complex entities.
The parameters for both operations include:
• AuthorizationManager managed object reference
• ManagedEntity managed object reference – The entity for which you want to grant the
privileges.
• Use the rootFolder managed object reference if the privileges being granted are for
operations or properties associated with a managed object that is not a managed entity.
• Use a specific ManagedEntity managed object reference (folder, datacenter, and so on) if
the privileges being granted are for operations or properties associated with a managed
entity.
See Permissions on page 178 for more information about this parameter.
• The permissions you want to grant. This parameter comprises an array of zero or more
Permission data objects. If a permission in the array already exists on the entity, the existing
permission is updated with the new information, otherwise the permission is added. A
Permission data object comprises the following information:
• The principal (the user or group) for which access is granted. The boolean property “group”
boolean determines whether this value is a user or group. To get the value for this field, you
can use RetrieveUserGroups. See Querying for Users and Groups on page 184.
• The ID of the AuthorizationRole that contains the privileges being granted.

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.

Removing Entity Permissions


You invoke the RemoveEntityPermission operation to take away permission for a particular user or
group on an entity. The parameters include:
• An AuthorizationManager managed object reference.
• A reference to the ManagedEntity managed object for which you want to remove the user’s
privileges.
• The user or group for which the permission is defined. To get the value for this field, use
RetrieveUserGroups. See Querying for Users and Groups on page 184.
• A boolean that specifies whether the user is a group (TRUE) or a user (FALSE).

187
VMware Infrastructure SDK Programming Guide

Querying for Permissions


You can use several operations to query for permissions: RetrieveAllPermissions,
RetrieveEntityPermission, and RetrieveRolePermissions.

Querying for All Permissions


You use the RetrieveAllPermissions operations to get all permissions defined for all users in the
system. This operation takes only one parameter, the AuthorizationManager managed object
reference.

Querying for the Permissions on a Specific Entity


You use the RetrieveEntityPermissions operation to get the permissions for a specific entity. The
parameters include:
• An AuthorizationManager managed object reference
• A reference to the ManagedEntity managed object whose permissions you want
• A boolean property that lets you include propagating permissions defined by parent entities.
See Permissions and Sub-Objects on page 178.
A child entity that is part of a complex entity has the same permissions as its parent entity. When
you query for permissions on a child entity of a complex entity (see Permissions and Complex
Entities on page 180), the results depend on whether the product is VirtualCenter or ESX Server. In
VirtualCenter, the entity that’s reported as owning the permissions is the parent entity. In ESX
Server, the child entity is reported as owning the permissions.

Querying for the Permissions that Use a Particular Role


You use RetrieveRolePermission to get the permissions that use a specific role. The parameters
include:
• An AuthorizationManager managed object reference
• The ID for the role used by the permissions

www.vmware.com
188
C H A P T E R 9 Managing Users

Obtaining a Reference to the


AuthorizationManager
The operations for adding or maintaining users, groups, permissions, and roles require a managed
object reference as one of the parameters. Users and groups require a reference to the
HostLocalAccountManager managed object. Permissions and roles require a reference to the
AuthorizationManager managed object. To obtain these, you use an accessor method on the
ServiceContent data object for the appropriate property. The following Java sample code snippet
shows how to obtain a managed object reference on the AuthorizationManager:
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
_svcRef.setValue("ServiceInstance");

_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;

// the VirtualInfrastructureManagement Client side stubs


import com.vmware.vim.*;

/**
* 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 {

protected VimServiceLocator _locator;


protected VimPortType _service;
protected int _svcState;

191
VMware Infrastructure SDK Programming Guide

protected ServiceContent _sic;


protected ManagedObjectReference _svcRef;

protected ManagedObjectReference _propCol;


protected ManagedObjectReference _rootFolder;

/**
* 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");

// could be ServiceInstance for "HostAgent" and "VPX" for VPXd


_svcRef.set_value("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();
}

_locator = new VimServiceLocator();


_locator.setMaintainSession(true);
_service = _locator.getVimPort(new URL(urlStr));

_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 {

TraversalSpec resourcePoolTraversalSpec = new TraversalSpec();


resourcePoolTraversalSpec.setName("resourcePoolTraversalSpec");
resourcePoolTraversalSpec.setType("ResourcePool");
resourcePoolTraversalSpec.setPath("resourcePool");
resourcePoolTraversalSpec.setSkip(new Boolean(false));
resourcePoolTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec
("resourcePoolTraversalSpec") });

TraversalSpec computeResourceRpTraversalSpec = new TraversalSpec();


computeResourceRpTraversalSpec.setName(
"computeResourceRpTraversalSpec");
computeResourceRpTraversalSpec.setType("ComputeResource");
computeResourceRpTraversalSpec.setPath("resourcePool");
computeResourceRpTraversalSpec.setSkip(new Boolean(false));
computeResourceRpTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("
resourcePoolTraversalSpec") });

TraversalSpec computeResourceHostTraversalSpec = new TraversalSpec();


computeResourceHostTraversalSpec.setName(
"computeResourceHostTraversalSpec");
computeResourceHostTraversalSpec.setType("ComputeResource");
computeResourceHostTraversalSpec.setPath("host");
computeResourceHostTraversalSpec.setSkip(new Boolean(false));

TraversalSpec datacenterHostTraversalSpec = new TraversalSpec();


datacenterHostTraversalSpec.setName("datacenterHostTraversalSpec");
datacenterHostTraversalSpec.setType("Datacenter");
datacenterHostTraversalSpec.setPath("hostFolder");
datacenterHostTraversalSpec.setSkip(new Boolean(false));

193
VMware Infrastructure SDK Programming Guide

datacenterHostTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });

TraversalSpec datacenterVmTraversalSpec = new TraversalSpec();


datacenterVmTraversalSpec.setName("datacenterVmTraversalSpec");
datacenterVmTraversalSpec.setType("Datacenter");
datacenterVmTraversalSpec.setPath("vmFolder");
datacenterVmTraversalSpec.setSkip(new Boolean(false));
datacenterVmTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });

TraversalSpec folderTraversalSpec = new TraversalSpec();


folderTraversalSpec.setName("folderTraversalSpec");
folderTraversalSpec.setType("Folder");
folderTraversalSpec.setPath("childEntity");
folderTraversalSpec.setSkip(new Boolean(false));
folderTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec"),
datacenterHostTraversalSpec,
datacenterVmTraversalSpec,
computeResourceRpTraversalSpec,
computeResourceHostTraversalSpec,
resourcePoolTraversalSpec });

PropertySpec[] propspecary = new PropertySpec[] { new PropertySpec() };


propspecary[0].setAll(new Boolean(false));
propspecary[0].setPathSet(new String[] { "name" });
propspecary[0].setType("ManagedEntity");

PropertyFilterSpec spec = new PropertyFilterSpec();


spec.setPropSet(propspecary);
spec.setObjectSet(new ObjectSpec[] { new ObjectSpec() });
spec.getObjectSet(0).setObj(_rootFolder);
spec.getObjectSet(0).setSkip(new Boolean(false));
spec.getObjectSet(0).setSelectSet(
new SelectionSpec[] { folderTraversalSpec });

// Recursively get all ManagedEntity ManagedObjectReferences


// and the "name" property for all ManagedEntities retrieved
ObjectContent[] ocary = _service.retrieveProperties(
_propCol, new PropertyFilterSpec[] { spec }
);

// If we get contents back. print them out.


if (ocary != null) {
ObjectContent oc = null;
ManagedObjectReference mor = null;

www.vmware.com
194
C H A P T E R 1 0 Creating a Simple Java Client Application

DynamicProperty[] pcary = null;


DynamicProperty pc = null;
for (int oci = 0; oci < ocary.length; oci++) {
oc = ocary[oci];
mor = oc.getObj();
pcary = oc.getPropSet();

System.out.println("Object Type : " + mor.getType());


System.out.println("Reference Value : " + mor.get_value());

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;

System.out.println("Inner Object Type : " +


imor.getType());
System.out.println("Inner Reference Value : " +
imor.get_value());
}
else {
System.out.println("Inner Property Value : " +
oval);
}
}
}
}
}
}
}
} else {
System.out.println("No Managed Entities retrieved!");
}

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>"
);
}

SimpleClient sc = new SimpleClient();

try {
// Create the Service Managed Object Reference
sc.createServiceRef();

// Connect to the Service


sc.connect(args[0], args[1], args[2]);

// Retrieve Container contents for all Managed Entities


// and their names
sc.getAndPrintInventoryContents();

// Disconnect from the WebServcice


sc.disconnect();
} catch (Exception e) {
System.out.println("Caught Exception : " +
" Name : " + e.getClass().getName() +
" Message : " + e.getMessage() +
" Trace : ");
e.printStackTrace();
}
}
}

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

Logging On to the Web Service


Logging On on page 61 describes the concepts behind the code for logging on. The following
sample illustrates how to log into the Web service.
ManagedObjectReference _svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
_svcRef.setValue("ServiceInstance");

// You can log on using either non-SSL or SSL.


// See Setting up the VMware Infrastructure SDK Client on page 25 for more information.
VimServiceLocator _locator = new VimServiceLocator();
_locator.setMaintainSession(true);
_service = _locator.getVimPort(new URL("https://<your_server>/sdk"));

ServiceContent _sic = _service.retrieveServiceContent(_svcRef);


_service.login(_sic.getSessionManager(), username, password, null);

www.vmware.com
198
C H A P T E R 1 1 Java Code Examples for Basic Operations

Basic Data Synchronization Loop


The following Java code snippet demonstrates the building of a data synchronization loop for a
single virtual machine. This snippet calls CheckForUpdates repeatedly:
{
...
{
...
ManagedEntity vmRef = FindByInventoryPath(_sic.getSearchIndex(),
PathToVm);

PropertySpec pSpec = new PropertySpec();


pSpec.setType("VirtualMachine");
pSpec.setPathSet("runtime.powerState");

ObjectSpec oSpec = new ObjectSpec();


oSpec.setObj(vmRef);
oSpec.setSkip(Boolean.FALSE);

PropertyFilterSpec pfSpec = new PropertyFilterSpec();


pfSpec.setObjectSet(new ObjectSpec[] {oSpec});
pfSpec.setPropSet(new PropertySpec[] {pSpec});

ManagedObjectReference pcRef = _sic.getPropertyCollector();


ManagedObjectReference pFilter = _service.CreateFilter(pcRef, pfSpec,
Boolean.FALSE);

String version = ""; // Start with no version


while (true) {
UpdateSet changeData = _service.checkForUpdates(pcRef, version);
if(changeData != null) {

// Update the version


version = changeData.getVersion();
PropertyFilterUpdate[] pfUpdate = changeData.getFilterSet();
for(int a=0; a<pfUpdate.length; ++a) {

// Only interested in our filter


if(pFilter.get_value().equals(pfUpdate[a].getFilter().
get_value())) {
ObjectUpdate[] objUpdate = pfUpdate[a].getObjectSet();
// Only one object in the filter, so only one ObjectUpdate
// instance
System.out.println("At " + new Date() +
", the power state is: " +

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

Handling Permissions and Roles


Managing Users on page 175 describes the basic concepts and operations involved in granting
users permission in the VMware Infrastructure SDK. This section contains code samples for some of
the basic operations regarding permissions.

Creating Users and Groups


This first code snippet creates a user.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
/*
* Construct a HostAccountSpec for the new user.
*/
HostAccountSpec acctSpec = new HostAccountSpec();
acctSpec.setDescription("A user account");
acctSpec.setId("rbothne");
acctSpec.setPassword("jul2650");

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.");
}

...
}
}

In this next snippet, we create a group.


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...

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

System.out.println("A runtime fault occurred.");


}
...
}
}

Adding, Updating, and Removing Authorization Roles


You use three operations to maintain authorization roles: AddAuthorizationRole,
UpdateAuthorizationRole, and RemoveAuthorizationRole.

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.");
}
...
}
}

Updating Authorization Roles


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
String perms[] = {"Authorization.ReassignRolePermissions",
"Authorization.ModifyRoles", "System.View"};
UpdateAuthorizationRole(_sic.getAuthorizationManager(), 45164,
"ModRoles", perms);
catch (NumberFormatException number){

203
VMware Infrastructure SDK Programming Guide

System.out.println("The role id must be an integer.");


}
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.");
}
...
}
}

Removing Authorization Roles


The RoleId, a unique identifier that identifies an authorization role, is returned from the
AddAuthorizationRole operation. To remove the role, you pass this Id in as one of the parameters
to indicate the role you want to remove.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
boolean failWhenUsed = true;
RemoveAuthorizationRole(_sic.getAuthorizationManager(),
45164, failWhenUsed);
}
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
removed.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}

www.vmware.com
204
C H A P T E R 1 1 Java Code Examples for Basic Operations

Adding or Updating Permissions


As described in Managing Users on page 175, you use the SetEntityPermissions operation either to
add or update a permission. If you invoke the operation on an entity that already has the
permissions, the permissions are updated.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedEntity meRef = FindByInventoryPath(_sic.getSearchIndex(),
PathToEntity);

// Permission for "Administrators" group


Permission p1 = new Permission();
p1.setGroup(true);
p1.setPrincipal("Administrators");
p1.setPropagate(true);
p1.setRoleId(p1RoleId);

// Permission for "bobs" user


Permission p2 = new Permission();
p2.setGroup(false);
p2.setPrincipal("bobs");
p2.setPropagate(true);
p2.setRoleId(p2RoleId);

// Permission for "rbothne" user


Permission p3 = new Permission();
p3.setGroup(false);
p3.setPrincipal("rbothne");
p3.setPropagate(true);
p3.setRoleId(p3RoleId);

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

Querying for Permissions


Three operations let you retrieve all permissions, permissions for a specific managed entity, and
permissions associated with a specific role.

Querying for All Permissions


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
Permission[] perms = _service.retrieveAllPermissions(
_sic.getAuthorizationManager);
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}

Querying for Permissions on an Entity


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
ManagedEntity meRef = FindByInventoryPath(_sic.getSearchIndex,
PathToEntity);
Permission[] perms = _service.retrieveEntityPermissions(
_sic.getAuthorizationManager,
meRef);
}
catch (ManagedObjectNotFound moNotFound){
System.out.println("The entity does not exist.");
}
catch (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}

207
VMware Infrastructure SDK Programming Guide

Querying for Permissions Associated with a Role


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
try {
_service.retrieveRolePermissions(_sic.getAuthorizationManager(),
role);
}
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 (RuntimeFault rFault) {
System.out.println("A runtime fault occurred.");
}
...
}
}

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

catch (RuntimeFault rFault) {


System.out.println("A runtime fault occurred.");
}
...
}
}

209
VMware Infrastructure SDK Programming Guide

Getting Information About Properties


Getting Property Information on page 124 describes the concepts behind using a property
collector to traverse a managed object’s properties and collect information. This section shows
sample code snippets using a property collector.

Defining a PropertyFilterSpec with Recursion


The code in this section creates a PropertyFilterSpec designed to traverse the managed entity
hierarchy shown below, starting from any arbitrary object in that hierarchy. During the traversal,
the application collection information about VirtualMachine and HostSystem managed objects.

rootFolder

Folder Folder Folder

Datacenter

vmFolder hostFolder

VirtualMachine VirtualMachine VirtualMachine VirtualMachine ComputerResource ComputeResource ClusterComputeResource ComputeResource

ResourcePool Host ResourcePool Host ResourcePool Host Host ResourcePool Host

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

PropertySpec pspec = new PropertySpec();


pspec.setType("VirtualMachine");
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {“runtime.powerState”});

PropertySpec pspec2 = new PropertySpec();


pspec.setType(“HostSystem”);
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {“summary.runtime.connectionState”});

ObjectSpec oSpec = new ObjectSpec();


oSpec.setObj(objRef);
oSpec.setSkip(Boolean.FALSE);

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

• ComputeResource --> host


• ResourcePool --> resourcePool
new SelectionSpec("visitFolders");

/ This TraversalSpec covers Datacenter --> vmFolder


TraversalSpec dc2VmTSpec = new TraversalSpec();
dc2VmTSpec.setType("Datacenter");
dc2VmTSpec.setPath("vmFolder");
dc2VmTSpec.setSelectSet(recursiveSpec);

// This TraversalSpec covers Datacenter --> hostFolder


TraversalSpec dc2HostTSpec = new TraversalSpec();
dc2HostTSpec.setType("Datacenter");
dc2HostTSpec.setPath("hostFolder");
dc2HostTSpec.setSelectSet(new SelectionSpec[]{recursiveSpec});

/ This TraversalSpec covers ComputeResource --> resourcePool


TraversalSpec cr2RpTSpec = new TraversalSpec();
cr2RpTSpec.setType("ComputeResource");
cr2RpTSpec.setPath("resourcePool");

/ This TraversalSpec covers ComputeResource --> host


TraversalSpec cr2HostTSpec = new TraversalSpec();
cr2HostTSpec.setType("ComputeResource");
cr2HostTSpec.setPath("host");

/ This TraversalSpec covers ResourcePool --> resourcePool


TraversalSpec rp2rpTSpec = new TraversalSpec();
rp2rpTSpec.setType("ResourcePool");
rp2rpTSpec.setPath("resourcePool");

// This TraversalSpec covers Folder --> childEntity


TraversalSpec folderTSpec = new TraversalSpec();
folderTSpec.setName(TraverseFolder);
folderTSpec.setType("Folder");
folderTSpec.setPath("childEntity");
folderTSpec.setSelectSet(new SelectionSpec[]{recursiveSpec,
dc2VmTSpec,
dc2HostTSpec,
cr2RpTSpec,
cr2HostTSpec,
rp2rpTSpec});

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});

return new PropertyFilterSpec[]{pfSpec};


}

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

Getting Updates on an Inventory Object


See Basic Data Synchronization Loop on page 199 for the sample code for getting updates.

www.vmware.com
214
C H A P T E R 1 1 Java Code Examples for Basic Operations

Handling Exceptions in the Data


Synchronization Loop
Exceptions can occur when any Web service method is called. These exceptions can occur during
initialization (such as calling the vimServiceLocator constructor) or during calls to Web
service operations (such as PowerOnVm or CheckForUpdates).
One class of exceptions that requires handling is the standard Java exceptions that arise due to
remote communication. This class includes some of the exceptions in the packages, java.net
and java.rmi. Nothing is special regarding the handling of these exceptions for the Web
service. Instead, it is how the client application recovers from the exception situations.
The other class comprises exceptions that show up as the Java exceptions while calling the various
operations.
For more information, see Exception Handling and Faults on page 256.

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

• Moving an Inventory Object on page 244


• Renaming an Object on page 245
• Monitoring Events and Alarms on page 246
• Task Scheduling and Monitoring on page 251
• Exception Handling and Faults on page 256

www.vmware.com
218
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Creating and Configuring a Virtual Machine


The following code sample snippet creates and configures a virtual machine.
package com.vmware.vimsample.vmcreate;

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 {

public static final int EXTRA_ARG_COUNT = 9;


public static final int MIN_EXTRA_ARGS = 1;
public static final int ARG_VMNAME = ClientInfo.ARG_LAST_BASE + 1;
public static final int ARG_CREATEONHOST = ClientInfo.ARG_LAST_BASE + 2;
public static final int ARG_DATACENTERFOLDER = ClientInfo.ARG_LAST_BASE +
3;
public static final int ARG_HOSTFOLDER = ClientInfo.ARG_LAST_BASE + 4;
public static final int ARG_GUESTOSID = ClientInfo.ARG_LAST_BASE + 5;
public static final int ARG_CPUS = ClientInfo.ARG_LAST_BASE + 6;
public static final int ARG_SIZEMB = ClientInfo.ARG_LAST_BASE + 7;
public static final int ARG_ANNOTATION = ClientInfo.ARG_LAST_BASE + 8;
public static final int ARG_DISKFILENAME = ClientInfo.ARG_LAST_BASE + 9;

VmUtils _vmUtils;

public VmCreate(String name, String[] args) {


super(name, MIN_EXTRA_ARGS, "<vmname> [<host> <datacenterfolder>
<hostfolder> <guestOsId> <cpuCount> <memorySizeMB> <vm annotation>
<diskfilename>]", args);

_vmUtils = new VmUtils(clientInfo, log);


}

public String getVmName() {


String vmname = clientInfo.getArg(ARG_VMNAME);
if (vmname == null || vmname.length() == 0) {
vmname = "NewVirtualMachine_001";
}
return vmname;
}

219
VMware Infrastructure SDK Programming Guide

public String getGuestOsId() {


String guestId = clientInfo.getArg(ARG_GUESTOSID);
if (guestId == null || guestId.length() == 0) {
guestId = "redhat";
}
return guestId;
}

public int getCpuCount() {


int cpus = 1;

String strcpus = clientInfo.getArg(ARG_CPUS);


if (strcpus != null && strcpus.length() > 0) {
cpus = Integer.parseInt(strcpus);

// currently only allows max of 2 VCPUs to be created.


if (cpus > 2) {
cpus = 2;
}
}

return cpus;
}

public int getMemorySizeMB() {


int sizeMB = 64;

String strsizeMB = clientInfo.getArg(ARG_SIZEMB);


if (strsizeMB != null && strsizeMB.length() > 0) {
sizeMB = Integer.parseInt(strsizeMB);
}

return sizeMB;
}

public String getDatacenterFolder() {


return clientInfo.getArg(ARG_DATACENTERFOLDER);
}

public String getHostFolder() {


return clientInfo.getArg(ARG_HOSTFOLDER);
}

public String getCreateOnHost() {


return clientInfo.getArg(ARG_CREATEONHOST);
}

www.vmware.com
220
C H A P T E R 1 2 Java Code Examples for Advanced Operations

public String getAnnotation() {


String vmanote = clientInfo.getArg(ARG_ANNOTATION);
if (vmanote == null) {
vmanote = "VirtualMachine Annotation";
}
return vmanote;
}

public String getDiskFileName() {


return clientInfo.getArg(ARG_DISKFILENAME);
}

public void runDelegate() throws Exception {


doCreateVm();
}

public void doCreateVm() throws Exception {


try {
ManagedObjectReference dcmor =
_vmUtils.getDatacenter(getDatacenterFolder());

ManagedObjectReference hostfoldermor =
_vmUtils.getHostFolder(dcmor);
ManagedObjectReference compresmor =
_vmUtils.getComputeResource(hostfoldermor);
ManagedObjectReference hostmor = _vmUtils.getHost(hostfoldermor,
getCreateOnHost());

ManagedObjectReference resourcePool =
_vmUtils.getResourcePool(compresmor);

ManagedObjectReference vmFolderMor = _vmUtils.getVmFolder(dcmor);

// may want to pass in DiskFilename later.


VirtualMachineConfigSpec vmConfigSpec =
_vmUtils.createVmConfigSpec(getVmName(),
null, compresmor, hostmor);

// user specified VM information


vmConfigSpec.setName(getVmName());
vmConfigSpec.setAnnotation(getAnnotation());
vmConfigSpec.setMemoryMB(new Long(getMemorySizeMB()));
vmConfigSpec.setNumCPUs(new Integer(getCpuCount()));
vmConfigSpec.setGuestId(getGuestOsId());

221
VMware Infrastructure SDK Programming Guide

ManagedObjectReference taskmor =
clientInfo.getConnection().getService().createVM_Task(
vmFolderMor, vmConfigSpec, resourcePool, hostmor
);

// If we get a valid task reference, monitor the task for success or


// failure and report task completion or failure.
if (taskmor != null) {
log.logLine("Got Valid Task Reference");

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 } }
);

// Wait till the task completes.


if (result[0].equals(TaskInfoState.success)) {
log.logLine(clientInfo.getAppName() +
" : Successful creating : " + getVmName());
} else {
log.logLine(clientInfo.getAppName() +
" : Failed creating : " + getVmName());
if (result.length == 2 && result[1] != null) {
if (result[1] instanceof MethodFault) {
clientInfo.getUtil().logFault((MethodFault)result[1]);
}
}
}
}
} catch (Exception e) {
clientInfo.getUtil().logException(e);
log.logLine(clientInfo.getAppName() + " : Failed creating : " +
getVmName());
throw e;
}
}

public static void main(String[] args) throws Exception {


VmCreate app = new VmCreate("VmCreate", args);

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.

Cloning a Virtual Machine as a Template


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference folderMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToFolder);

/**
* 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);

VirtualMachineCloneSpec vmCSpec = new VirtualMachineCloneSpec();


vmCSpec.setLocation(vmRelocSpec);
vmCSpec.setTemplate(Boolean=TRUE);
vmCSpec.setPowerOn(Boolean=FALSE);

ManagedObjectReference taskMoRef = _service.cloneVM_Task(vmMoRef,


folderMoRef, new String("Templ_1"), vmCSpec);

www.vmware.com
224
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Marking an Existing Virtual Machine as a Template


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), args[3]);

_service.MarkAsTemplate(vmMoRef);

...
}
}

225
VMware Infrastructure SDK Programming Guide

Performing Power Operations on a Virtual


Machine
The following sample code snippets illustrates powering on, powering off, or suspending a virtual
machine.
{
...
{
// 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);
...
}
}

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

/* The PropertySpec defines the type of managed objects


/ for which you are looking and the property of those
/ managed objects, in this case info.state.
*/

PropertySpec pSpec = new PropertySpec();


pSpec.setAll(false);
pSpec.setType("Task");
pSpec.setPathSet(new String[] {"info.state"});

ObjectSpec oSpec = new ObjectSpec();


oSpec.setObj(taskMoRef);

PropertyFilterSpec pfSpec = new PropertyFilterSpec();


pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
pfSpec.setPropSet(new PropertySpec[] { pSpec });

227
VMware Infrastructure SDK Programming Guide

do {
ObjectContent[] objs = __service.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });

if(objs == null)
return null;

DynamicProperty[] dProps = objs[0].propSet;

System.out.println("Current state is: " + dProps[0].val);


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("Task completed successfully.");

...

}
}

www.vmware.com
228
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Formatting Event Messages


As described in Formatting Event Messages on page 160, you can use the fullFormattedMessage
property of the Event object for an event message string or you can define your own string based
on the context. The following code sample snippet illustrates how you can define according to
context.
Note: You can find a complete, compilable code sample in the \SDK\Samples_2_0 directory.

{
...
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();

// Map between event type and details


Hashtable eventDetail = new Hashtable();
for(int i=0; i<eventDetails.length; ++i) {
eventDetail.put(eventDetails[i].getKey(), eventDetails[i]);
}

// Get the 'latestEvent' property of the EventManager


oc = getObjectProperties(_propCollector,
_eventManager,
"latestEvent");

Event anEvent = (Event)oc[0].getPropSet(0).getVal();


System.out.println("The latestEvent was: " +
anEvent.getClass().getSimpleName());
System.out.println(formatEvent(Vm, eventDetail, anEvent));
System.out.println(formatEvent(Host, eventDetail, anEvent));
System.out.println(formatEvent(ComputeResource,

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>

String formatEvent(int fType, Hashtable eventDetail, Event theEvent)


{
// EventDescriptionEventDetail contains format strings and category
// for the event.
// There are 5 format strings to use depending on which context:
// formatOnComputeResource - Used for the ComputeResource (Usually
// a cluster) context
// formatOnDatacenter - Used for the Datacenter context
// formatOnHost - Used for the HostSystem context
// formatOnVm - Used for the VirtualMachine context
// fullFormat - Used for a fully qualified context

// 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

// formatOnComputeResource - "{vm.name} on {host.name} is powered


// on"
// formatOnDatacenter - "{vm.name} on {host.name} is powered
// on"
// formatOnHost - "{vm.name} is powered on"
// formatOnVm - "Virtual machine on {host.name} is
// powered on"
// fullFormat - "{vm.name} on {host.name} in
// {datacenter.name} is powered on"

// The messages for the Event type 'VmRenamedEvent' are:


// formatOnComputeResource - "Renamed {vm.name} from {oldName} to
{newName}"
// formatOnDatacenter - "Renamed {vm.name} from {oldName} to
{newName}"
// formatOnHost - "Renamed {vm.name} from {oldName} to
// {newName}"
// formatOnVm - "Renamed from {oldName} to {newName}"
// fullFormat - "Renamed {vm.name} from {oldName} to
// {newName} in {datacenter.name}"

// To handle the various event types, you need to create


// code that covers each specific event type you want to format.

String typeName = theEvent.getClass().getSimpleName();


EventDescriptionEventDetail detail =
(EventDescriptionEventDetail)eventDetail.get(typeName);

// Determine format string


String format = detail.getFullFormat();
switch (fType)
{
case ComputeResource:
format = detail.getFormatOnComputeResource();
break;
case Datacenter:
format = detail.getFormatOnDatacenter();
break;
case Host:
format = detail.getFormatOnHost();
break;
case Vm:
format = detail.getFormatOnVm();
break;
}

if("VmPoweredOnEvent".equals(typeName)) {

231
VMware Infrastructure SDK Programming Guide

return replaceText(format, (VmPoweredOnEvent)theEvent);


} else if("VmRenamedEvent".equals(typeName)) {
return replaceText(format, (VmRenamedEvent)theEvent);
} else if("UserLoginSessionEvent".equals(typeName)) {
return replaceText(format, (UserLoginSessionEvent)theEvent);
} else {
// Try generic, if all values are replaced by base type
// return that, else return fullFormattedMessage;
String ret = replaceText(format, theEvent);
if(ret.length()==0 || ret.indexOf("{") != -1)
ret = theEvent.getFullFormattedMessage();
return ret;
}
}

String replaceText(String format, UserLoginSessionEvent theEvent)


{
// Do base first
format = replaceText(format, (Event)theEvent);
// Then specific values
format = format.replace("{ipAddress}", theEvent.getIpAddress());
return format;
}

String replaceText(String format, VmPoweredOnEvent theEvent)


{
// Same as base type
return replaceText(format, (Event)theEvent);
}

String replaceText(String format, VmRenamedEvent theEvent)


{
// Do base first
format = replaceText(format, (Event)theEvent);
// Then specific values
format = format.replace("{oldName}", theEvent.getOldName());
format = format.replace("{newName}", theEvent.getNewName());
return format;
}

String replaceText(String format, Event theEvent)


{
format = format.replace("{userName}", theEvent.getUserName());
if(theEvent.getComputeResource() != null)
format = format.replace("{computeResource.name}",
theEvent.getComputeResource().getName());
if(theEvent.getDatacenter() != null)

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

Resetting a Virtual Machine


As described in Resetting a Virtual Machine on page 79, you can use the ResetVM_Task operation
to power off, then power on a virtual machine. The following code fragment illustrates how clients
call the ResetVM_Task operation, and how the client can monitor the resulting task to determine
when the operation completes.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference vmMoRef =
_service.findByInventoryPath(_sic.getSearchIndex(), PathToVm);

ManagedObjectReference taskMoRef = _service.resetVM_Task(vmMoRef);

/* The PropertySpec defines the type of managed objects


/ for which you are looking and the property of those
/ managed objects, in this case info.state.
*/

PropertySpec pSpec = new PropertySpec();


pSpec.setAll(false);
pSpec.setType("Task");
pSpec.setPathSet(new String[] {"info.state"});

ObjectSpec oSpec = new ObjectSpec();


oSpec.setObj(taskMoRef);

PropertyFilterSpec pfSpec = new PropertyFilterSpec();


pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
pfSpec.setPropSet(new PropertySpec[] { pSpec });

do {
ObjectContent[] objs = _service.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });

if(objs == null)
return null;

DynamicProperty[] dProps = objs[0].propSet;

System.out.println("Current state is: " + dProps[0].val);

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

Moving Virtual Machines Across Hosts


Migrating Virtual Machines on page 81 explains the various operations required to perform either a
hot or cold migration.

Migrating a Virtual Machine


As described in Migrating Virtual Machines on page 81, there are two ways to migrate virtual
machines: hot migration (using VMotion) and cold migration. The following application shows a
hot migration using MigrateVM_Task. The MigrateVM_Task operation can be used for both a hot
migration and a cold migration. Using MigrateVM_Task, however, does not move a virtual
machine’s virtual disk files.
{
...

{
// 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);
}
}

...
}
}

Moving a Virtual Machine’s Virtual Disks


As described in Migrating Virtual Machines on page 81, when you migrate a virtual machine to a
different host with the MigrateVM_Task operation, only the virtual machine’s configuration files are
moved. The virtual machine’s disk files remain in their original location. To move the disk files, you
use the the RelocateVM_Task operation.
{
/**
...

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.
...

ManagedObjectReference vmMoRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToVm);
ManagedObjectReference dcMoRef = _service.findByInventoryPath(
_sic.getSearchIndex(), PathToDatacenter);
ManagedObjectReference crMoRef = _service.findByInventoryPath(
_sic.getSearchIndex(), PathToComputeResource);

/**
* 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.
*/

ObjectSpec oSpec1 = new ObjectSpec();


oSpec.setObj(dcMoRef);

ObjectSpec oSpec2 = new ObjectSpec();


oSpec.setObj(crMoRef);

PropertySpec pSpec1 = new PropertySpec();


pSpec.setAll(false);
pSpec.setType("Datacenter");
pSpec.setPathSet("datastore");

PropertySpec pSpec2 = new PropertySpec();


pSpec.setAll(false);
pSpec.setType("ComputeResource");
pSpec.setPathSet("resourcePool");

PropertyFilterSpec pfSpec = new PropertyFilterSpec();


pfSpec.setObjectSet(new ObjectSpec[] { oSpec1, oSpec2 });
pfSpec.setPropSet(new PropertySpec[] { pSpec1, pSpec2 });

// Use the RetrieveProperties operation to get the property content.


ObjectContent[] objs = _service.retrieveProperties(
_sic.getPropertyCollector(),

239
VMware Infrastructure SDK Programming Guide

new PropertyFilterSpec[] { pfSpec });

// The propset property contains the datastore managed object


// reference.
DynamicProperty[] dProps = objs[0].propSet;

// The val property contains the managed object reference.


ManagedObjectReference dstoreMoRef = dProps[0].val;
ManagedObjectReference rpoolMoRef = dProps[1].val;

// Create a VirtualMachineRelocateSpec with the information obtained so


// so far.
VirtualMachineRelocateSpec vmReSpec = new VirtualMachineRelocateSpec();
vmReSpec.setDatastore(dstoreMoRef);
vmReSpec.setPool(rpoolMoRef);
vmReSpec.setTransform(VirtualMachineRelocateTransformation.flat);

// Now move the disks.


ManagedObjectReference taskMoRef = _service.relocateVM_Task(
vmMoRef,
vmReSpec);

...
}
}

www.vmware.com
240
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Responding to Virtual Machine Questions


The following code sample snippet illustrates how to answer virtual machine questions.

{
...

{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference vmMoRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToVm);

_service.answerVM(vmMoRef, questId, answer);


...
}
}

241
VMware Infrastructure SDK Programming Guide

Taking a Snapshot of a Virtual Machine


Snapshots on page 56 and Managing Virtual Machine Snapshots on page 84 provide detailed
information about the concepts and operations involved in managing snapshots. This section
provides a code sample snippet in which a snapshot is taken of a virtual machine.
{
...

{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference vmRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToVm);

boolean memory_files = true;


boolean quiesceFs = true;

ManagedObjectReference taskRef = _service.CreateSnapshot_Task(vmRef,


SnapName, SnapDescript, memory_files, quiesceFs);

...
}
}

www.vmware.com
242
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Creating and Deleting Inventory Objects


Inventory Management on page 47 describes the concepts involved in creating inventory objects
such as folders and datacenters. This section contains sample code for creating and deleting a
datacenter.
Note: For sample code that creates a virtual machine, see Creating and Configuring a Virtual
Machine on page 219.

Creating a Datacenter
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference dcfolderMoRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToDcFolder);
ManagedObjectReference dcenter =
_service.createDatacenter(dcfolderMoRef, DcName);

...
}
}

Deleting a Managed Entity


{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference meMoRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToMe);
ManagedObjectReference taskRef =
_service.destroy(meMoRef);

...
}
}

243
VMware Infrastructure SDK Programming Guide

Moving an Inventory Object


The following code sample moves one or more objects into a folder.
{
...
{
{
// Log on code. See Logging On to the Web Service on page 198.
...

ManagedObjectReference folderRef = _service.findByInventoryPath(


_sic.getSearchIndex(), PathToFolder);

ManagedObjectReference[] entities = new ManagedObjectReference[]();


for(int i=0; i<paths.length; i++) {
entities[i] = _service.findByInventoryPath(_sic.getSearchIndex(),
PathsToEntities[i]);
}

ManagedObjectReference taskRef = _service.moveIntoFolder(folderRef,


entities);

...
}
}

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

ManagedObjectReference taskRef = _service.Rename_Task(meRef, name);


...
}
}

245
VMware Infrastructure SDK Programming Guide

Monitoring Events and Alarms


Events, Tasks, and Alarms on page 49 and Managing Events, Tasks, and Alarms on page 151
describe the concepts and operations involved in monitoring events and alarms.

Creating and Monitoring Events with a HistoryCollector


The following sample illustrates how clients can monitor events as they occur. This sample collects
all the events associated with an entity, then displays the results based on keyboard input.
{
...

{
// Log on code. See Logging On to the Web Service on page 198.
...
// Find the managed entity.
ManagedObjectReference meRef = _service.findByInventoryPath(
_sic.getSearchIndex(), PathToEntity);

// Establish the entity as the one for the collection.


EventFilterSpecByEntity entitySpec = new EventFilterSpecByEntity();
entitySpec.setEntity(meRef);

/*
* 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);

// Build the EventFilterSpec object.


EventFilterSpec eFSpec = new EventFilterSpec();
eFSpec.setEntity(entitySpec);

// Now create the collector.


ManagedObjectReference eHistoryCollect =
_service.createCollectorForEvents(_sic.getEventManager(),
eFSpec);

// Read the results by entering "Next", "Previous", or "stop"


BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
String str;

www.vmware.com
246
C H A P T E R 1 2 Java Code Examples for Advanced Operations

System.out.println("Enter \'next\' to read the next collected


events.");
System.out.println("Enter \'prev\' to read the previous collected
events.");
System.out.println("Enter \'stop\' to exit.");

// Display certain properties of the results.


do {
str = br.readline();
if(str.equalsIgnoreCase("next"))
{
Event[] eventCollection = _service.readNextEvents(
eHistoryCollect, 100);
}
else if(str.equalsIgnoreCase("prev"))
{
Event[] eventCollection = _service.readPreviousEvents(
eHistoryCollect, 100);
}
else
{
break;
}

for(i = 0; i < eventCollection.length; i++)


{
system.out.print("Chain Id: " + eventCollection[i].chainId +
", ");
system.out.print("Event Id: " + eventCollection[i].key + ", ");
system.out.print("Date Created: " +
eventCollection[i].createdTime + ", ");
system.out.print("Event Description: " +
eventCollection[i].fullFormattedMessage ", ");
system.out.println("User: " + eventCollection[i].userName +
", ");
}
} while(true);

...
}
}

247
VMware Infrastructure SDK Programming Guide

Creating and Monitoring Alarms


The following figure shows CPU usage. The code sample snippet in this section creates an alarm
that is triggered on a virtual machine when its CPU usage rises above 90.

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

MetricAlarmExpression trigger = new MetricAlarmExpression();


trigger.setType("VirtualMachine");
trigger.setOperator(MetricAlarmOperator.isAbove);
trigger.setMetric(cpuMetric);
trigger.setRed(90);
trigger.setYellow(75);

/*
* 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");

// Define when the action should be triggered.


AlarmTriggeringAction triggerAction = new AlarmTriggeringAction();
triggerAction.setAction(meAction);
triggerAction.setGreen2Yellow(Boolean.FALSE);
triggerAction.setRed2Yellow(Boolean.FALSE);
triggerAction.setYellow2Green(Boolean.FALSE);
triggerAction.setYellow2Red(Boolean.TRUE);

// Create the alarm specification.


AlarmSpec aSpec = new AlarmSpec();
aSpec.setAction(triggerAction);
aSpec.setDescription("An alarm for powering off virtual machines
when CPU usage crosses a certain threshold.");
aSpec.setEnabled(Boolean.TRUE);
aSpec.setExpression(trigger);
aSpec.setName("Alarm for CPU Usage");
aSpec.setSetting(aSetting);

/*
* 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

ManagedObjectReference meRef = _service.FindByInventoryPath(


_sic.getSearchIndex(), PathToEntity);

ManagedObjectReference cpuAlarmRef = _service.createAlarm(


_sic.getAlarmManager(), meRef, aSpec);

...
}
}

www.vmware.com
250
C H A P T E R 1 2 Java Code Examples for Advanced Operations

Task Scheduling and Monitoring


Tasks on page 49 describes the concepts involved in task scheduling and monitoring. Managing
Tasks on page 153 describes the operations used for scheduling and monitoring. This section
contains code sample snippets illustrating the practical application of the information in those
sections.

Creating Scheduled Tasks


The following sample code illustrates creating a scheduled task that performs the power-on
operation.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
// Find the managed entity on which the action is performed.
ManagedObjectReference vmRef =
_service.FindByInventoryPath(_sic.getSearchIndex,
PathToVm);

// Define the argument for the method action.


MethodActionArgument[] maa = new MethodActionArgument();
maa.setValue(vmRef);

// Define the operation to be performed.


MethodAction ma = new MethodAction();
ma.setArgument(maa);
ma.setName("powerOnVM");

// Set the schedule for the action. When will it be performed?


DailyTaskScheduler dTScheduler = new DailyTaskScheduler();
dTScheduler.setHour(6);
dTScheduler.setMinute(30);

// Define the scheduled task specification.


ScheduledTaskSpec tSpec = new ScheduledTaskSpec();
tSpec.setDescription("Start virtual machine according to
prescribed schedule.");
tSpec.setEnabled(Boolean=TRUE);
tSpec.setName("Power On Virtual Machine");
tSpec.setAction(ma);
tSpec.setScheduler(dTScheduler);
tSpec.setNotification("admin@vmware.com");

251
VMware Infrastructure SDK Programming Guide

// Create the scheduled task.


_service.createScheduledTask(_sic.getScheduledTaskManager,
vmRef, tSpec);
...
}
}

Monitoring Scheduled Tasks


The following sample illustrates how the client can stay informed of all scheduled tasks in the
system.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
// Find the managed entity on which the action is performed.
ManagedObjectReference vmRef =
_service.FindByInventoryPath(_sic.getSearchIndex,
PathToVm);
ManagedObjectReference[] schedTasks[] =
_service.RetrieveEntityScheduledTask(_sic.getSearchIndex,
PathToVm);
...
}
}

Monitoring Non-Scheduled Tasks


The ManagedEntity managed object has a property called recentTask that represents the set of
recent tasks operating on a managed entity. The following code sample snippet illustrates a
PropertyFilterSpec that collects the recent tasks for a specified virtual machine.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
// Find the managed entity on which the action is performed.
ManagedObjectReference vmRef =
_service.FindByInventoryPath(_sic.getSearchIndex,
PathToVm);

/* The PropertySpec defines the type of managed objects


/ for which you are looking and the property of those
/ managed objects, in this case info.state.
*/

www.vmware.com
252
C H A P T E R 1 2 Java Code Examples for Advanced Operations

PropertySpec pSpec = new PropertySpec();


pSpec.setAll(false);
pSpec.setType(“VirtualMachine”);
pSpec.setPathSet(new Task[] {“recentTask”});

/* The ObjectSpec defines the starting point for the


/ collection, in this case the specific VirtualMachine managed
/ object reference. Notice
/ that the skip property is set to false. This means
/ that the program checks the starting object to see if
/ it is the managed object type defined in the PropertySpec.
/ Because the code contains no selectSet property,
/ this is the only object that is checked.
*/
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(vmMoRef);

// Constructing the PropertyFilterSpec


PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setObjectSet(new ObjectSpec[] { oSpec });
pfSpec.setPropSet(new PropertySpec[] { pSpec });

// Retrieve the results of the collection.


ObjectContent[] objs = _service.retrieveProperties(
_sic.getPropertyCollector,
new PropertyFilterSpec[] { pfSpec });
if (objs == null)
return null;
DynamicProperty[] dProps = objs[0].propSet;
if (dProps == null)
return null;
return dProps[0].val;
}
...
}

Ending a Task
You can use CancelTask to cancel either a scheduled task or a task resulting from an invoked
operation.

Cancelling a Task Resulting from an Operation


The code sample snippet in Creating and Configuring a Virtual Machine on page 219 returns a Task
managed object reference. If necessary, you can use that managed object reference to cancel the
running task.

253
VMware Infrastructure SDK Programming Guide

{
...
{
// Log on code. See Logging On to the Web Service on page 198.
...
_service.cancelTask(taskMoRef);
}
...
}

Cancelling a Scheduled Task


You might want to cancel a current or upcoming run of a scheduled task. To cancel an upcoming
run, use ReconfigureScheduledTask to modify the schedule. To cancel a current run, use a property
collector to find the appropriate Task managed object reference, as shown in the following code
sample snippet.
{
...
{
// Log on code. See Logging On to the Web Service on page 198.

PropertySpec pspec = new PropertySpec();


pspec.setType("ScheduledTask");
pspec.setAll(Boolean.FALSE);
pspec.setPathSet(new String[] {"info.activeTask", "info.name"});

ObjectSpec ospec = new ObjectSpec();


ospec.setObj(_sic.getScheduledTaskManager());
ospec.setSkip(Boolean.TRUE);

TraversalSpec tspec = new TraversalSpec();


tspec.setType("ScheduledTaskManager");
tspec.setPath("scheduledTask");

ospec.setSelectSet(new SelectionSpec[] {tspec});

PropertyFilterSpec pfspec = new PropertyFilterSpec();


pfspec.setPropSet(new PropertySpec[] {pspec});
pfSpec.setObjectSet(new ObjectSpec[] {ospec});

ObjectContent[] objs = _service.RetrieveProperties(


_sic.getPropertyCollector,
new PropertyFilterSpec[] {pfspec});

// Find the scheduled task that you want to cancel.

www.vmware.com
254
C H A P T E R 1 2 Java Code Examples for Advanced Operations

if(objs == null)
return null;

//For each ScheduledTask found


for(int x=0; x < objs.length; ++x) {
ObjectContent oc = objs[x];
if(oc != null && oc.getPropSet() != null) {
DynamicProperty[] pSets = oc.getPropSet();
ManagedObjectReference activeTask = null;
String taskName = null;

// For each property collected from the ScheduledTask


for(int ps=0; ps < pSets.length; ++ps) {
DynamicProperty dp = pSets[ps];
if(dp.getName().equals("info.activeTask") {
activeTask = (ManagedObjectReference)dp.getVal();
} else if(dp.getName().equals("info.name") {
taskName = (String)dp.getVal();
}
}

// Check if it's the ScheduledTask you want to cancel


if(activeTask != null && "nameOfTaskToStop".equals(taskName) {
_service.CancelTask(activeTask);
break;
}
}
}
}
}

255
VMware Infrastructure SDK Programming Guide

Exception Handling and Faults


The Web service can encounter an exception or error (also referred to as a fault) while executing an
operation. We previously described how these exceptions can occur (Handling Exceptions in the
Data Synchronization Loop on page 215). Details about these errors are encapsulated in a
MethodFault object or an object derived from MethodFault. See the VMware Infrastructure SDK
Reference Guide for specific details about the derived faults.

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

Logging On to the Web Service


Logging On on page 61 describes the concepts behind the code for logging on. The following
sample illustrates how to log into the Web service.
System.Net.ServicePointManager.CertificatePolicy = new CertPolicy();
ManagedObjectReference _svcRef = new ManagedObjectReference();
_svcRef.type = "ServiceInstance";
_svcRef.Value = "ServiceInstance";

VimService _service = new VimService();


_service.Url = "https://<your_server>/sdk";
_service.CookieContainer = new System.Net.CookieContainer();

ServiceContent _sic = _service.retrieveServiceContent(_svcRef);


_service.Login(_sic.sessionManager, username, password, null);

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

Accessing the Managed Object Browser


To access the Managed Object Browser, enter the following URL in the browser’s address field:
protocol://<your_server>/mob. The browser displays the home page for the Managed
Object Browser.
Note: For information about configuring for the http or https protocol, see Setting up the
VMware Infrastructure SDK Client on page 25.

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

Viewing Task Information with the Managed


Object Browser
After you have accessed the browser (as described in Accessing the Managed Object Browser on
page 260), you can examine the contents of any of the objects on the server. For example, if you
wanted to examine recent tasks, you could click the TaskManager link (for the taskManager
property) in the ServiceContent data object screen. This displays the properties of the
TaskManager managed object, including recentTask.

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.

Cluster compute resource


An extended ComputeResource that represents a cluster of hosts available for backing virtual
machines.

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.

Guest operating system


An operating system that runs inside a virtual machine.

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.

Microsoft SOAP Toolkit


The Microsoft Simple Object Access Protocol (SOAP) Toolkit 2.0 comprises a client-side
component, a server-side component and other components that construct, transmit, read, and
process SOAP messages. This toolkit also provides additional tools that simplify application
development.

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

See also Resume.


To return a suspended virtual machine to operation, use the resume feature.s

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.

Virtual machine configuration


The specification of what virtual devices (such as disks and memory) are present in a virtual
machine and how they are mapped to host files and devices.

Virtual machine configuration file


A file containing a virtual machine configuration. It is created when you create the virtual machine.
It is used by SDK to identify and run a specific virtual machine.

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.

VMware ESX Server file system


A file system that is optimized for storing virtual machines. Also referred to as VMFS.

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.

Cancelling the Operation


UpgradeTools_Task returns a Task object. If the operations fails to return, you can use the
unMountToolsInstaller operation to cancel the operation. This operation takes as its only
parameter a reference to the VirtualMachine managed object.

www.vmware.com
276
A P P E N D I X A Upgrading VMware Tools

Upgrading VMware Tools for a Single Virtual


Machine – Java Example
The following Java code uses an inventory path to find a reference to a single virtual machine
managed object, then tests that virtual machine to see if it’s Tools satisfies the criteria for
upgrading. If the Tools passes the test, the application invokes UpgradeTools_Task on that single
virtual machine.
import java.net.URL;
import javax.xml.rpc.Stub;

// the VirtualInfrastructureManagement Client side stubs


import com.vmware.vim.*;

/**
* 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 {

protected VimServiceLocator _locator;


protected VimPortType _service;
protected int _svcState;
protected ServiceContent _sic;
protected ManagedObjectReference _svcRef;
protected ManagedObjectReference _vmRef;
protected ManagedObjectReference _sindex;
protected ManagedObjectReference _propCol;

/**
* 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");

// could be ServiceInstance for "HostAgent" and "VPX" for VPXd


_svcRef.set_value("ServiceInstance");
}

/**

277
VMware Infrastructure SDK Programming Guide

* 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();
}

_locator = new VimServiceLocator();


_locator.setMaintainSession(true);
_service = _locator.getVimPort(new URL(urlStr));

_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

_vmRef = _service.findByInventoryPath(_sindex, _invPath);

PropertySpec[] propspecary = new PropertySpec[] { new PropertySpec() };


propspecary[0].setAll(new Boolean(false));
propspecary[0].setPathSet(new String[] { "disabledMethod" });
propspecary[0].setType("VirtualMachine");

PropertyFilterSpec spec = new PropertyFilterSpec();


spec.setPropSet(propspecary);
spec.setObjectSet(new ObjectSpec[] { new ObjectSpec() });
spec.getObjectSet(0).setObj(_vmRef);
spec.getObjectSet(0).setSkip(new Boolean(false));

ObjectContent[] ocary = _service.retrieveProperties(


_propCol, new PropertyFilterSpec[] { spec }
);
if (ocary != null) {
ObjectContent oc = null;
ManagedObjectReference mor = null;
DynamicProperty[] pcary = null;
DynamicProperty pc = null;
for (int oci = 0; oci < ocary.length; oci++) {
oc = ocary[oci];
mor = oc.getObj();
pcary = oc.getPropSet();

boolean UpgradeOK = true;


if (pcary != null) {
for (int pci = 0; pci < pcary.length; pci++) {
pc = pcary[pci];
if (pc != null) {
String[] pci2 = (String[])pc.getVal();
for (int x = 0 ; x < pci2.length; x++){
if (pci2[x].equals("UpgradeTools_Task")) {
UpgradeOK = false;
}
}
} else {
ManagedObjectReference upgradeTask =
_service.upgradeTools_Task(_vmRef, null);
}
}
}
if(UpgradeOK) {
ManagedObjectReference upgradeTask =
_service.upgradeTools_Task(_vmRef, null);
} else

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>"
);
}

toolsUpgrade1 tu1 = new toolsUpgrade1();

try {
// Create the Service Managed Object Reference
tu1.createServiceRef();

// Connect to the Service


tu1.connect(args[0], args[1], args[2]);

// Retrieve virtual machine and check for upgrade-ability.


// If upgrade-able, then invoke the operation.
tu1.upgrade(args[3]);

// Disconnect from the WebService


tu1.disconnect();
} catch (Exception e) {
System.out.println("Caught Exception : " +
" Name : " + e.getClass().getName() +
" Message : " + e.getMessage() +
" Trace : ");
e.printStackTrace();
}
}
}

www.vmware.com
280
A P P E N D I X A Upgrading VMware Tools

Upgrading VMware Tools in Batch – Java


Example
The following Java code uses a property collector and iterates over the virtual machine inventory
to find all the virtual machines whose disabledMethod property does not include
UpgradeTools_Task. The code invokes UpgradeTools_Task on each virtual machine that satisfies
this criteria.
import java.net.URL;

// the VirtualInfrastructureManagement Client side stubs


import com.vmware.vim.*;

/**
* 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 {

protected VimServiceLocator _locator;


protected VimPortType _service;
protected ServiceContent _sic;
protected ManagedObjectReference _svcRef;

protected ManagedObjectReference _propCol;


protected ManagedObjectReference _rootFolder;

/**
* 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");

// could be ServiceInstance for "HostAgent" and "VPX" for VPXd


_svcRef.set_value("ServiceInstance");
}

/**
* Creates an instance of the VMA proxy and establishes a connection
*

281
VMware Infrastructure SDK Programming Guide

* @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();
}

_locator = new VimServiceLocator();


_locator.setMaintainSession(true);
_service = _locator.getVimPort(new URL(urlStr));

_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 {

TraversalSpec datacenterVmTraversalSpec = new TraversalSpec();


datacenterVmTraversalSpec.setName("datacenterVmTraversalSpec");
datacenterVmTraversalSpec.setType("Datacenter");
datacenterVmTraversalSpec.setPath("vmFolder");
datacenterVmTraversalSpec.setSkip(new Boolean(false));

www.vmware.com
282
A P P E N D I X A Upgrading VMware Tools

datacenterVmTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });

TraversalSpec folderTraversalSpec = new TraversalSpec();


folderTraversalSpec.setName("folderTraversalSpec");
folderTraversalSpec.setType("Folder");
folderTraversalSpec.setPath("childEntity");
folderTraversalSpec.setSkip(new Boolean(false));
folderTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec"),
datacenterVmTraversalSpec });

PropertySpec[] propspecary = new PropertySpec[] { new PropertySpec() };


propspecary[0].setAll(new Boolean(false));
propspecary[0].setPathSet(new String[] { "disabledMethod" ,
"config.name" });
propspecary[0].setType("VirtualMachine");

PropertyFilterSpec spec = new PropertyFilterSpec();


spec.setPropSet(propspecary);
spec.setObjectSet(new ObjectSpec[] { new ObjectSpec() });
spec.getObjectSet(0).setObj(_rootFolder);
spec.getObjectSet(0).setSkip(new Boolean(false));
spec.getObjectSet(0).setSelectSet( new SelectionSpec[] {
folderTraversalSpec });

// Recursively get all the VirtualMachine ManagedObjectReferences


// and the name and disabledMethod properties for all
// VirtualMachines retrieved
ObjectContent[] ocary =
_service.retrieveProperties(
_propCol, new PropertyFilterSpec[] { spec }
);

// If we get contents back. upgrade tools if able


if (ocary != null) {
ObjectContent oc = null;
ManagedObjectReference vmRef = null;
DynamicProperty[] pcary = null;
DynamicProperty pc = null;
for (int oci = 0; oci < ocary.length; oci++) {
oc = ocary[oci];
vmRef = oc.getObj();
pcary = oc.getPropSet();

String vmName = "";


boolean UpgradeOk = true;

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>"
);
}

toolsUpgrade tu = new toolsUpgrade();

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

// Connect to the Service


tu.connect(args[0], args[1], args[2]);

// Find all virtual machines, check for upgrade-ability.


// Upgrade tools if they are upgrade-able.
tu.upgradeTools();

// Disconnect from the WebServcice


tu.disconnect();
} catch (Exception e) {
System.out.println("Caught Exception : " +
" Name : " + e.getClass().getName() +
" Message : " + e.getMessage() +
" Trace : ");
e.printStackTrace();
}
}
}

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

Counter Information Categories


Each performance counter contains information in the following categories:
• unit: The statistic's units. Some examples of possible types of units include percent,
millisecond, or KB.
• description: A textual description of the performance counter, potentially including
information about what value it reports.
• statistic type: 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.
• rollup type: 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.
• entity: Entities from which the performance counter is collected. This can include virtual
machines, hosts, clusters, or resource pools. The performance counter is collected for each
device (cpu, NIC, etc.) instance only, as the sum of all device instances, or both.

www.vmware.com
288
A P P E N D I X B Performance Counters

Most Useful Performance Counters


The following tables list the most useful performance counters in the VMware Infrastructure SDK.
See Complete List of Performance Counters on page 292 for a complete list of metrics.

CPU Usage (Group: cpu)


This table contains the values for each category of the counters that measure CPU performance

Counter Unit Description Statistic Rollup Type Entity


Name Type
usage Percentage, precision to CPU usage as a rate average, host, virtual
1/100 percentage point. percentage over the minimum, machine
1 = 0.01%. A value interval of collection maximum
between 0 and 10000
usagemhz MHz CPU usage in MHz over rate average, host, virtual
the interval of collection minimum, machine, compute
maximum resources and
resource pools

Disk Performance (Group: disk)


This table contains the values for each category of the counters that measure disk performance

Counter Unit Description Statistic Rollup Type Entity


Name Type
usage KBps The sum of the data read rate average, host, virtual
and written for all of the minimum, machine (aggregate
disk instances of the host maximum level only)
or virtual machine
read KBps Amount of data read in rate average host, virtual
the performance interval machine (per disk
instance only)
write KBps Amount of data written to rate average host, virtual
disk in the performance machine (per disk
interval instance only)

289
VMware Infrastructure SDK Programming Guide

Memory Performance (Group: mem)


This table contains performance counters that measure memory performance.

Counter Unit Description Statistic Rollup Type Entity


Name Type
usage Percentage, Memory currently in use. absolute average, host, virtual machine,
precision to 1/ This is active memory as a minimum, compute resources and
100 percentage percentage of total maximum resource pools
point. 1 = 0.01%. available memory
A value
between 0 and
10000
vmmemctl KB Amount of memory absolute average, virtual machine, and
currently used by the minimum, resource pools
virtual machine memory maximum
control
active KB Amount of memory that is absolute average, host, virtual machine,
actively used minimum, compute resources and
maximum resource pools
granted KB Amount of memory absolute average, host, virtual machine,
available for use minimum, compute resources and
maximum resource pools

Network Performance (Group: net)


This table contains the values for each category of the counters that measure Network
performance

Counter Unit Description Statistic Rollup Type Entity


Name Type
usage KBps The sum of data rate average, host, virtual machine
transmitted and received minimum, (aggregate level only)
for all the NIC instances of maximum
the host or virtual machine
transmitted KBps Amount of data rate average host, virtual machine (per
transmitted in the NICinstance only)
performance interval
received KBps Amount of data received in rate average host, virtual machine (per
the performance interval NIC instance only)

www.vmware.com
290
A P P E N D I X B Performance Counters

System Performance (Group: sys)


This table contains performance counters that measure system performance.

Counter Unit Description Statistic Rollup Type Entity


Name Type
uptime seconds Number of seconds since absolute latest host, virtual machine
system startup

291
VMware Infrastructure SDK Programming Guide

Complete List of Performance Counters


Most Useful Performance Counters on page 289 lists counters that are most useful for monitoring
performance. The following tables contain a complete list of performance counters.

CPU Usage (Group: cpu)


This table contains the values for each category of the counters that measure CPU performance.

Counter Name Unit Description Statistic Rollup Type Entity


Type
usage Percentage, CPU usage as a rate average, host, virtual
precision to percentage over the minimum, machine
1/100 percentage interval of collection maximum
point. 1 = 0.01%.
A value between
0 and 10000
usagemhz MHz CPU usage in MHz over rate average, host, virtual
the interval of collection minimum, machine, compute
maximum resources and
resource pools
system millisecond CPU time spent on system delta summation virtual machine
processes (per cpu instance
only)
wait millisecond CPU time spent on wait delta summation virtual machine
state (per cpu instance
only)
ready millisecond CPU time spent on ready delta summation virtual machine
state (per cpu instance
only)
extra millisecond CPU time that is extra delta summation virtual machine
(per cpu instance
only)
used millisecond CPU time that is used delta summation virtual machine
(per cpu instance
only)
guaranteed millisecond CPU time that is delta summation virtual machine
guaranteed for the virtual (per cpu instance
machine only)

www.vmware.com
292
A P P E N D I X B Performance Counters

Counter Name Unit Description Statistic Rollup Type Entity


Type
reservedCapacity MHz The sum of the absolute average host
reservation properties of
the (immediate) children
of the host's root resource
pool. For details, see
Configuring Resource
Pools with the
ResourceConfigSpec on
page 92.

CPU Utilization for Resources (Group: rescpu)


This table contains performance counters that measure CPU performance related to average
active time, peak active time and average run time over 1 minute, 5 minutes and 15 minutes.

Counter Name Unit Description Statistic Rollup Type Entity


Type
actav1 percent The average active absolute latest host, virtual machine
time for the CPU over
the past minute
actav5 percent The average active absolute latest host, virtual machine
time for the CPU over
the past five minutes
actav15 percent The average active absolute latest host, virtual machine
time for the CPU over
the past fifteen
minutes
actpk1 percent The peak active time absolute latest host, virtual machine
for the CPU over the
past minute
actpk5 percent The peak active time absolute latest host, virtual machine
for the CPU over the
past five minutes
actpk15 percent The peak active time absolute latest host, virtual machine
for the CPU over the
past fiften minutes
runav1 percent The average runtime delta latest host, virtual machine
for the CPU over the
past minute

293
VMware Infrastructure SDK Programming Guide

Counter Name Unit Description Statistic Rollup Type Entity


Type
runav5 percent The average run time absolute latest host, virtual machine
for the CPU over the
past five minutes
runav15 percent The average run time absolute latest host, virtual machine
for the CPU over the
past fifteen minutes
runpk1 percent The peak active time absolute latest host, virtual machine
for the CPU over the
past minute
runpk5 percent The peak runtime for absolute latest host, virtual machine
the CPU over the past
five minutes
runpk15 percent The peak runtime for absolute latest host, virtual machine
the CPU over the past
15 minutes
maxLimited1 percent The scheduling limit absolute latest host, virtual machine
over the past minute
maxLimited5 percent The scheduling limit absolute latest host, virtual machine
over the past 5
minutes
maxLimited15 percent The scheduling limit absolute latest host, virtual machine
over the past 15
minutes
sampleCount number The sample CPU absolute latest host, virtual machine
count
samplePeriod millisecond The sample period absolute latest host, virtual machine

Memory Performance (Group: mem)


This table contains performance counters that measure memory performance.

Counter Name Unit Description Statistic Rollup Type Entity


Type
usage Percentage, Memory currently in absolute average, host, virtual machine,
precision to 1/ use. This is active minimum, compute resources
100 percentage memory as a maximum and resource pools
point. 1 = 0.01%. percentage of total
A value between available memory
0 and 10000

www.vmware.com
294
A P P E N D I X B Performance Counters

Counter Name Unit Description Statistic Rollup Type Entity


Type
vmmemctl KB Amount of memory absolute average, virtual machine, and
currently used by the minimum, resource pools
virtual machine maximum
memory control
active KB Amount of memory absolute average, host, virtual machine,
that is actively used minimum, compute resources
maximum and resource pools
granted KB Amount of memory absolute average, host, virtual machine,
available for use minimum, compute resources
maximum and resource pools
shared KB Amount of shared absolute average, host, virtual machine,
memory minimum, compute resources
maximum and resource pools
zero KB Zero memory absolute average, host, virtual machine,
minimum, compute resources
maximum and resource pools
unreserved KB Amount of unreserved absolute average, host, compute
memory minimum, resources
maximum
swapunreserved KB Amount of unreserved absolute average, host, compute
swap space minimum, resources
maximum
swapused KB Amount of memory absolute average, host, compute
used for swap space minimum, resources
maximum
sharedcommon KB Amount of shared, absolute average, host, compute
common memory minimum, resources
maximum
heap KB Amount of memory absolute average, host, compute
allocated for heap minimum, resources
maximum
heapfree KB Free space in the heap absolute average, host, compute
minimum, resources
maximum
state number Memory state absolute latest host, compute
resources

295
VMware Infrastructure SDK Programming Guide

Counter Name Unit Description Statistic Rollup Type Entity


Type
swapped KB Amount of memory absolute average, virtual machine,
being swapped minimum, resource pools
maximum
swaptarget KB Amount of memory absolute average, virtual machine,
that can be swapped minimum, resource pools
maximum
swapin KB Amount of memory absolute average, virtual machine,
swapped in minimum, resource pools
maximum
swapout KB Amount of memory absolute average, virtual machine,
swapped out minimum, resource pools
maximum
vmmemctltarget KB Amount of memory absolute average, virtual machine,
that can be used by minimum, resource pools
the virtual machine maximum
memory control
consumed KB Amount of host absolute average, virtual machine,
memory consumed by minimum, resource pools
the virtual machine for maximum
guest memory
overhead KB Amount of memory absolute average, host, virtual machine,
that is overhead minimum, compute resources
maximum and resource pools
reservedCapacity MB The sum of the absolute average host
reservation properties
of the (immediate)
children of the host's
root resource pool. For
details, see Configuring
Resource Pools with
the
ResourceConfigSpec
on page 92.

www.vmware.com
296
A P P E N D I X B Performance Counters

Network Performance (Group: net)


This table contains the values for each category of the counters that measure network
performance.

Counter Name Unit Description Statistic Rollup Type Entity


Type
usage KBps The sum of data rate average, host, virtual machine
transmitted and minimum, (aggregate level only)
received for all the maximum
NIC instances of the
host or virtual
machine
transmitted KBps Amount of data rate average host, virtual machine
transmitted in the (per NICinstance only)
performance interval
received KBps Amount of data rate average host, virtual machine
received in the (per NIC instance only)
performance interval
packetRx number Number of packets delta summation host, virtual machine
received in the (per net instance only)
performance interval
packetTx number Number of packets delta summation host, virtual machine
transmitted in the (per net instance only)
performance interval

Disk Performance (Group: disk)


This table contains the values for each category of the counters that measure disk performance.

Counter Name Unit Description Statistic Rollup Type Entity


Type
usage KBps The sum of the data rate average, host, virtual machine
read and written for minimum, (aggregate level only)
all of the disk maximum
instances of the host
or virtual machine
read KBps Amount of data read rate average host, virtual machine
in the performance (per disk instance only)
interval
write KBps Amount of data rate average host, virtual machine
written to disk in the (per disk instance only)
performance interval

297
VMware Infrastructure SDK Programming Guide

Counter Name Unit Description Statistic Rollup Type Entity


Type
numberRead number Number of times data delta summation host, virtual machine
was read from the (per disk instance only)
disk in the defined
interval
numberWrite number Number of times data delta summation host, virtual machine
was written to the (per disk instance only)
disk in the defined
interval

System Performance (Group: sys)


This table contains performance counters that measure system performance.

Counter Name Unit Description Statistic Rollup Type Entity


Type
uptime seconds Number of seconds absolute latest host, virtual machine
since system startup
resourceCpuUsage MHz Resource CPU usage rate average, host, virtual machine
minimum,
maximum
heartbeat number Number of heartbeats delta summation host, virtual machine
from the virtual
machine in the
defined interval

Cluster Services Metrics (Group: clusterServices)


This table contains the values for each category of the counters that measure cluster services.

Counter Name Unit Description Statistic Rollup Type Entity


Type
cpufairness number An integer between 1 absolute latest host
and 100 representing
the percentage of
CPU resources
allocated.
memfairness number An integer between 1 absolute latest host
and 100 representing
the percentage of
memory resources
allocated.

www.vmware.com
298
A P P E N D I X B Performance Counters

Counter Name Unit Description Statistic Rollup Type Entity


Type
effectivecpu MHz VMware DRS Effective rate average compute
CPU resources resources
available
effectivemem KB VMware DRS Effective absolute average compute
Memory resources resources
available
failover number VMware HA Number absolute latest compute
of failures that can be resources
tolerated

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.

Privileges and Operations


The following table lists the privileges required to perform operations. In some cases, the privilege
required is dynamic and depends on several factors. For these operations, see the discussion of the
operation in the VMware Infrastructure SDK Reference Guide.
The table also includes whether the operation is supported on VirtualCenter, ESX Server, or both.

Operation Privilege VC ESX


AcquireLocalTicket System.Anonymous X X
AcquireMksTicket VirtualMachine.Interact.ConsoleInteract X X
AddAuthorizationRole Authorization.ModifyRoles X X
AddCustomFieldDef Global.ManageCustomFields X
AddHost_Task Host.Inventory.AddHostToCluster X

301
VMware Infrastructure SDK Programming Guide

Operation Privilege VC ESX


AddInternetScsiSendTargets Host.Config.Storage X X
AddInternetScsiStaticTargets Host.Config.Storage X X
AddPortGroup Host.Config.Network X X
AddServiceConsoleVirtualNic Host.Config.Network X X
AddStandaloneHost_Task Host.Inventory.AddStandaloneHost X
AddVirtualNic Host.Config.Network X X
AddVirtualSwitch Host.Config.Network X X
AnswerVM VirtualMachine.Interact.AnswerQuestion X X
ApplyRecommendation Resource.ApplyRecommendation X
AssignUserToGroup Host.Local.ManageUserGroups X X
AttachVmfsExtent Host.Config.Storage X X
AutoStartPowerOff Host.Config.AutoStart X X
AutoStartPowerOn Host.Config.AutoStart X X
BrowseDiagnosticLog Global.Diagnostics X X
CancelTask Global.CancelTask X
CancelWaitForUpdates System.View X X
CheckCustomizationResources System.View X
CheckCustomizationSpec VirtualMachine.Provisioning.Customize X
CheckForUpdates System.View X X
CheckIfMasterSnmpAgentRunning Host.Config.Snmp X X
CheckLicenseFeature Global.Licenses X X
CloneVM_Task NONE. X
Privileges are required on the virtual machine being
cloned and depend on whether or not the virtual
machine is a template. See CloneVM_Task in the
VMware Infrastructure SDK Reference Guide for specific
privileges.
You will also need the
VirtualMachine.Inventory.Create privilege on the
folder where the new virtual machine will be
located.
ComputeDiskPartitionInfo Host.Config.Storage X X
ConfigureDatastorePrincipal Host.Config.Maintenance X X
ConfigureLicenseSource Global.Licenses X X

www.vmware.com
302
A P P E N D I X C Privileges

Operation Privilege VC ESX


CreateAlarm NONE. X
Alarm.Create privilege required on the entity
associated with the alarm.
CreateCluster Host.Inventory.CreateCluster X
CreateCollectorForEvents System.View X X
CreateCollectorForTasks System.View X
CreateCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
CreateDatacenter Datacenter.Create X X
CreateDiagnosticPartition Host.Config.Storage X X
CreateFilter System.View X X
CreateFolder Folder.Create X X
CreateGroup Host.Local.ManageUserGroups X X
CreateLocalDatastore Host.Config.Storage X X
CreateNasDatastore Host.Config.Storage X X
CreatePerfInterval Performance.ModifyIntervals X X
CreateResourcePool Resource.CreatePool X X
CreateScheduledTask NONE. X
ScheduledTask.Create required on the entity
associated with the scheduled task.
CreateSnapshot_Task VirtualMachine.State.CreateSnapshot X X
CreateUser Host.Local.ManageUserGroups X X
CreateVM_Task VirtualMachine.Inventory.Create X X
Also, Resource.AssignVMToPool privilege required on
the resource pool with which the virtual machine
will be associated.
CreateVmfsDatastore Host.Config.Storage X X
CurrentTime System.View X X
CustomizationSpecItemToXml System.View X
CustomizeVM_Task VirtualMachine.Provisioning.Customize X
DeleteCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
DeleteFile Datastore.DeleteFile X X
DeselectVnic Host.Config.Network X X
Destroy_Task See Destroy_Task in the VMware Infrastructure SDK X X
Reference Guide.

303
VMware Infrastructure SDK Programming Guide

Operation Privilege VC ESX


DestroyChildren See DestroyChildren in the VMware Infrastructure SDK X X
Reference Guide.
DestroyCollector NONE X X
DestroyDatastore Datastore.Delete X X
DestroyNetwork Network.Delete X X
DestroyPropertyFilter NONE X X
DisableFeature Global.Licenses X X
DisableHyperThreading Host.Config.HyperThreading X X
DisableMultipathPath Host.Config.Storage X X
DisableRuleSet Host.Config.NetService X X
DisconnectHost_Task Host.Config.Connection X X
DoesCustomizationSpecExist VirtualMachine.Provisioning.ReadCustSpecs X
DuplicateCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
EnableFeature Global.Licenses X X
EnableHyperThreading Host.Config.HyperThreading X X
EnableMultipathPath Host.Config.Storage X X
EnableRuleset Host.Config.NetService X X
EnterMaintenanceMode_Task Host.Config.Maintenance X X
ExitMaintenanceMode_Task Host.Config.Maintenance X X
ExtendVmfsDatastore Host.Config.Storage X X
FindByDatastorePath System.View X X
FindByDnsName System.View X X
FindByInventoryPath System.View X X
FindByIp System.View X X
FindByUuid System.View X X
FindChild System.View X X
FormatVmfs Host.Config.Storage X X
GenerateLogBundles_Task Global.Diagnostics X X
GetAlarm System.View X
GetAlarmState NONE X
System.Read privilege is required on the entity
associated with the alarm.
GetCustomizationSpec VirtualMachine.Provisioning.ReadCustSpecs X
Login System.Anonymous X X

www.vmware.com
304
A P P E N D I X C Privileges

Operation Privilege VC ESX


Logout System.View X X
LogUserEvent NONE X X
Global.LogEvent required on the entity associated
with the event.
MarkAsTemplate VirtualMachine.Provisioning.MarkAsTemplate X
MarkAsVirtualMachine VirtualMachine.Provisioning.MarkAsVM X
Resource.AssignVMToPool required on the resource
pool to associate with the virtual machine.
MergePermissions Authorization.ReassignRolePermissions X X
MigrateVM_Task See MigrateVM_Task in the VMware Infrastructure X
SDK Reference Guide.
MountToolsInstaller VirtualMachine.Interact.ToolsInstall X X
MoveHostInto_Task Host.Inventory.EditCluster X
Host.Inventory.MoveHost required on the host being
moved.
MoveInto_Task Host.Inventory.EditCluster X X
Host.Inventory.MoveHost required on the host being
moved.
MoveIntoFolder_Task See MoveIntoFolder_Task in the VMware X X
Infrastructure SDK Reference Guide.
MoveIntoResourcePool See MoveIntoFolder_Task in the VMware X X
Infrastructure SDK Reference Guide.
OverwriteCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
PowerOffVM_Task VirtualMachine.Interact.PowerOff X X
PowerOnVM_Task VirtualMachine.Interact.PowerOn X X
QueryAvailableDisksForVmfs Host.Config.Storage X X
QueryAvailablePartition Host.Config.Storage X X
QueryAvailablePerfMetric NONE X X
System.Read is required on the entity for which
available performance metrics are queried.
QueryConfigOption System.Read X X
QueryConfigOptionDescriptor System.Read X X
QueryConfigTarget System.Read X X
QueryConnectionInfo Host.Inventory.AddStandaloneHost X X
QueryDescriptions Global.Diagnostics X X

305
VMware Infrastructure SDK Programming Guide

Operation Privilege VC ESX


QueryEvents System.View X X
QueryHostConnectionInfo System.Read X X
QueryLicenseSourceAvailability Global.Licenses X X
QueryLicenseUsage Global.Licenses X X
QueryMemoryOverhead System.Read X X
QueryNetworkHint Host.Config.Network X X
QueryOptions System.Read X X
QueryPartitionCreateDesc Host.Config.Storage X X
QueryPartitionCreateOptions Host.Config.Storage X X
QueryPerf NONE X X
System.Read privilege is required on the entity
whose performance statistics are being queried.
QueryPerfComposite NONE X X
System.Read privilege is required on the entity
whose performance statistics are being queried.
QueryPerfCounter System.View X X
QueryPerfProviderSummary NONE X X
System.Read privilege is required on the entity
whose performance statistics are being queried.
QueryVmfsDatastoreCreateOptions Host.Config.Storage X X
QueryVmfsDatastoreExtendOptions Host.Config.Storage X X
QueryVMotionCompatibility Resource.QueryVMotion X
ReadNextEvents NONE X X
ReadNextTasks NONE X
ReadPreviousEvents NONE X X
ReadPreviousTasks NONE X
RebootGuest VirtualMachine.Interact.Reset X X
RebootHost_Task Host.Config.Maintenance X X
RecommendHostsForVm System.Read X
ReconfigureAlarm Alarm.Edit X
ReconfigureAutostart Host.Config.AutoStart X X
ReconfigureCluster_Task Host.Inventory.EditCluster X
ReconfigureHostForDAS_Task Host.Config.Connection X
ReconfigureScheduledTask ScheduledTask.Edit X

www.vmware.com
306
A P P E N D I X C Privileges

Operation Privilege VC ESX


ReconfigureServiceConsoleReservation Host.Config.Memory X X
ReconfigVM_Task dynamic X X
ReconnectHost_Task Host.Config.Connection X
RefreshDatastore System.Read X X
RefreshFirewall Host.Config.NetService X X
RefreshNetworkSystem Host.Config.Network X X
RefreshServices Host.Config.NetService X X
RefreshStorageSystem Host.Config.Storage X X
RegisterVM_Task VirtualMachine.Inventory.Create X X
Resource.AssignVMToPool privilege is required on
the resource pool to which the virtual machine
should be attached.
ReleaseLease NONE. X X
Reload System.Read X X
RelocateVM_Task Resource.ColdMigrate X
RemoveAlarm Alarm.Delete X
RemoveAllSnapshots_Task VirtualMachine.State.RemoveSnapshot X X
RemoveAuthorizationRole Authorization.ModifyRoles X X
RemoveCustomFieldDef Global.ManageCustomFields X
RemoveDatastore Host.Config.Storage X X
RemoveEntityPermission NONE X X
Authorization.ModifyPermissions privilege is
required on the entity associated with the
permission.
RemoveGroup Host.Local.ManageUserGroups X X
RemoveInternetScsiSendTargets Host.Config.Storage X X
RemoveInternetScsiStaticTargets Host.Config.Storage X X
RemovePerfInterval Performance.ModifyIntervals X X
RemovePortGroup Host.Config.Network X X
RemoveScheduledTask ScheduledTask.Delete X
RemoveServiceConsoleVirtualNic Host.Config.Network X X
RemoveSnapshot_Task VirtualMachine.State.RemoveSnapshot X X
RemoveUser Host.Local.ManageUserGroups X X
RemoveVirtualNic Host.Config.Network X X

307
VMware Infrastructure SDK Programming Guide

Operation Privilege VC ESX


RemoveVirtualSwitch Host.Config.Network X X
Rename_Task See Rename_Task in the VMware Infrastructure SDK X X
Reference Guide.
RenameCustomFieldDef Global.ManageCustomFields X
RenameCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
RenameDatastore Datacenter.RenameDatastore X X
RenameSnapshot VirtualMachine.State.RenameSnapshot X All
but
ESX
2.x
RenewLease NONE X X
RescanAllHba Host.Config.Storage X X
RescanHba Host.Config.Storage X X
RescanVmfs Host.Config.Storage X X
ResetCollector NONE X X
ResetEntityPermissions NONE X X
Authorization.ModifyPermissions privilege is
required on the entity associated with the
permission as well as the entity’s parent.
ResetGuestInformation VirtualMachine.Config.ResetGuestInfo X X
ResetVM_Task VirtualMachine.Interact.Reset X X
RestartMasterSnmpAgent Host.Config.Snmp X X
RestartService Host.Config.NetService X X
RestartServiceConsoleVirtualNic Host.Config.Network X X
RetrieveAllPermissions System.View X X
RetrieveDiskPartitionInfo Host.Config.Storage X X
RetrieveEntityPermissions NONE X X
System.Read privilege is required on the entity
whose performance statistics are being queried.
RetrieveEntityScheduledTask System.View X
RetrieveProperties System.View X X
RetrieveRolePermissions System.View X X
RetrieveServiceContent System.Anonymous X X
RetrieveUserGroups System.View X X

www.vmware.com
308
A P P E N D I X C Privileges

Operation Privilege VC ESX


RevertToCurrentSnapshot_Task VirtualMachine.State.RevertToSnapshot X On all
RevertToSnapshot_Task VirtualMachine.State.RevertToSnapshot but
ESX
2.x
RewindCollector NONE X X
RunScheduledTask ScheduledTask.Run X
SearchDatastore_Task Datastore.Browse X X
SearchDatastoreSubFolders_Task Datastore.Browse X X
SelectActivePartition Host.Config.Storage X X
SelectVnic Host.Config.Network X X
SetCollectorPageSize NONE X X
SetEntityPermissions NONE X X
Authorization.ModifyPermissions required on entity
associated with the permissions as well as its parent.
SetField NONE X X
Global.SetCustomField required on the entity
associated with the custom field.
SetLicenseEdition Global.Licenses X X
SetLocale System.View X X
SetMultipathLunPolicy Host.Config.Storage X X
SetScreenResolution VirtualMachine.Interact.ConsoleInteract X X
ShutdownGuest VirtualMachine.Interact.PowerOff X X
ShutdownHost_Task Host.Config.Maintenance X X
StandbyGuest VirtualMachine.Interact.Suspend X X
StartService Host.Config.NetService X X
StopMasterSnmpAgent Host.Config.Snmp X X
StopServiceq Host.Config.NetService X X
SuspendVM_Task VirtualMachine.Interact.Suspend X X
TerminateSession Sessions.TerminateSession X X
UnassignUserFromGroup Host.Local.ManageUserGroups X X
UninstallService Host.Config.NetService X X
UnmountToolsInstaller VirtualMachine.Interact.ToolsInstall X X
UnregisterAndDestroy_Task Folder.Deletea X X
UnregisterVM VirtualMachine.Inventory.Delete X X

309
VMware Infrastructure SDK Programming Guide

Operation Privilege VC ESX


UpdateAuthorizationRole Authorization.ModifyRoles X X
UpdateChildResourceConfiguration See UpdateChildResourceConfiguration in the X X
VMware Infrastructure SDK Reference Guide.
UpdateConfig See UpdateConfig in the VMware Infrastructure SDK X X
Reference Guide.
UpdateConsoleIpRouteConfig Host.Config.Network X X
UpdateDefaultPolicy Host.Config.Network X X
UpdateDiskPartitions Host.Config.Storage X X
UpdateDnsConfig Host.Config.Network X X
UpdateInternetScsiAlias Host.Config.Storage X X
UpdateInternetScsiAuthenticationProperties Host.Config.Storage X X
UpdateInternetScsiDiscoveryProperties Host.Config.Storage X X
UpdateInternetScsiIPProperties Host.Config.Storage X X
UpdateInternetScsiName Host.Config.Storage X X
UpdateIpConfig Host.Config.Network X X
UpdateIpRouteConfig Host.Config.Network X X
UpdateNetworkConfig Host.Config.Network X X
UpdateOptions See UpdateOptions in the VMware Infrastructure SDK X
Reference Guide.
UpdatePerfInterval Performance.ModifyIntervals X X
UpdatePhysicalNicLinkSpeed Host.Config.Network X X
UpdatePortGroup Host.Config.Network X X
UpdateServiceConsoleVirtualNic Host.Config.Network X X
UpdateServiceMessage Sessions.GlobalMessage X X
UpdateServicePolicy Host.Config.NetService X X
UpdateSnmpConfig Host.Config.Snmp X X
UpdateSoftwareInternetScsiEnabled Host.Config.Storage X X
UpdateSystemResources Host.Config.Resources X X
UpdateUser Host.Local.ManageUserGroups X X
UpdateVirtualNic Host.Config.Network X X
UpdateVirtualSwitch Host.Config.Network X X
UpgradeTools_Task VirtualMachine.Interact.ToolsInstall X X
UpgradeVM_Task VirtualMachine.Config.UpgradeVirtualHardware X X
UpgradeVmfs Host.Config.Storage X X

www.vmware.com
310
A P P E N D I X C Privileges

Operation Privilege VC ESX


UpgradeVmLayout Host.Config.Storage X X
ValidateMigration See ValidateMigration in the VMware Infrastructure X
SDK Reference Guide.
Resource.AssignVMToPool required on The target
resource pool for the virtual machines.
WaitForUpdates System.View X X
XmlToCustomizationSpecItem System.View X

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

Privileges and Properties


The following list contains the privileges required to read certain properties of managed objects.

Object Property Privilege


AlarmManager defaultExpression System.View
description System.View
AuthorizationManager privilegeList System.View
roleList System.View
description System.View
ComputeResource resourcePool System.View
host System.View
CustomFieldsManager field System.View
CustomizationSpecManager info VirtualMachine.Provisioning.ReadCustSpecs
encryptionKey System.View
Datacenter vmFolder System.View
hostFolder System.View
EventManager description System.View
latestEvent System.View
maxCollector System.View
Folder childType System.View
childEntity System.View
HostCpuSchedulerSystem hyperThread Host.Config.HyperThreading
HostDiagnosticSystem activePartition Host.Config.Storage
HostFirewallSystem firewallInfo Host.Config.NetService
HostMemoryManagerSystem consoleReservationInfo Host.Config.Memory
HostNetworkSystem capabilities Host.Config.Network
networkConfig Host.Config.Network
networkInfo Host.Config.Network
offloadCapabilities Host.Config.Network
HostServiceSystem serviceInfo Host.Config.NetService
HostSnmpSystem snmpConfig Host.Config.Snmp
HostStorageSystem fileSystemVolumeInfo Host.Config.Storage
storageDeviceInfo Host.Config.Storage

www.vmware.com
312
A P P E N D I X C Privileges

Object Property Privilege


HostVMotionSystem netConfig Host.Config.Network
ipConfig Host.Config.Network
LicenseManager source Global.Licenses
sourceAvailable Global.Licenses
featureInfo Global.Licenses
ManagedEntity parent System.View
effectiveRole System.View
name System.View
PerformanceManager description System.View
historicalInterval System.View
perfCounter System.View
PropertyCollector filter System.View
ResourcePool owner System.View
ScheduledTaskManager scheduledTask System.View
description System.View
ServiceInstance serverClock System.View
capability System.View
SessionManager sessions Sessions.TerminateSession
currentSession System.Anonymous
message System.View
messageLocaleList System.Anonymous
supportedLocaleList System.Anonymous
defaultLocale System.Anonymous
TaskManager recentTask System.View
description System.View
maxCollector System.View
UserDirectory domainList System.View

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.

Publication Date Description


June 15, 2006 Programming Guide completely re-written from 1.x. The guide includes:
• Extensive chapters describing concepts and operations
• Information about using the Managed Object Browser
• Sample code snippets and a simple client application
September 22, 2006 • New appendix (Upgrading VMware Tools on page 275) describing the new operation
for upgrading VMware Tools. Appendix contains Java samples for single and batch
operations.
• Improved list of Performance Counters on page 287.
• Improved Developing Client Applications on page 21. SimpleClient application
moved to separate chapter, Creating a Simple Java Client Application on page 191.
• Revised definition of Universally Unique Identifier (UUID).
• Managing Users and Logging On chapter now separated into two chapters: Logging
On on page 61 and Managing Users on page 175.

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

You might also like