Programming Guide
Revision: 20090113
Item: VI-ENG-Q407-282
You can find the most up-to-date technical documentation on the VMware Web site at:
http://www.vmware.com/support/
The VMware Web site also provides the latest product updates.
If you have comments about this documentation, submit your feedback to:
docfeedback@vmware.com
© 2007, 2009 VMware, Inc. All rights reserved. This product is protected by U.S. and international copyright and intellectual
property laws. VMware products are covered by one or more patents listed at http://www.vmware.com/go/patents.
VMware, the VMware “boxes” logo and design, Virtual SMP, and VMotion are registered trademarks or trademarks of
VMware, Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks
of their respective companies.
VMware, Inc.
3401 Hillview Ave.
Palo Alto, CA 94304
www.vmware.com
2 VMware, Inc.
Contents
About This Book 11
1 What’s New in the VI SDK? 15
Support for New VI API Version (API 2.5) 15
How Does the VI API 2.5 Differ from Previous Releases? 15
How Does the New API Affect Existing Applications? 16
Can Client Applications Target Both ESX Server 3.0.x and ESX Server 3.5? 16
New Managed Object Types and Operations 17
New Operations 18
New Data Objects and Properties 20
Deprecated Properties and Types 20
New Java Sample Applications 21
Versioning, Durable LUN Names, and HTTP File Access Samples 22
Handling Different API‐ and Object‐Model‐Versions 22
Obtaining All Information about SCSI Devices 24
Using HTTP for Cold Migration of Virtual Machine Files 24
Java Samples Summary 24
2 Basic Concepts for Developers 27
Introducing the VMware Infrastructure Management Object Model 27
Understanding the VI API 28
API Supported by ESX Server and VirtualCenter Server 28
Data Structures Comprising the VMware Infrastructure Object Model Types 28
Managed Object Types 29
References to Managed Objects 29
Data Objects 29
Properties 29
Understanding the Role of Client‐side Proxy Code 31
Using the VI Client to Become Familiar with the Object Model 31
Using the Managed Object Browser (MOB) to Explore Objects on the Server 32
Accessing the MOB 32
Navigating the MOB Display 33
Using the Reference to the Server’s ServiceInstance Managed Object 34
Differences in ESX Server and VirtualCenter Server Inventory 37
Inventory of Managed Entities (The ManagedEntity Managed Object Type) 39
Using the API Reference Guide 40
3 Service‐Management Operations 41
AuthorizationManager and SessionManager Provide Security Services 41
SessionManager Managed Object Type 42
Determining Whether currentSession Is Still Active After Reboot 42
Authorization Based on Identity 42
Finding Objects and Properties: The PropertyCollector Managed Object 44
Finding Objects and Properties: SearchIndex Managed Object 44
EventManager Managed Object Type 45
TaskManager Managed Object Type 45
ScheduledTaskManager Managed Object 47
VMware, Inc. 3
Programming Guide
AlarmManager Managed Object 48
PerformanceManager Managed Object Type 49
4 Introduction to the Inventory 51
ManagedEntity as a Base (Abstract) Class 51
Folder Managed Object 52
Datacenter Managed Object Type 53
VirtualMachine Managed Object Type 54
HostSystem Managed Object Type 55
HostConfigInfo 56
HostHardwareInfo 56
HostDatastoreBrowser 56
Datastore Managed Object Type 57
ComputeResource Managed Object Type 58
ResourcePool Managed Object Type 58
ClusterComputeResource Managed Object Model 59
5 Using the PropertyCollector and SearchIndex Managed Objects 61
Obtaining Managed Object References 61
Passing Properties to the SearchIndex to Obtain a ManagedObjectReference 61
The FindByDnsName Operation 62
Creating a Specification That Filters Objects and Properties 63
Specifying the Properties or Objects 63
Retrieving a Specific Managed Object (No Properties) 63
Retrieving All the Properties 63
Retrieving One or More Properties 64
Retrieving Information from Multiple Objects 64
Specifying the Starting Point for a Search Using an ObjectSpec 64
What Is the Starting Object? 65
Skipping the Starting Object 65
Using Multiple ObjectSpec Objects 66
Putting It All Together: The PropertyFilterSpec Object 66
Using ServiceContent Object’s searchIndex Property 67
Traversing Objects 68
A Simple Collector with No Traversal 68
Traversal Using Simple Collectors (with No Traversal) 68
The Better Way to Traverse: the TraversalSpec 70
Using a PropertyCollector with Traversals 70
The Simplest Way To Traverse: Get Close to Your Target Objects 71
Finding Information about Other Objects 72
Finding Information on the VirtualCenter Server 73
Starting Anywhere in the Tree: A Generic TraversalSpec 75
Synchronizing Data 76
Creating a Filter 76
Checking or Waiting for Updates 77
6 Basic Inventory Operations 79
Creating a Datacenter 79
Deleting a Datacenter 80
Managing Folders 80
Creating a Folder 80
Deleting a Folder 80
Deleting the Folder and Unregistering the Virtual Machines 80
4 VMware, Inc.
Contents
Deleting a Folder and Its Contents Completely 80
Moving Inventory Items into a Folder 80
Renaming Inventory Items 81
7 Virtual Machine Operations 83
Performing Power Operations 83
Powering On 83
Powering Off 83
Suspending 84
Power Operations Example 84
Resetting a Virtual Machine 84
Managing Snapshots 85
Creating Snapshots 86
Creating Snapshots and ESX 2.x Server 86
Code Example of Snapshot Creation 86
Reverting to Snapshots 87
Removing Snapshots 87
Obtaining a VirtualMachineSnapshot Managed Object Reference 88
Migrating a Powered‐On Virtual Machine (VMotion) 88
Enabling Migration 88
Enabling the VMotion Feature 89
Updating the VMotion IP Configuration 89
Validating Migration 89
Performing VMotion 89
Example 90
Moving Files 92
Code Example 92
Creating a Virtual Machine 93
Creating a Virtual Machine from Scratch 93
Creating and Configuring a Virtual Machine 94
Cloning Virtual Machines 97
Renaming a Virtual Machine 97
Creating Templates 97
Identifying an Existing Virtual Machine as a Template 98
Cloning an Existing Virtual Machine 98
Changing a Template to an Active Virtual Machine 99
Configuring a Virtual Machine 99
Defining Console Preferences 99
Configuring CPU and Memory Information 99
Specifying CPU Processors and Memory Nodes 99
Allocating CPU and Memory Resources 100
Defining the CPU Feature Mask 100
Specifying the Amount of Memory 100
Defining the Number of Virtual Processors 100
Defining the Virtual Devices 100
Defining the Physical Device 101
Configuring the Virtual Machine for Migration 102
Replacing Existing VMDK with New VMDK 102
Defining File Information 103
Naming the Virtual Machine 103
Defining Network Shaping 103
Defining Default Power Operations 103
Setting Flags on the Virtual Machine 103
Defining Tools Information 103
Defining or Removing a Description 103
VMware, Inc. 5
Programming Guide
Defining IDs for Guest Operating System and Configuration File Location 104
Defining the Universally Unique Identifier (UUID) 104
Recommending Hosts for Virtual Machines 104
8 Monitoring and Managing Performance 105
Configuring Intervals for Statistics 105
Creating Performance Intervals 106
Updating Performance Intervals 106
Removing Performance Intervals 106
Querying Statistics 106
Perf Intervals 107
Retrieving MetricIds 107
Querying Performance Statistics 107
Querying Information for an Entity and Its Children 107
Querying Performance Provider Information 108
Querying Metadata Information 108
Basic Performance Counters 108
9 Events and Alarms 111
Logging a User‐Defined Event 111
Retrieving Historical Information 111
Retrieving Historical Event Information 111
Creating a Collector for Events 111
Reading the Items in the EventHistoryCollector 113
Formatting Event Messages 113
Retrieving Historical Task Information 117
Creating a Collector for Tasks 117
Reading the Items in the TaskHistoryCollector 117
Using a History Collector 118
Setting the Viewable Latest Page 118
Updating the History Collector 118
Modifying the Current Position 118
Deleting a Collector 119
Managing Alarms 120
Creating Alarms 120
Configuring or Reconfiguring an Alarm 120
Defining the Triggering Conditions 121
Defining a Metric Alarm Expression 121
Handling Multiple Conditions 122
Setting the Range and Frequency of a Metric Expression 122
Defining a State Alarm Expression 123
Choosing an Action or Set of Actions 124
Constructing the AlarmSpec 125
Getting a List of Alarms 125
Getting the Overall Status of Alarm 125
Deleting an Alarm 126
Disabling an Alarm 126
10 Managing Physical Resources 127
Managing Clusters and Resource Pools 127
Creating a Cluster of Hosts 127
Configuring or Reconfiguring a Cluster 128
Enabling a Cluster for VMware DRS or VMware HA 128
Defining a Set of Rules 129
6 VMware, Inc.
Contents
Creating Resource Pools 129
Reconfiguring Resource Pools 129
Reconfiguring a Single Resource Pool 129
Reconfiguring a Set of Resource Pools 129
Configuring Resource Pools with the ResourceConfigSpec 130
Allocating CPU and Memory 130
Expanding the Minimum Resources 131
Setting a Limit to Memory/CPU Usage 131
Specifying the Entity for the Configuration 131
Defining Shares 131
Destroying the Children of a Resource Pool 132
Moving Resource Pools and Virtual Machines Into a Resource Pool 132
Overcommitting Resources 133
Managing Hosts 134
Adding a Standalone Host 135
Adding a Host to a Cluster 135
Moving Hosts Into a Cluster 135
Conditions for Moving Existing Hosts 136
Moving a Single Host Into a Cluster 136
Moving a Set of Hosts Into a Cluster 136
Moving Existing Hosts into a Folder 136
Removing Hosts from a Cluster 137
Connecting and Disconnecting Hosts 137
Recommending Hosts for Virtual Machines 138
Achieving a More Efficient Resource Usage for Clusters (DRS Only) 138
Shutting Down or Restarting a Host 138
11 Managing Networking Infrastructure 139
Configuring the Service Console TCP/IP 139
Configuring TCP/IP on the VMkernel 139
Determining the Host’s Network Configuration 140
Adding a Virtual Switch 140
Adding a Port Group to a vSwitch 140
Adding a Virtual NIC (VNIC) 141
Updating the Host’s Network Configuration 141
Updating the Network Configuration in Batch 141
Updating the Service Console VNIC 141
Adding or Removing a Virtual Network Interface Card for the Service Console 142
Restarting the Service Console VNIC 142
Updating the TCP/IP Configuration on the VMkernel 142
Defining the Host Network Policy 142
Obtaining the HostNetworkSystem Managed Object Reference 143
12 Storage Operations 145
Creating an NAS‐Backed Datastore 145
Creating a VMFS‐Backed Datastore 145
Extending a VMFS Datastore Across Multiple Disks 146
Determining Options for Extending a VMFS‐Backed Datastore 146
Searching for Available Disks for Extending VMFS Datastores 146
Removing and Deleting Datastores 147
Configuring a VMFS‐Backed Datastore 147
Configuring Extended Datastores 147
Specifying a Partition Table 147
Specifying the VMFS Datastore 147
VMware, Inc. 7
Programming Guide
Determining Options for Creating a New VMFS Datastore 148
Defining the HostScsiDiskPartition 148
Defining the HostDiskPartitionInfoSpecification 148
Configuring iSCSI Initiators 148
Determining the Host Bus Adapter 149
Determining the HBA ID String 149
Determining the iSCSI Host Bus Adapter’s Capabilities 149
Configuring the IP Address (Hardware Initiator) 149
Enabling the Software Initiator (Software Initiator) 150
Configuring the iSCSI Name and Alias 150
Setting the Authentication Information 150
Configuring Target Discovery 150
Configuring Access to Targets 151
Issuing a Rescan on the HBAs 151
Obtaining Managed Object References for Storage Operations 151
13 Managing Users 153
Security Management 153
Privileges, Roles, and Permissions 153
Privileges 153
Privileges and Operations 153
Operations That Require Privileges on an Entity and Its Parent 154
Privileges and Properties 154
Roles 154
Permissions 155
Permissions and Sub‐Objects 155
Permissions and Complex Entities 156
HTTP‐Based File Access Permissions 156
Users, Groups, and Permissions 157
Adding and Maintaining Users and Groups (ESX only) 157
Querying for Users and Groups 158
Adding and Maintaining Authorization Roles 158
Setting and Maintaining Permissions on an Entity 159
Setting, Updating, or Resetting Entity Permissions 159
Removing Entity Permissions 159
Querying for Permissions 160
Querying for All Permissions 160
Querying for the Permissions on a Specific Entity 160
Querying for the Permissions that Use a Particular Role 160
Obtaining a Reference to the AuthorizationManager 160
14 Using the Task Framework 161
Using Properties to Determine a Task’s Capabilities 161
Using the info Property 161
Using the recentTask Property 161
Using the RetrieveEntityScheduledTask Operation 162
Creating a Scheduled Task 163
Configuring and Reconfiguring a Scheduled Task 164
Choosing an Action or Set of Actions 164
Defining the Task Schedule 164
Constructing the ScheduledTaskSpec 166
Monitoring Tasks 166
Cancelling a Task 167
Cancellable and Non‐Cancellable Tasks 167
8 VMware, Inc.
Contents
Code Example—Cancelling a Task Resulting from an Operation 167
Deleting a Scheduled Task 168
Retrieving the Scheduled Tasks on an Entity 168
A Performance Counters Reference 171
Counter Information Categories 171
Complete List of Performance Counters 171
CPU Usage (Group: cpu) 171
CPU Utilization for Resources (Group: rescpu) 172
Memory Performance (Group: mem) 173
Network Performance (Group: net) 175
Disk Performance (Group: disk) 176
System Performance (Group: sys) 176
Cluster Services Metrics (Group: clusterServices) 177
B Managed Object Privileges Reference 179
Privileges Required to Perform Operations 179
Privileges Required to Read Properties 186
C Upgrading VMware Tools 189
Prerequisites 189
Invoking UpgradeTools_Task 189
Failure Mode 189
Cancelling the Operation 190
Upgrading VMware Tools for a Single Virtual Machine—Java Example 190
Upgrading VMware Tools in Batch—Java Example 192
D PropertyCollector Tutorial 197
PropertyCollector Operations 197
RetrieveProperties 197
CheckForUpdates 197
WaitForUpdates 198
Mechanics of Accessing Properties 198
Nested Properties and Property Paths 198
Key‐Based Arrays and Indexed Arrays 198
Filtering Results 199
PropertyFilter 199
ObjectSpec 199
PropertySpec 200
Traversal and Recursion 200
Object Selection Without TraversalSpec Objects 201
Object Selection With a Single TraversalSpec Object 201
Traversing a Fixed Number of Levels 201
Using Recursion in TraversalSpec Objects 202
Reducing Network Traffic by Using the partialUpdates Flag 204
Index 205
VMware, Inc. 9
Programming Guide
10 VMware, Inc.
About This Book
This book, the Programming Guide, provides information about using the VMware® Infrastructure (VI) SDK to
develop client applications that can manage, monitor, and control the life‐cycle of virtual infrastructure using
the VMware Infrastructure management components.
VMware provides several different SDK products, each intended for different developer communities and
target platforms. This guide is intended for developers who are creating applications aimed at managing
VMware virtual infrastructure through ESX Server and VirtualCenter Server systems.
Revision History
This guide is revised with each release of the product or when necessary. A revised version can contain minor
or major changes. Table 1 summarizes the significant changes in each version of this guide.
20060615 Initial publication of a complete rewrite for VI SDK 2.0.1. New chapters on concepts and operations.
Information about the Managed Object Browser. Sample code and simple client application.
20061002 Updated to include more information about Performance Counters, Developing Client Applications.
Re‐organized chapters on Managing Users and Logging On.
VMware, Inc. 11
Programming Guide
20071008 Initial reorganization for VI SDK 2.5 (for ESX Server 3.5, VirtualCenter 2.5, and ESX Server 3i Beta 2).
Changes include:
1 Added an introductory chapter (What’s New in the VI SDK?”), which provides information about
new features and capabilities, including information about several new samples (durable LUNs,
HTTP Put/Get, versioning).
2 From the now‐defunct Getting Started Guide (from VI SDK 2.0.1), added content from:
“Introducing the Object Model” (added relevant information to Chapter 2 ‐ “Basic Concepts for
Developers,” on page 27)
“VirtualMachine and Host Resources” (added relevant information to Chapter 4 ‐ “Introduction
to the Inventory,” on page 51)
“Managing and Monitoring” (added relevant information to Chapter 3 ‐ “Service‐Management
Operations,” on page 41
“PropertyCollector Tutorial” (added as Appendix D, “PropertyCollector Tutorial,” on page 197)
“Using the PerformanceManager” (added to Chapter 8 ‐ “Monitoring and Managing
Performance,” on page 105).
3 Removed these chapters:
“Developing Client Applications” Much of the information in this chapter had to do with initial
setup for development purposes. All relevant information is now contained in the VI SDK 2.5
Developer’s Setup Guide.
“VMware Infrastructure Key Concepts”
“Creating a Simple Java Client Application” (Removed in deference to the samples provided with
the VI SDK.)
“Java Code Examples for Basic Operations” (See the Java samples, especially the provided
apputils, for basic operations, such as connecting to the server, authenticating user credentials,
and so on.)
“Java Code Examples for Advanced Operations” (See the Java samples provided in the VI SDK
package).
“C# Code Examples for Basic Operations” (a mere two pages that showed only how to logon
using C# code. See the actual sample code that ships with the VI SDK for information about using
C#.)
“Glossary” (definitions are now covered in context).
Information about setting up a development environment (Java, C#) for using the VI SDK is now
contained in the Developer’s Setup Guide.
20071129 Initial release for VI SDK 2.5. Additional changes (since those listed for 20071008) include:
1 Removed the “Basic Pattern for Client Applications” chapter and incorporated the information in
Chapter 2 ‐ “Basic Concepts for Developers,” on page 27.
2 Renamed the “Getting Information and Updates” chapter to Chapter 5 ‐ “Using the
PropertyCollector and SearchIndex Managed Objects,” on page 61.
3 Renamed the “Managing Inventory” chapter to Chapter 6 ‐ “Basic Inventory Operations,” on page 79.
Removed the VirtualMachine‐specific content from Managing Inventory and added to Chapter 7 ‐
“Virtual Machine Operations,” on page 83. Removed the host‐specific content from Managing
Inventory and added to Chapter 10 ‐ “Managing Physical Resources,” on page 127. Removed
networking configuration information from Managing Inventory and added to Chapter 11 ‐
“Managing Networking Infrastructure,” on page 139.
4 Revised several figures using UML (unified modeling language) to show class hierarchy.
20090113 Update for VI SDK 2.5. Additional changes (since those listed for 20071129) include:
1 Added the following section ‐ Chapter 3 ‐ “Determining Whether currentSession Is Still Active After
Reboot,” on page 42.
2 Added the following section ‐ Chapter 7 ‐ “Replacing Existing VMDK with New VMDK,” on
page 102.
3 Revised the values in Chapter 8 ‐ “Retrieving MetricIds,” on page 107.
4 Added the following section ‐ Chapter 13 ‐ “HTTP‐Based File Access Permissions,” on page 156.
5 Revised the compatibility of the following operations ‐ Appendix B, “CreatePerfInterval,” on
page 180 and Appendix B, “UpdatePerfInterval,” on page 186.
12 VMware, Inc.
About This Book
Intended Audience
This book is intended for anyone who wants to develop applications using the VI SDK. VI SDK developers
typically include software developers creating virtual infrastructure management applications using Java or
C# (in the Microsoft .NET environment) targeting the Web‐services based API available on ESX Server and
VirtualCenter Server systems.
Target server—The VirtualCenter Server or ESX Server systems that are the targets of your client‐side
code.
Development workstation—The Linux or Microsoft Windows machine that is configured with the
Web‐services client‐side libraries, development environment, and the VI SDK sample code and other
artifacts found in the download.
Document Feedback
VMware welcomes your suggestions for improving our documentation. If you have comments, send your
feedback to:
docfeedback@vmware.com
http://www.vmware.com/support/pubs
Online Support
You can submit questions or post comments to the Management APIs (VI Perl, VI SDK, CIM SDK) forum,
which is monitored by VMware technical support and product teams. You can access the forum at:
http://www.vmware.com/community/forum.jspa?forumID=393.
Support Offerings
Find out how VMware support offerings can help meet your business needs. Go to
http://www.vmware.com/support/services.
VMware, Inc. 13
Programming Guide
14 VMware, Inc.
1
ESX Server 3.5, VirtualCenter Server 2.5, and ESX Server 3i support a new version of the VMware
Infrastructure API—VI API 2.5—that provides new interfaces and data structures (managed objects, data
objects, and so on) that comprise VMware infrastructure management components.
For example, VirtualCenter 2.5 provides a new patch‐management feature, VMware Update Manager, which
provides automated scanning (to determine appropriate patchsets) and patching of ESX Server systems
(among other capabilities). The VI API 2.5 supports ESX Server patching with the addition of new managed
object types and operations, specifically, the HostPatchManager managed object, with its
ScanHostPatch_Task and InstallHostPatch_Task operations. (See Table 1‐1, “New Managed Objects
Supported in VI API 2.5,” on page 17 for a summary list.)
This chapter includes these topics:
Support for New VI API Version (API 2.5)
New Managed Object Types and Operations
New Java Sample Applications
The API 2.5 WSDL uses the namespace “vim25,” which supports the API available on ESX Server 3.5,
VirtualCenter Server 2.5, and ESX Server 3i Web services.
The API 2.0 WSDL uses the namespace “vim2,” which is the same as in previous releases of the SDK,
including VI SDK 2.0.1. The VI API 2.0 is available on ESX Server 3.0.x, VirtualCenter Server 2.0.x, ESX
Server 3.5, VirtualCenter Server 2.5, and ESX Server 3i.
In addition, in some cases, some of the existing managed objects, properties, and operations have been
deprecated in favor of new capabilities. The differences can be summarized as follows:
Completely new managed objects—for example, ExtensionManager, ViewManager,
VirtualDiskManager, and HostPatchManager.
VMware, Inc. 15
Programming Guide
New operations on existing managed objects, such as the Datacenter managed object type’s new
PowerOnMultiVM_Task, or the HostSystem managed object type’s PowerDownHostToStandBy_Task
and PowerUpHostFromStandBy_Task.
New data objects, properties, and faults associated with both new and existing (VI API 2.0) data
structures. For example, the new HostSystemHealthInfo data object type defines one of the properties
of another new data object, HealthSystemRuntime. HealthSystemRuntime is used as a new property of
HostRuntimeInfo, which is a data object defined in API 2.0.
New properties on existing managed objects or data objects. For example, HealthSystemRuntime
mentioned above, and the new alternateName and standardInquiry properties available on the
ScsiLun data object.
Deprecated managed objects, properties, or operations. For example, the QueryMemoryOverhead
operation is deprecated in this release, in favor of the QueryMemoryOverheadEx.
Several new Java sample applications demonstrate using the new API, or handling differences between using
the new API and its predecessor. See Table 1‐5 for a reference listing of new sample applications.
Also, in some cases, the object model has been refactored to provide a more robust foundation for future
enhancement.
For example, a new managed object type—ExtensibleManagedObject—serves as the base class from which
many other managed object types are derived. This change is transparent to client‐application developers
(meaning, you do not need to make changes to existing code). But you may notice the new structure as you
navigate through the version 2.5 VI API Reference Guide.
See the VI API Reference Guide for more information. The API Reference Guide is available in the VI SDK 2.5
package, in this path:
\SDK\doc\ReferenceGuide
Can Client Applications Target Both ESX Server 3.0.x and ESX Server 3.5?
In a word, “yes.” Client applications that use the VI API 2.0 (the vim2 WSDL) will be able to communicate with
all target servers—ESX Server 3.5, VirtualCenter 2.5, ESX Server 3i, ESX Server 3.0.x, and VirtualCenter Server
2.0.x.
To leverage new features of ESX Server 3.5, VirtualCenter 2.5, and ESX Server 3i—the new
HostPatchManager, for example—you must use the VI API 2.5 (the vim25 WSDL).
You can also create new client applications that support mixed server environments (ESX Server 3.5, ESX
Server 3.0.x, VirtualCenter Server 2.5, VirtualCenter 2.0.x), and vary the behavior depending on the version.
First, query the server to obtain the WSDL namespace version information. Then, use logic in your code to
invoke operations or handle data types properly, appropriate for the server version. The VI SDK 2.5 includes
several Java samples (in the \version sub‐directory) that demonstrate how: The GetVersion sample is a utility
class that obtains the version information from the server’s WSDL. Other samples demonstrate how
processing can vary, based on the server version. The version samples are discussed in more detail in
“Handling Different API‐ and Object‐Model‐Versions” on page 22.
16 VMware, Inc.
Chapter 1 What’s New in the VI SDK?
Table 1‐1 summarizes the new managed objects available in the VI SDK 2.5. Of the Managed Object types listed
in Table 1‐1, these four are used to model ServiceContent properties that return managed object references to
singleton instances of the managed objects, as instantiated on the server:
ExtensionManager
FileManager
ViewManager
VirtualDiskManager
More information about these new services will be available soon, in an update to this Programming Guide.
ContainerView View managed object type that facilitates monitoring the contents of a single container.
Facilitates rendering object list within a specific container, for UI client applications.
Extends (ManagedObjectView.)
ExtensibleManagedObject Base interface for extensible managed object types.
ExtensionManager Provides services to register and managed. Clients use the ExtensionManager,
available in ServiceInstance, to access Extension objects.
FileManager Provides operations for managing and manipulating files and folders on Datastore
objects—for example, copying, deleting, and moving datastore files, and making
directories on a Datastore. Experimental; subject to change.
HostBootDeviceSystem Managed object type that describes the current system boot device configuration.
HostDateTimeSystem Provides for NTP (network time protocol) and date and time configuration on a host.
Information regarding the running status of the NTP daemon and functionality to start
and stop the daemon is provided by the HostServiceSystem object.
HostFirmwareSystem Provides access to the firmware of an ESX Server 3i host system, and enables ESX Server
3i configuration backup, restore, and reset. Experimental; subject to change.
HostHealthStatusSystem Manages health state of the host, enabling checking state and resetting state.
HostPatchManager Interface for scanning and patching an ESX Server using software updates available
over the Web, from VMware.
InventoryView View managed object type that enables browsing the inventory and tracking changes
to open folders. Facilitates rendering tree‐based inventory navigation for UI client
applications. (Extends ManagedObjectView.)
ListView View managed object type that enables modifying view content without adding or
destroying filters. (Extends ManagedObjectView.)
ManagedObjectView Base class for view objects that expose a set of ManagedObjects. Extended by
ContainerView, InventoryView, and ListView.
View Base class for session‐specific view objects.
ViewManager Provides access to managed objects that extend ViewManagedObject (base class), such
as ContainerView, InventoryView, and ListView. These server‐side view objects enable
client applications to display subsets of properties for update.
VirtualDiskManager Service for managing and manipulating virtual disks on datastores using URL or
datastore path for source and target names.
For details about each of these new managed object types, see the VI API Reference Guide. The API Reference
Guide is available in the VI SDK 2.5 package, in this path:
\SDK\doc\ReferenceGuide
VMware, Inc. 17
Programming Guide
New Operations
Table 1‐2 lists new operations available in the VI API 2.5.
Table 1-2. New operations available in the VI API 2.5
Managed Object Type Operation
ClusterComputeResource RefreshRecommendation
ComputeResource ReconfigureComputeResource_Task
Datacenter PowerOnMultiVM_Task
EventManager PostEvent
ExtensibleManagedObject setCustomValue
ExtensionManager SetPublicKey
UnregisterExtension
UpdateExtension
FindExtension
RegisterExtension
GetPublicKey
FileManager MoveDatastoreFile_Task
MakeDirectory
CopyDatastoreFile_Task
DeleteDatastoreFile_Task
Folder CreateClusterEx
HostBootDeviceSystem UpdateBootDevice
QueryBootDevices
HostDatastoreSystem UpdateLocalSwapDatastore
HostDateTimeSystem RefreshDateTimeSystem
UpdateDateTime
QueryAvailableTimeZones
UpdateDateTimeConfig
QueryDateTime
HostFirmwareSystem RestoreFirmwareConfiguration
ResetFirmwareToFactoryDefaults
BackupFirmwareConfiguration
QueryFirmwareConfigUploadURL
HostHealthStatusSystem ResetSystemHealthInfo
RefreshHealthStatusSystem
HostMemorySystem ReconfigureVirtualMachineReservation
HostPatchManager InstallHostPatch_Task
ScanHostPatch_Task
HostSnmpSystem SendTestNotification
ReconfigureSnmpAgent
18 VMware, Inc.
Chapter 1 What’s New in the VI SDK?
HostSystem PowerDownHostToStandBy_Task
AcquireCimServicesTicket
PowerUpHostFromStandBy_Task
QueryMemoryOverheadEx
UpdateFlags
InventoryView OpenInventoryViewFolder
CloseInventoryViewFolder
LicenseManager QuerySupportedFeatures
ListView ResetListViewFromView
ResetListView
ModifyListView
PerformanceManager QueryPerfCounterByLevel
ServiceInstance RetrieveProductComponents
SessionManager LoginBySSPI
ImpersonateUser
SessionIsActive
LoginExtension
Task SetTaskState
UpdateProgress
TaskManager CreateTask
View DestroyView
ViewManager CreateListView
CreateInventoryView
CreateContainerView
CreateListViewFromView
VirtualDiskManager ShrinkVirtualDisk_Task
ZeroFillVirtualDisk_Task
SetVirtualDiskUuid
QueryVirtualDiskUuid
ExtendVirtualDisk_Task
CreateVirtualDisk_Task
CopyVirtualDisk_Task
DeleteVirtualDisk_Task
MoveVirtualDisk_Task
QueryVirtualDiskFragmentation
DefragmentVirtualDisk_Task
QueryVirtualDiskGeometry
InflateVirtualDisk_Task
VirtualMachine DefragmentAllDisks
VMware, Inc. 19
Programming Guide
See the VI API Reference Guide for more information. The API Reference Guide is available in the VI SDK 2.5
package, in this path:
\SDK\doc\ReferenceGuide
NOTE Some of the new managed object types or operations may be experimental, and subject to change, as
noted in the VI API Reference Guide.
A complete comparative reference of VI API 2.0 and VI API 2.5 managed objects, operations, data objects,
properties, and faults is available on the VMware API and SDK Documentation page at:
http://www.vmware.com/support/pubs/api_pubs.html
DrsRecommendationReasonCode Use the RecommendationReasonCode
enumerated type.
IDEDiskNotSupported Use the DeviceControllerNotSupported fault
type.
ClusterDrsRecommendation Use ClusterRecommendation.
LicenseManager.featureInfo Use QuerySupportedFeatures.
20 VMware, Inc.
Chapter 1 What’s New in the VI SDK?
DestroyDatastore Do not use this method: DestroyDatastore throws
ResourceInUse. Datastores are automatically
removed when no longer in use, so this method is
unnecessary.
CreateCluster Use CreateClusterEx.
DeleteFile Use DeleteDatastoreFile_Task (a method of the
new FileManager managed object.
QueryMemoryOverhead Use QueryMemoryOverheadEx.
DestroyNetwork Do not use this method: DestroyNetwork throws
ResourceInUse. Networks are automatically
removed when no longer in use, so this method is
unnecessary.
CreatePerfInterval Use UpdatePerfInterval. Historical intervals
cannot be created.
RemovePerfInterval Use UpdatePerfInterval. Historical intervals
cannot be removed.
ClusterDasVmConfigInfo.powerOffOnIsolation Use isolationResponse. If a value is specified in
both powerOffOnIsolation and
isolationResponse, the value in isolationResponse
takes precedence and the value in
powerOffOnIsolation is ignored
CustomizationWinOptions.deleteAccounts Deleting user accounts as part of a customization
routine is not supported as of VI API 2.5: the
deleteAccounts property is ignored. To change the
administrator password, set the administrator
password to blank in the master vm. Sysprep will
then be able to change the password to the one
specified by the password.
VirtualMachineFlagInfo.runWithDebugInfo Use the new monitorType property (an
enumeration comprising string values “debug,”
“release,” and “stats”).
In addition, the Java samples have been improved over previous versions: Some of the code has been
refactored; some of the Java packages have been reorganized. Other changes include:
The supporting utility classes have been moved to their own package, apputil. Inside this package you’ll
find packages vim, vim25, and version. The version utilities facilitate determining the version of the
WSDL on the Web service, and returning the version as a Java String. The version utility classes areused
by DisplayNewProperties, GetVirtualDiskFiles, HostPowerOps, InstallHostPatch, and
QueryMemoryOverhead.
VMware, Inc. 21
Programming Guide
See “Java Samples Summary” on page 24 for a reference table listing all the Java samples and package names.
The next section discusses highlights of three key new samples.
Handling Different API‐ and Object‐Model‐Versions
Obtaining All Information about SCSI Devices
Using HTTP for Cold Migration of Virtual Machine Files
NOTE The “deprecated” label on a feature (type, operation, property) means that a new, better way to meet a
specific requirement exists (better than the deprecated feature). For example, QueryMemoryOverhead
operation (of HostSystem) is deprecated as of VI API 2.5, and a new operation, QueryMemoryOverheadEx
takes its place. Although client applications using deprecated features will continue to work, VMware
recommends that developers use the new type, operation, or property (rather than the deprecation) for client
applications using the VI API 2.5.
You can migrate existing client applications to work with ESX Server 3.5 or VirtualCenter 2.5, and you can
target previous versions (ESX Server 3.0.x, VirtualCenter Server 2.0.x) as well—several Java samples
demonstrating how to code for different targets are provided in the VI SDK package.
For starters, in a mixed target environment, obtaining version information about the server’s API support is
an important initial step. Since the API is exposed as a Web service, the Web service’s WSDL file contains the
information, and can be accessed at the Web service endpoint.
Table 1‐4 lists the new samples included in this release that demonstrate using new features and handling
deprecated object types, properties, or operations.
22 VMware, Inc.
Chapter 1 What’s New in the VI SDK?
DisplayNewProperties Displaying various properties, depending on the WSDL version returned from the
server. Behavior varies, depending the version returned. When connected to an ESX
Server 3.5 or VirtualCenter Server 2.5 systems, DisplayNewProperties obtains (and
displays) several new properties available through the API 2.5, including power
state (runtime.powerState), boot duration (runtime.bootDuration), system health
information (runtime.systemHealthInfo), and time information
(config.dateTimeInfo).
GetVirtualDiskFiles Using new properties of existing managed objects or data objects, depending on the
WSDL version returned from the server. GetVirtualDiskFiles uses the
HostDatastoreBrowser to find virtual disks on a specified virtual machine, to enable
adding virtual disks to the VM. When connected to an ESX Server 3.5 system,
GetVirtualDiskFiles invokes the SearchDatastoreSubFolders_Task using a data
object (VmDiskFilleQueryFilter) that has a new property (controllerType). The
result is that only those disks whose controller type matches the virtual machine
controller will be shown.
HostPowerOps Using new operations on existing managed objects. In the 2.5 object model, the
HostSystem managed object type has two new operations,
PowerDownHostToStandBy_Task, PowerUpHostFromStandBy_Task.
InstallHostPatch Demonstrates using the HostPatchManager, available on ESX Server 3.5.
QueryMemoryOverhead Using a new operation (QueryMemoryOverheadEx) in place of a deprecated
operation.
For example, when connected to an ESX Server 3.5, DisplayNewProperties lists power state
(runtime.powerState), boot durations (runtime.bootDuration), system health information
(runtime.systemHealthInfo), and time zone information (config.dateTimeInfo). Since none of these
properties are supported through the VI API 2.0, when DisplayNewProperties runs against an ESX Server
3.0.x, these properties are not displayed.
As another example, when connected to an ESX Server 3.5 system, GetVirtualDiskFiles invokes the
SearchDatastoreSubFolders_Task using a data object (VmDiskFilleQueryFilter) that has a new
property (controllerType). The result is that only those disks whose controller type matches the virtual
machine controller will be shown.
The PowerDownHostToStandBy sample (PowerDownHostToStandBy.java) demonstrates using a new
operation (PowerDownHostToStandby).
See the VI API Reference Guide for more information. The API Reference Guide is available in the VI SDK 2.5
package, in this path:
\SDK\doc\ReferenceGuide
VMware, Inc. 23
Programming Guide
The Java sample (SCSILunName.java) demonstrates obtaining the complete set of SCSI LUN properties. The
ScsiLun data object includes two new properties—alternateNames, standardInquiry—that can be used to
correlate multiple LUN UUIDs to a single hardware device.
See the VI API Reference Guide for more information. The API Reference Guide is available in the VI SDK 2.5
package, in this path:
\SDK\doc\ReferenceGuide
OptionSpec.java
Create an event history collector for a single VMEventHistoryCollectorMonitor.java
virtual machine and get its latest page.
24 VMware, Inc.
Chapter 1 What’s New in the VI SDK?
Table 1-5. Java samples listing (path starts from \SDK\samples\Axis\java\com\vmware) (Continued)
Directory Description Java filename
Connect to specified service, login using Connect.java
specified credentials, logout.
Creates Folder, Datacenter, and Cluster Create.java
managed entities.
Deletes Folder, Datacenter, and Cluster Delete.java
managed entities.
Displays update information from various GetUpdates.java
virtual machines and hosts.
Demonstrates uses of the Licensing API. LicenseManager.java
Moves the specified Managed Entity,. Move.java
Demonstrates using the PropertyCollector PropertyCollector.java
managed object.
Renames a Managed Entity Rename.java
Demonstrates using the SearchIndex managed SearchIndex.java
object.
Connects to specified service, logs in (if SimpleClient.java
appropriate, assuming the server is configured
to support HTTPS only), retrieves
ServiceContent managed object and then
obtains inventory (managed entities), displays
listing to console, and then logs out.
Displays details about currently running tasks. TaskList.java
Adds a Virtual Switch. AddVirtualSwitch.java
Adds a port group to a virtual switch. AddVirtualSwitchPortGroup.java
Removes a Host VirtualNic from a PortGroup RemoveVirtualNic.java
on a Virtual Switch.
Removes the specified virtual switch. RemoveVirtualSwitch.java
Removes a port group from a virtual switch. RemoveVirtualSwitchPortGroup.java
Uses HTTP “Get” to retrieve all files associated GetVMFiles.java
with a specified virtual machine (configuration,
snapshot, suspend, log, and virtual disk files)
and copies them to a specified local directory.
(Use the ColdMigration.java sample to
subsequently move the files to a different
server.)
VMware, Inc. 25
Programming Guide
Table 1-5. Java samples listing (path starts from \SDK\samples\Axis\java\com\vmware) (Continued)
Directory Description Java filename
Prints all managed entity counters (virtual PrintCounters.java
machine, resource pool) to a specified target file.
Reads performance measurements from the Realtime.java
current time.
An ESX Top look‐alike demonstrating VI VITop.java
Performance monitoring API. Note: This
sample is non‐functional at the present time.
Demonstrates how to use the VIUsage.java
PerformanceManager managed object type.
Creates a one time scheduled task named OneTimeScheduledTask.java
VMPowerOffTask to power off a virtual
machine.
Creates a Weekly recurrence scheduled task to WeeklyRecurrenceScheduledTask.java
reboot the guest of a virtual machine.
Obtains version information from the WSDL GetVersion.java
available on ESX Server and VirtualCenter
Server. Other samples in this sub‐directory use
this class to obtain version information.
Accessing a new property available on ESX GetVirtualDiskFiles.java
Server 3.5 or VirtualCenter 2.5.
Demonstrates exercising an operation available PowerDownHostToStandBy.java
on ESX Server 3.5 or VirtualCenter 2.5.
Demonstrates using a new operation (in place of QueryMemoryOverhead.java
a deprecated operation).
Create a virtual machine. VmCreate.java
Obtains a reference to a virtual machine and VmPowerOps.java
invokes various power operations on the
reference, as specified on the command line
options, such as snapshot, powering‐off, and so
on.
Reconfigure a virtual machine. VmReconfig.java
Performs virtual machine snapshot operations. VmSnapshot.java
26 VMware, Inc.
2
For example, virtual memory enables software to use more memory than is physically installed in a computer,
by swapping data from physical memory to physical disk. Virtualization techniques can be applied to all
layers of an IT infrastructure—networks, storage, laptop or server hardware, operating systems, and
applications.
VMware’s flagship enterprise product, VMware Infrastructure 3, enables virtualization of the wide array of
enterprise computing resources. VMware Infrastructure 3 encompasses ESX Server and VirtualCenter Server,
and several additional server products for distributed resource management, disaster recovery, and high
availability, to name a few.
As with physical IT infrastructure components, virtual infrastructure components must be provisioned,
deployed, monitored, and managed. For VMware infrastructure components, the VMware Infrastructure
object model is a comprehensive set of robust server‐side composite objects that provides this “management”
layer (referred to as “VMware Infrastructure Management”). This object model comprises data structures
(composite object types) for managing, monitoring, configuring, obtaining information, and controlling
life‐cycle operations associated with virtual infrastructure. External clients can access this management
framework through the VMware Infrastructure API.
This chapter provides a brief overview of the VMware Infrastructure object model and API. It includes these
topics:
Introducing the VMware Infrastructure Management Object Model
Understanding the VI API
Using the VI Client to Become Familiar with the Object Model
Using the API Reference Guide
Migration or relocation—Moving virtual machines between hosts using VMotion.
Clustering and failover—Configuring virtual machines and associated storage to fail over between hosts.
VMware, Inc. 27
Programming Guide
Resource management—Backing virtual computing power with VMware HA (high availability) and
VMware DRS (distributed resource management).
Provisioning—Deploying customized virtual machines from templates.
Monitoring—Configuring and reporting status on various conditions within the datacenter.
The virtual infrastructure management framework is accessed by external client applications using the VI API.
VI API is implemented as industry‐standard Web services, hosted on VirtualCenter Server and ESX Server
systems. The VI API complies with the Web Services Interoperability Organization (WS‐I) Basic Profile 1.0,
which includes XML Schema 1.0, SOAP 1.1, WSDL 1.1.
The Web service provides all the operations necessary, including life‐cycle operations, to monitor and manage
virtual infrastructure components—compute resources, virtual machines, networks, storage, and the like.
Web services technology provides operations (same basic concept as “methods” in other programming
languages). Using the VI SDK and the programming language of your choice, you can create client
applications that invoke these operations to perform the full range of server‐side management and
monitoring tasks.
The Web services API is defined in a WSDL (Web Services Description Language) file. The WSDL file is
used by Web‐services utilities to create client‐side proxy code (stubs) that facilitate remote method
invocation, marshaling and unmarshalling object data, and other low‐level details of distributed
object‐oriented applications programming.
Client applications invoke operations by sending SOAP (Simple Object Access Protocol)‐formatted
messages. SOAP is an XML format and is programming‐language neutral. One of the jobs of the
client‐side Web services tools is formatting (transparent to you, the developer) the SOAP messages from
the programming language that you use.
Communications between client and server occur over HTTP or HTTPS (secure HTTP, which uses SSL to
encrypt client‐server communications). The default is HTTPS, but the Web server (on ESX Server and
VirtualCenter Server) can be configured to support HTTP.
The VI SDK provides all the components necessary to work with the VI API, including two versions of the
WSDL files (vim2, vim25), sample code, and various libraries. The Developer’s Setup Guide provides
information about setting up the development environment for using Java and Microsoft .NET (specifically,
using the C# programming language) to create new applications, and information about running the sample
applications included with the VI SDK.
28 VMware, Inc.
Chapter 2 Basic Concepts for Developers
The various managed object types on the server define common administrative and management services one
would expect to find in any datacenter—services such as managing performance (PerformanceManager),
finding entities that exist in the inventory (SearchIndex), disseminating and controlling licenses
(LicenseManager), and configuring alarms to respond to certain events (AlarmManager), for example.
ManagedObjectReference is one of the VMware Infrastructure Management object model’s data object types:
It’s the mechanism that enables distributed computing for VMware virtual infrastructure. A given instance of
a managed object reference (instance of the ManagedObjectReference data object) identifies a specific
managed object on the server, and encapsulates the state and methods of that server‐side object, making them
available to the client application.
Clients invoke methods (operations) on the server by passing the appropriate managed object reference.
Data Objects
A data object is a complex data type that comprises properties only—it does not provide any operations. Data
objects are used throughout the VI API to capture or reflect the state of various properties of managed objects.
As implemented in the VI API, data objects are analogous to structures (struct) in C, C++, and several other
programming languages, or abstract data types (class definition) in Java (Java does not have the notion of a
struct, but rather uses class declarations to define abstract data types.
Properties
Properties contain information about the server‐side objects at a given point in time. Each property is defined
as a specific data type. Data types include:
Simple data types, such as a string, boolean, or integer (or other numeric) datatype. For example, the
ManagedEntity managed object has a name property that takes a string value.
Arrays of simple data types or data objects. For example, a HostSystem managed object contains an
array of virtual machines that are hosted by that physical machine.
Enumerated types (enumeration, or simply, enum) of predefined values. The values can be a collection of
simple data types or data objects. For example, a virtual machineʹs power state can be one of only three
possible string values—poweredOn, poweredOff, or suspended.
Complex data types—data objects such as AboutInfo, Action, and ServiceContent, that have been
specifically defined for the VMware infrastructure object model.
Negotiating composite data structures requires some understanding of nested properties and property paths,
and understanding how the key‐based arrays differ from index‐based arrays.
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 type, or it might be another complex type. If the last
property in the path is a complex type, an instance of the data type is returned.
VMware, Inc. 29
Programming Guide
For example, by specifying a.b.c, if c is an 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 ManagedObjectReference, you get an instance of a
ManagedObjectReference.
Indexed arrays are accessed in the usual manner, using an index integer. Indexed arrays are used for
arrays of data types whose position in the array does not change. For example, the roleList property of
the AuthorizationManager managed object is an array of authorization roles. Adding a new role to the
array does not change the position of existing elements in the array.
Key‐based arrays are used for information whose position is subject to change. A key‐based array (same
basic concept as Perl’s “hash”) uses a unique, unchanging value as a “key” to access an element’s value.
Typically, the key is specified as a string, but integers can also be used—for example, Event arrays use
integers as keys.
The VMware infrastructure management object model uses key‐based arrays to keep track 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.
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.
The various data structures (managed object types, data object types, properties, and so on) are defined in the
VI API ReferenceGuide. The VI API ReferenceGuide provides language‐neutral information about all the
object types and data structures. (Figure 2‐1 shows a UML (unified modeling language) rendering based on
the information from the VI API ReferenceGuide. Note that managed object types have operations (the lower
portion of the class definition box), while the data object and enumeration do not.)
30 VMware, Inc.
Chapter 2 Basic Concepts for Developers
The client‐side proxy code generated from the WSDL includes accessor (“getter”) and mutator (“setter”)
methods for each simple property defined in server‐side managed object and data object types.
The inventory is a collection (in the data structures sense of the word) of all managed entities on the
server‐instances of HostSystem, Datacenter, VirtualMachine, ResourcePool, ComputeResource,
ClusterComputeResource, and Folder.
For an ESX Server system, the VI Client shows the single host at the top‐level of the tree (see the left‐hand pane
in Figure 2‐2.)
Figure 2-2. Example ESX Server (host agent) inventory viewed using the VI Client
While an ESX Server comprises a single root folder (rootFolder) object, with a single (transparent)
datacenter, a VirtualCenter Server can support multiple data centers. VirtualCenter Server also provides
several additional service capabilities and administrative functions.
For example, note the Scheduled Tasks, Events, and Maps icons in the menu bar of Figure 2‐3, compared to the
the menu bar of the ESX Server instance shown in Figure 2‐2, which has none of these icons (and, more
importantly, none of the functionality the functionality they represent).
VMware, Inc. 31
Programming Guide
Figure 2-3. Example VirtualCenter Server inventory viewed using the VI Client
The inventory as displayed in the VI Client is materialized from the content of the server‐side objects at any
given point in time. For example, the inventory shown in Figure 2‐3 (and Figure 2‐2) comprises a single
datacenter with three different virtual machines.
The VI Client uses the information about the objects (the properties, and the relationships among them) to
materialize a hierarchy in the left‐hand pane of its display.
See the VMware Infrastructure 3 online library (Managing the VI Client Inventory—Understanding VI Client
Objects) for additional information about the VI Client and how it represents server‐side objects graphically.
Using the Managed Object Browser (MOB) to Explore Objects on the Server
Another way to look at the objects on the server is by using the Managed Object Browser. The Managed Object
Browser, or MOB, is a web‐based server application hosted on all ESX Server and VirtualCenter Server
systems. The MOB lets you look at the objects that exist on the server.
CAUTION Despite the word “browser” in its name, the MOB is not a read‐only mechanism—it’s a powerful
tool that can be used to make changes to the server, by clicking the InvokeMethod link (available on any
method (operations) for managed objects). As you examine the server using the MOB, be aware of its
capabilities so that you donʹt make unintended changes to the server.
1 Launch a browser.
2 Enter the fully‐qualified domain name (or the IP address) for the ESX Server host or VirtualCenter Server:
https://hostname.yourcompany.com/mob
Youʹll be notified that the “VMware VI SDK Browser requires a username and password,” with a prompt
requiring a user name and password.
32 VMware, Inc.
Chapter 2 Basic Concepts for Developers
3 Enter the user account and password for the server system‐typically, root/password for the ESX Server
system, and Administrator/password for VirtualCenter Server system. (Obtain the user account and
password information from your VMware system administrator, if necessary.)
After entering user account and password, youʹll see some preliminary warning messages regarding the
authority of the SSL certificate, such as “Website Certified by an Unknown Authority” (assuming that the
default server certificate provided by VMware has not been replaced. The specific message text varies by
web browser.)
You can safely disregard such warnings and continue to logon to the MOB (assuming that VMware is the
certificate authority).
NOTE If the ESX Server or VirtualCenter Server system has been configured to support regular HTTP
(non‐SSL) connections, you will not be prompted for user name and password, nor will you see any
SSL‐certificate‐related warnings.
Upon successful connection to the MOB, the browser displays the managed object reference for the service
(ManagedObjectReference:ServiceInstance), its properties (with current values), and available methods
(see Figure 2‐4).
Figure 2-4. ServiceInstance is the starting point for navigating server-object instances
ServiceInstance is the starting point for examining server‐side objects using the MOB.
Complex data types (including collections, such as arrays, enumerations, and data objects, including managed
object references), display a link the Value column displays a link to the specific instance of the object
comprising the property.
To explore the objects on the server, simply click on the various links in the Value column to navigate to the
page that displays the object. For example, to find out more about the ServiceContent type, click on the
content link to display ServiceContent and its properties.
VMware, Inc. 33
Programming Guide
The property values are specific instances of data objects, references to singleton managed objects of a specific
type, or simple data types (a string, boolean, or number, for example). Most of the service instance properties
are references to singleton objects used to manage objects of a given type.
capability—An instance of a Capability data object comprising flags that indicate server support (or
lack of support) for specific features. (The Capability data object comprises flags that indicate support
for features on the server instance.) For example, multiHostSupported capability will be true for
VirtualCenter but false for ESX Server (host agent).
content—An instance of a ServiceContent data object comprising the root folder of the inventory, the
session manager, property collector, and various other service‐wide or session‐wid managed objects, such
as the AuthorizationManager, the TaskManager, and the EventManager. (The ServiceContent data
object comprises the bulk of a service instance’s properties, including the root folder of the inventory, the
session manager, and the property collector.
serverClock—The server date and time (xsd:dateTime).
The service instance also gives you access to the various session management objects, such as the
AuthorizationManager, the TaskManager, and the EventManager.
In simple terms, ServiceContent is a “large grained” server object, providing access to everything the server
offers. ServiceContent is a data object whose properties include numerous managed object references that
point to specific instances of managed object types (see Figure 2‐6).
34 VMware, Inc.
Chapter 2 Basic Concepts for Developers
Figure 2-6. ServiceContent data object comprises the specific server instance
For example, the rootFolder property is a ManagedObjectReference to an instance of a Folder managed
object; the perfManager is a ManagedObjectReference to a specific instance of a PerformanceManager
managed object type, and so on.
These managed object types define the typical administrative and management services one would expect to
use in any datacenter, virtual or otherwise—services such as managing performance (PerformanceManager),
finding entities that exist in the inventory (SearchIndex), disseminating and controlling licenses
(LicenseManager), and configuring alarms to respond to certain events (AlarmManager), for example.
In addition to providing services to the server as a whole, the ServiceContent object also contains references
to inventory objects—objects that are specific instances of entities, such as hosts and the virtual machines that
run on them, which comprise the inventory of manageable virtual‐datacenter components.
From the ServiceContent object, you can “drill down” into the inventory hierarchy.
VMware, Inc. 35
Programming Guide
Figure 2-7. The MOB provides real-time information about the server-side objects
Managed objects are server‐side objects. Managed objects are not passed to client applications, except by
reference, using specific instances of the ManagedObjectReference data type.
Manipulating or monitoring server‐side managed objects requires client application code to first obtain a
managed object reference to the specific object of interest.
With a managed object reference, you can invoke operations using the Mo_Ref, to effect or monitor changes on
the server.
Clients invoke methods (operations) on the server by passing the appropriate managed object reference to the
server, in the method invocation.
36 VMware, Inc.
Chapter 2 Basic Concepts for Developers
From the ServiceContent page, click the link for the value of the rootFolder property to display the root of
the inventory, containing all the managed entities.
The inventory comprises the collection of all managed entities on the server.
A “managed entity” is one of the seven specific managed object types that extends the ManagedEntity
managed object type.
VMware, Inc. 37
Programming Guide
The host agent (ESX Server) inventory hierarchy is similar to the VirtualCenter, but limits some objects to
single instances—for example, a host agent can manage a single host only, so only one host agent managed
entity exists in the ESX Server inventory.
As shown in Figure 2‐10, only VirtualMachine and ResourcePool managed objects can have multiple
instances in the ESX Server hierarchy.
Inventory managed objects are also known as “managed entities” because they extend the ManagedEntity
managed object type (base class).
38 VMware, Inc.
Chapter 2 Basic Concepts for Developers
The current virtual infrastructure includes seven managed object types that extend the ManagedEntity
superclass (directly or indirectly, in the case of ClusterComputeResource).
ClusterComputeResource—Abstracts a cluster of HostSystem objects as a unified compute resource for
virtual machines.
ComputeResource—Abstracts the physical resources of a host system and enables them to be associated
with the virtual machines that run on the host.
Datacenter —Contains other managed entities, including folders, virtual machines, host systems.
VirtualCenter Server instances support multiple datacenters; ESX Server supports only one datacenter
(although the Datacenter object is not visible through the VI Client).
Folder—The Folder managed object type can be used to organize virtual machines and hosts in an
inventory. Folders can be nested inside other folders to any depth, but any specific folder must contain
objects of a single type—for example, datacenters, virtual machines, or hosts—or other folders.
HostSystem—Comprises a single physical machine
ResourcePool—Divides physical resources among virtual machines
VirtualMachine—Comprises a single virtual machine
The list of managed entities is in simple alphabetical order. However, the inventory is organized hierarchically,
based on the relationships of the managed objects, which is established by the properties as defined on a
specific server instance.
ManagedEntity is an abstract base class (that extends the ExtensibleManagedObject managed object type)
(see Figure 2‐11).
As shown in Figure 2‐1, properties can nest to several levels deep. For example, a VirtualMachine’s runtime
property is defined as a VirtualMachineRuntimeInfo data object, which in turn comprises several
properties, including a powerState property that is defined as an enumeration (VirtualMachinePowerState,
comprising three different string values.
To define the path to a specific property
The ManagedEntity base class includes several properties and operations that are inherited by each
subclass—for example, the name property is an inherited property.
In addition to common properties and methods that are inherited from the base class, each managed entity
type has its own special‐purpose methods and properties.
VMware, Inc. 39
Programming Guide
For example, the HostSystem managed object has an EnterMaintenanceMode_Task operation; the other
managed entities do not.
The VI API ReferenceGuide provides complete information about all the managed object types and other data
structures.
The API Reference Guide is available in the VI SDK package, in this sub‐directory:
SDK/doc/ReferenceGuide
40 VMware, Inc.
3
Service-Management Operations 3
This chapter describes several managed object types that enable configuring or controlling a server instance.
Note that much of this information (and more) can be obtained from the VI API Reference. This chapter
includes overviews of these managed object types:
AuthorizationManager and SessionManager Provide Security Services
Finding Objects and Properties: The PropertyCollector Managed Object
Finding Objects and Properties: SearchIndex Managed Object
EventManager Managed Object Type
TaskManager Managed Object Type
ScheduledTaskManager Managed Object
AlarmManager Managed Object
PerformanceManager Managed Object Type
The SessionManager and AuthorizationManager work together, by using a several data structures that
model users, user accounts, privileges, and roles.
A client application obtains a session (a specific instance of a UserSession data object), and the
SessionManager keeps track of different sessions and the objects associated with the session.
The SessionManager managed object type provides identification, and the Permissions object provides
access control.
VMware, Inc. 41
Programming Guide
passwordFilePath
AcquireLocalTicket
userName
currentSession
defaultLocale
Login UserSession
Logout
fullName
message
key
messageLocaleList
lastActiveTime
sessionList
locale
SetLocale
loginTime
supportedLocaleList
messageLocale
TerminateSession
userName
UpdateMessage
Legend
method: boldface
property: roman
The SessionManager (Figure 3‐1) enables a client to create a session. A session is associated with a specific
user account.
The SessionManager defines the lifetime and visibility of certain objects, such as PropertyCollector filters.
Session‐specific objects are not visible outside the session in which they were created. When a session
terminates, all session‐specific objects are destroyed.
SessionManager has Login and Logout operations that allow users to create and end sessions. (Sessions can
also be ended by an account with system administrator privileges, using the TerminateSession operation.)
The system administrator can configure the server instance to support local sessions, which enable users with
credentials on the host to logon based on those privileges.
A client application executing on behalf of a local user can invoke the AcquireLocalTicket operation to
obtain a one‐time user name and password for logging on without entering a subsequent password. This
feature is useful for host‐based utilities that run at in the local console.
If a Web services session is lost, the VirtualCenter Server or ESX Server performs garbage collect on the session
within approximately 30 minutes.
Once a session exists, the AuthorizationManager (Figure 3‐2) can check that the user’s privileges before
performing operations, ensuring that user account has the appropriate permissions. If not, the
AuthorizationManager returns a NoPermission fault or a ManagedObjectNotFound fault.
42 VMware, Inc.
Chapter 3 Service-Management Operations
Permission
ManagedEntity
entity ...
group
principal
propagate AuthorizationRole
roleId info
name
privilege AuthorizationPrivilege
roleId name
Legend system onParent
method: boldface privGroupName
property: roman privId
The AuthorizationManager depends on one or more Permission objects (data objects associated with roles)
to prevent or allow access to any specific object.
Every managed entity has one or more Permissions objects attached to it. Permissions may attach directly
to a managed entity, or may be inherited from a parent entity in the inventory tree.
A Permission data object associates a user with a privilege to perform an operation on the object to which the
Permission object is attached. A Permission object must contain three things:
A managed entity reference
A user name or group name
A role
The managed entity reference identifies the managed object to which the permission applies. However, some
operations do not operate directly on a single managed object. In those cases, the permissions on the
ServiceInstance object (at the root of the inventory hierarchy) apply.
To obtain access to a specific managed entity, the user name for both the current session and the Permission
object must match, or the user must be a member of the specified group (if the permission includes a group
name).
A role is a collection of privileges. For convenience in managing privileges, the VMware Infrastructure object
model provides pre‐defined roles such as “Administrator” and “Virtual Machine Power User” that group
privileges into collections commonly needed by users performing functions appropriate to the role name.
Clients (if they have appropriate permissions) may use the AuthorizationManager to define new roles for
their own installations.
The AuthorizationManager object provides methods to create, alter, and delete Permission objects and
roles. AuthorizationManager also allows a client to view the list of privileges (which is fixed) and the list of
roles that are currently defined.
For standalone ESX Server hosts, the UserDirectory object enables a client application to browse the set of
users and groups on the host. UserDirectory has only one method, RetrieveUserGroups, which is used to
search for either user names or group names. The matches can be exact or partial (substring) matches, or the
client can request the list of all users on the machine.
VMware, Inc. 43
Programming Guide
Client applications can use the PropertyCollector to create one or more session‐specific property filters for
the length of the session (or until explicitly terminated). Two important data structures associated with the
PropertyCollector are the
Legend
method: boldface
property: roman
44 VMware, Inc.
Chapter 3 Service-Management Operations
Event objects record significant state changes of managed entities, such as:
Powering a virtual machine on or off.
Deploying a new virtual machine.
Reconfiguring a compute resource.
Adding a new host to VirtualCenter.
An event history collector is created to filter events from the entire database of past events. The specification
for creating the event filter can select events during a specific time range, belonging to a particular user, or
associated with certain other objects, such as alarms.
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; a scheduled task event contains a reference to the responsible
scheduled task and the managed entity associated with the scheduled task. See “ScheduledTaskManager
Managed Object” on page 47.
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 locale‐specific. The locale‐specific strings used to create events are stored in the
EventManager’s description array.
The EventManager also lets you log a user‐defined event. You can use the EventManager to save historical
information to supplement the predefined events, or to provide markers when browsing event history.
VMware, Inc. 45
Programming Guide
TaskManager
CreateCollectorForTasks TaskHistoryCollector
description latestPage
maxCollector ReadNextTasks
recentTask ReadPreviousTasks
TaskInfo
cancelable
Legend canceled
Task completeTime
method: boldface
CancelTask entity
property: roman
info entityName
error
eventChainId
key
locked
name
progress
queueTime
reason
result
startTime
state
task
Task objects are used to track operations that do not complete immediately, such as:
Shutting down a virtual machine.
Migrating a virtual machine.
Sending an email message as a result of an alarm.
Clients may start a task and check the status. Tasks may be automatically started based on a client operation
request if the task is expected to take a long time. Tasks can also be scheduled to take place according to a
schedule or based on a specific event.
Figure 3‐7 shows the connections among the various objects related to tasks.
46 VMware, Inc.
Chapter 3 Service-Management Operations
ServiceContent TaskInfo
taskManager entity
reason
task
TaskManager
recentTask Task
description
info TaskReason
(subtyped)
TaskDescription
reason
state
All task history is kept in a database. You can view older tasks by creating a task history collector to select the
desired tasks from the database. The specification for creating the task filter can select tasks during a specific
time range, belonging to a particular user, or in a particular state. You can also limit the selection to specific
alarms, entities, or scheduled tasks.
Task objects keep status information such as the task’s start time, current progress (as percentage complete),
state (such as queued or running), and completion status. All this information is preserved in the historical
record of the task. However, the managed object for the task is needed only while the task is still active and
referenced by the TaskManager. Thus, the Task managed object is detached from its TaskInfo data object, so
the Task object can be discarded when it’s no longer needed.
After starting up the VirtualCenter server.
At a specified time.
At hourly, daily, weekly, or monthly intervals.
Figure 3-8. ScheduleTaskManager Managed Object Type and ScheduledTask Data Object
ScheduledTaskManager
ScheduledTask
CreateScheduledTask
description info ScheduledTaskInfo
RetrieveEntityScheduledTask ReconfigureScheduledTask
activeTask
scheduledTask RemoveScheduledTask
entity
RunScheduledTask
error
lastModifiedTime
lastModifiedUser
nextRunTime
prevRunTime
progress
result
Legend
scheduledTask
method: boldface
state
property: roman
VMware, Inc. 47
Programming Guide
The run status and progress of a scheduled task are tracked in the associated ScheduledTaskInfo object.
While the scheduled task is running, a reference to a Task object is included.
info alarm
ReconfigureAlarm creationEventId
RemoveAlarm entity
key
AlarmManager lastModifiedTime
Create Alarm lastModifiedUser
GetAlarm
defaultExpression AndAlarmExpression
description
GetAlarmState expression
AlarmExpression
OrAlarmExpression
expression
MetricAlarmExpression
metric
AlarmDescription operator
action red
entityStatus yellow
expr type
hostSystemConnectionState
metricOperator StateAlarmExpression
metricType operator
stateOperator red
virtualMachinePowerState yellow
statePath
type
AlarmState
Legend Description
alarm
method: boldface entity ManagedEntity key
property: roman key label
overallStatus ... summary
time
An Alarm can be triggered conditionally. The AlarmExpression data object type provides a way to specify
complex conditions for triggering alarms. Actions that can be triggered by alarms include:
Invoking an operation through the API.
Running a shell script on the VirtualCenter server.
Sending an email message.
Sending an SNMP trap.
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.
Alarm expressions let you define conditions to monitor, and to combine conditions using boolean logic. This
flexibility allows you to configure VirtualCenter to monitor your datacenter in whatever way you choose.
When an alarm triggers, it produces an event for the event history database. The action triggered by the alarm
may also leave an event history.
48 VMware, Inc.
Chapter 3 Service-Management Operations
PerfMetricId
counterId
instance
PerfCounterInfo
associatedCounters
Legend groupInfo
key
method: boldface
nameInfo
property: roman
rollupType
statsType
unitInfo
PerfEntityMetric PerfSampleInfo
entity interval
sampleInfo timestamp
value PerfMetricSeries
id
There are two basic ways to query statistics:
QueryPerf accesses metrics for a list of managed entities. Use this when you want to monitor specific
entities that provide performance data.
QueryPerfComposite accesses metrics or a single managed entity and all of its child entities. Use this
when you are interested in a group of related entities, such as all virtual machines that belong to a given
resource pool.
When you invoke QueryPerf or QueryPerfComposite, you can choose a PerfInterval to suit your
reporting need. PerfIntervals are specified by their sampling periods, called “interval IDs.” Or you can
choose the performance metric provider’s raw sampling period, called its “refresh rate,” for data within the
past hour only. When you use the provider’s refresh rate, you access an implied PerfInterval with a fixed
sample period, and a fixed retention length of one hour.
Data older than one hour is consolidated into the shortest defined PerfInterval and stored in the historical
database. Historical performance data is kept according to the defined PerfIntervals. When the retention
length expires, older data is summarized into the next larger PerfInterval.
Performance counters are available for a wide variety of system performance characteristics, and in a number
of different forms. Objects comprising statistics include:
CPU usage, with breakdown into system processes, wait time, ready time, and so on.
VMware, Inc. 49
Programming Guide
Memory usage, with breakdown into active, shared, heap, swap, and so on.
Network usage, with breakdown into statistics for transmitted and received packets.
Disk usage, with breakdown into reads and writes.
System uptime and heartbeat statistics.
Performance measurements can be collected for:
Hosts (HostSystem managed object)
Virtual machines (VirtualMachine)
Resource pools (ResourcePool)
Statistics types are of three kinds:
Absolute value—Raw measurement of specific quantity.
Delta—Measurement of the difference between successive raw measurements.
Rate—Measurement of differences over time normalized to standard interval.
Counter types:
Average
Minimum
Maximum
Latest
Summation
50 VMware, Inc.
4
Folder Managed Object
Datacenter Managed Object Type
VirtualMachine Managed Object Type
HostSystem Managed Object Type
Datastore Managed Object Type
ComputeResource Managed Object Type
ResourcePool Managed Object Type
ClusterComputeResource Managed Object Model
VMware, Inc. 51
Programming Guide
Task
CancelTask
info
A Folder can contain child objects only of types that match one of the values of its childType property, in
addition to any nested folders it contains.
52 VMware, Inc.
Chapter 4 Introduction to the Inventory
HostConnectInfo
clusterSupported
datastore
host
network
serverIp
vimAccountNameRequired
vm
Legend
Folder
method: boldface
property: roman ...
VMware, Inc. 53
Programming Guide
Most virtual machine properties are instances of data objects, such as VirtualMachineConfigInfo.
VirtualMachineSummary —A data object that encapsulates several basic properties, such as current
status of the virtual machine (powered on, powered off), basic performance statistics, and a reference
(managed object reference) to the containing VirtualMachine object. This data object lets you obtain
information about common properties without specifying the properties individually to the
PropertyCollector. The VirtualMachineSummary object includes a reference to the containing
VirtualMachine object, so it is also convenient for clients that monitor only the
VirtualMachineSummary (using the PropertyCollector). A client can use the reference to invoke an
operation on the VirtualMachine object.
The VirtualMachineConfigInfo contains information about the virtual machine’s current configuration. For
example, the annotation property is a user‐supplied string that describes this particular virtual machine; the
files property contains information about files associated with the virtual machine; and the UUID property is a
unique BIOS identifier for the virtual machine.
54 VMware, Inc.
Chapter 4 Introduction to the Inventory
config Network
customValues
hardware DestroyNetwork
Task host
host
overallStatus inUse
... name
Legend quickStats
method: boldface rebootRequired summary
property: roman runtime UsageSummary
vm
The HostSystem (Figure 4‐5) managed object type encapsulates the hardware subsystems that support a
virtual machine.
Most all host system properties are instances of various data objects, such as HostHardwareInfo. Some of the
other important properties include:
HostSystem
HostListSummary—Data object that encapsulates several frequently accessed HostAgent
properties, such as hardware configuration information, current status of the host system, and some
basic performance statistics.
VMware, Inc. 55
Programming Guide
HostCapability—Data object that provides quick access to common properties (and circumvents
using the PropertyCollector). Comprises combined description of the host hardware and software
capabilities.
HostConfigInfo—The configuration information for the host.
HostHardwareInfo—The Hardware characteristics of the host.
HostDatastoreBrowser—The interface to access files in the datacenter.
The HostCapability data object type identifies features that depend on the specific hardware or software on
the host.
For instance, managed hosts (ESX Server hosts being managed by VirtualCenter Server) have VMotion
capability; standalone hosts do not.
If the host lacks a specific capability, the server typically issues a NotSupported fault (if a client attempts to
invoke an unsupported capability).
As with some of the other object types provided in the VMware Infrastructure API, the HostCapability data
object type is extensible.
When a client requests the capabilities of servers whose version is newer than the client, the server may reply
with capabilities that are unknown to the client. These are present in the reply as dynamic properties, which
are name‐value pairs.
HostConfigInfo
The HostConfigInfo data object type comprises host configuration properties such as storage configuration,
hyperthreading, and network configuration.
The HostConfigInfo data object type also contains the HostNetCapability data object type, which
publishes network‐related capabilities of the host, such as NIC teaming. The HostNetCapability data object
type, like the HostCapability data object type, is extensible with dynamic properties.
HostHardwareInfo
The HostHardwareInfo data object type, contained within the HostSystem managed object type, describes
the specifics of the host system’s hardware devices and characteristics. This is where you find CPU speeds,
chip types, PCI devices, NUMA characteristics, and other hardware details not present in the
HostListSummary.
HostDatastoreBrowser
The HostDatastoreBrowser managed object type, contained within the HostSystem managed object type,
provides an interface to list files on a set of datastores. A client can present this information to a user who needs
to decide where to put virtual machine files.
56 VMware, Inc.
Chapter 4 Introduction to the Inventory
HostSystem
...
Datastore
browser
capability DatastoreSummary
DestroyDatastore
accessible
host
capacity
info
datastore
RefreshDatastore
freeSpace
RenameDatastore
name
summary
url
vm
VirtualMachine
Legend ...
method: boldface
property: roman
Access to files and virtual machines uses a path name prefixed with the name of the datastore (in square
brackets) containing the files. For example, a virtual machine configuration file can be referenced as:
[data1]vmdir/linux/vm25/debian.vmx
A Datastore object contains a DatastoreSummary object. The DatastoreSummary object contains the
capacity and free space information for the datastore. It also contains a reference to the full Datastore object
that contains the DatastoreSummary object.
The Datastore, HostSystem, Datacenter, ComputeResource, and VirtualMachine data objects are linked
as follows:
Each HostSystem data object keeps a list of references to Datastore objects representing the datastores
mounted by the host.
Each Datastore data object contains a list of references to HostSystem managed objects, identifying the
hosts that have mounted that datastore.
Each Datacenter object keeps a list of references to the datastores it manages.
Each Datastore object keeps a list of references to VirtualMachine objects representing the virtual
machines stored on the datastore.
Each ComputeResource object keeps a list of references to datastore objects available to it.
VMware, Inc. 57
Programming Guide
ResourcePool
ComputeResourceSummary childConfiguration
config
effectiveCpu
CreateResourcePool
effectiveMemory
DestroyChildren
numActiveVmotion
MoveIntoResourcePool
numCpuCores
owner
numCpuThreads
resourcePool
numEffectiveHosts
runtime
numHosts
summary
numLogicalCpus
UpdateChildResourceConfiguration
numRunningVMs
Legend UpdateConfig
numVmotions
method: boldface vm
overallStatus
property: roman totalCpu
totalMemory
The ComputeResource managed object represents either a single host or a cluster of hosts available for
backing virtual machines.
A ComputeResource contains lists of hosts, datastores, and network objects. Properties of the
ComputeResource include:
A ComputeResourceSummary data object, containing current usage status and information on the
resources available for virtual machines.
An EnvironmentBrowser object that allows the client to browse files on datastores, HardwareInfo
objects, and ConfigOption objects.
A root ResourcePool for the ComputeResource.
Resource pools are configured with absolute values for minimum and maximum quantities of each resource,
enabling system administrators to guarantee service levels for virtual machines, by resource.
Resource pools can also be configured in terms of shares, which allow a system administrator to specify the
relative importance of virtual machines using a resource pool.
58 VMware, Inc.
Chapter 4 Introduction to the Inventory
ResourceConfigSpec
cpuAllocation
entity
lastModified
ResourcePool
childConfiguration
config
owner ComputeResource
runtime
summary
...
vm
DestroyChildren
MoveIntoResourcePool ResourcePoolSummary
UpdateChildResourceConfiguration
UpdateConfig
CreateResourcePool
resourcePool
VirtualMachine
...
Legend
method: boldface
property: roman
A compute resource always has at least one resource pool associated with it. The root resource pool
represents all of the CPU and memory resources available from the host or the aggregate of hosts in the
compute resource. In some environments, the root pool can be divided between child resource pools, which
can be subdivided to arbitrary depths, allowing the flexibility to implement complex resource allocation
policies between competing needs.
Virtual machines, as well as resource subdivisions, are known as “children” of a resource pool.
As its name implies, the ClusterComputeResource managed object type handles VMware infrastructure
when deployed on clustered hardware. The ClusterComputeResource managed object type includes several
operations and properties designed to support VMware HA (high availability) and VMware DRS (distributed
resource management), including:
The AddHost_Task and MoveInto_Task operations enable building a cluster by adding host machines.
The RecommendHostsForVm operation selects the host in a cluster with sufficient resources to power‐on a
virtual machine.
The ApplyRecommendation operation migrates a set of virtual machines between hosts in the cluster to
achieve more efficient resource usage. Recommendations are prepared in the background by the VMware
DRS service and stored in the drsRecommendation property of ClusterComputeResource.
VMware, Inc. 59
Programming Guide
ClusterDrsMigration
Legend HostSystem cpuLoad
method: boldface destination
...
property: roman destinationCpuLoad
destinationMemoryLoad
key
memoryLoad
source
sourceCpuLoad
sourceMemoryLoad
time
vm
Hosts cannot be individually removed from the cluster. The Destroy_Task operation removes the entire
cluster. To reconfigure a cluster, first use Destroy_Tast to delete the cluster, and then create a new cluster
using the CreateCluster operation of the Folder managed object.
Both VMware DRS and VMware HA can be configured by the user. To make changes to the cluster
configuration, invoke the ReconfigureCluster_Task operation, passing a ClusterConfigSpec data object
that describes the changes.
The current configuration of the ClusterComputeResource (for both VMware DRS and VMware HA) is
available in the ClusterConfigInfo property.
60 VMware, Inc.
5
Obtaining Managed Object References
Creating a Specification That Filters Objects and Properties
Using ServiceContent Object’s searchIndex Property
Traversing Objects
Synchronizing Data
Many of the sample applications provided in the VI SDK package use the PropertyCollector and its
methods to obtain objects or properties, including these:
Java sample: SDK\samples\Axis\java\com\vmware\samples\general\PropertyCollector.java
C# sample: SDK\samples\DotNet\SimpleClient
Using the SearchIndex managed object to obtain a managed object reference to the managed entity of
interest. The SearchIndex can return managed object references to specific managed
entities—ComputeResource, Datacenter, Folder, HostSystem, ResourcePool,
VirtualMachine—given an inventory path, IP address, or DNS name. (You can find values of these
properties by using the Managed Object Browser.)
Using the PropertyCollector managed object.
Using any available accessor methods on the ServiceContent object. The ServiceContent data object
encompasses the root folder of the inventory tree the PropertyCollector.
The SearchIndex managed object provides operations that use a property value of a ManagedEntity to
return a managed object reference to the ManagedEntity. If you don’t have the value, the easiest way to find
the property value is to browse the Managed Object Browser for the particular object you want.
VMware, Inc. 61
Programming Guide
The string to use is the value of the hostName property.
This operation takes the same parameters as FindByUuid: a SearchIndex managed object reference, a string
(in this case, the DNS name), and a boolean parameter. If set to true, the search is limited to virtual machines.
If set to false, the search is limited to hosts. Like FindByUuid, you can set an optional parameter, datacenter,
that limits the search to a particular Datacenter. Otherwise, the operation searches the entire inventory.
You can also search for the objects by:
IP address
UUID (universally unique identifier)
inventory path
datastore path
In addition, you can simply find all the children objects (using the FindChild operation) of a specific managed
entity.
See the VI API ReferenceGuide for more information about these operations.
62 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
Figure 5‐1 shows the configuration information for a virtual machine, including the virtual machine’s UUID
(universal unique ID) property and value. In your client application code, you can pass this string to the
FindByUuid method:
String uuid = "502c4e80-aa5b-3aa1-56ca-e05fdcbd6e54";
ManagedObjectReference vmRef = my_conn.findByUuid(_sic.getSearchIndex(), null, uuid, true);
The null value is being passed for the datacenter argument—you could limit the search to a specific datacenter,
but in this case, the entire inventory will be searched. The boolean argument “true” specifies that you want to
limit the search to virtual machines (and not other managed entity types).
type—The target object. A string property that specifies the type of managed object you want the
property collector to collect. For a list of allowable values, see the type property in the VI API
ReferenceGuide.
pathSet—(optional) An array of string values that specifies the property (or properties) of the managed
object that you want to retrieve. If this property is not set, the all property is used to collect all properties.
all—(optional) A boolean property. If set to true, any value set for the pathSet property is ignored. If
not present, the property defaults to false.
If only the type property is set, you are specifying that you want to collect only the managed object type
specified by that property. The next section shows an example of this situation
In this example, you are specifying that you want to collect virtual machines. No properties (the all property
is false and the pathSet property is not set), just virtual machines. You construct the object as an array since
the PropertyFilterSpec (to be discussed below) requires a PropertySpec array. Also, since you defined it
as an array, you could specify multiple object types and properties if you wanted (see “Retrieving Information
from Multiple Objects” on page 64).
Example 5-2. Using the PropertySpec to Find All the Properties of an Object
PropertySpec[] pSpec = new PropertySpec[] { new PropertySpec() };
pSpec[0].setAll(new Boolean(true));
pSpec[0].setType("VirtualMachine");
VMware, Inc. 63
Programming Guide
The pathSet property is constructed as a string array. This enables you to add more properties to the
collection. For example, suppose you want to find not only the power states but also the maximum CPU and
memory usage at runtime? Example 5‐4 shows the PropertySpec for this.
Nested properties are specified using dot notation. If the property is nested more than one level below the
ManagedObject in the object’s property hierarchy, you must provide the fully‐qualified path. In Example 5‐4,
runtime is a property of the VirtualMachine. runtime is a VirtualMachineRuntimeInfo object with
properties of its own. powerState, maxCpuUsage, and maxMemUsage are properties of the
VirtualMachineRuntimeInfo object. Therefore the values are expressed as runtime.powerState,
runtime.maxCpuUsage, and runtime.maxMemUsage.
NOTE 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 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 complex type, then you get an instance of
that type.
pSpec[1].setType("HostSystem");
In the first line, the array is constructed with two elements. In pSpec[0], you specify the first object you want
to collect. In pSpec[1], you specify the second.
obj—The starting object. Where the collection will begin. The collection does not check or collect anything
above this object in the property or inventory hierarchy.
64 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
skip—A boolean property that, when set to false, checks that the starting object matches the type
specified in the PropertySpec.
selectSet—An optional property that defines an array of SelectionSpec objects. If the selectSet
property exists, it specifies additional objects to search. If selectSet does not exist, the property collector
collects from the starting object only (assuming the skip property is set to false).
childEntity (Datacenter)
...
childEntity(VirtualMachine) childEntity (VirtualMachine)
runtime.powerState runtime.powerState
Figure 5‐2 shows an example of a property hierarchy from the top of an inventory tree (the rootFolder
property of the ServiceInstance object) to the powerState property. You can make your starting object any
one of these managed objects. If you are looking for the powerState of a specific virtual machine, you could
even make the starting object the virtual machine itself. The closer your starting object is to the object whose
information you are collecting, the more efficiently your application returns results.
To use the rootFolder as the starting object, you can obtain a managed object reference to it by using an
accessor method, as shown by the code sample snippet in Example 5‐6.
The easiest way is to get other objects in the hierarchy is to use one of the SearchIndex operations. For
example, you can use the Managed Object Browser to find the inventory path to a Folder object, then use the
FindByInventoryPath operation to return the managed object reference for that Folder. Example 5‐7 shows
a code snippet for a path based on Figure 5‐2 above.
Most of the time, this is not a problem. For example, using the hierarchy shown in Figure 5‐2, if your
PropertySpec type property is set to “VirtualMachine” and the ObjectSpec obj property (the starting
VMware, Inc. 65
Programming Guide
object) is set to the rootFolder, setting the skip property to true should not cause a problem. If the starting
point is a virtual machine and the skip property is set to true, and you are collecting virtual machine objects,
a null object may be returned.
propspecary[1].setAll(new Boolean(false));
propspecary[1].setType("HostSystem");
propspecary[1].setPathSet(new String[] {"runtime.connectionState"});
obSpec[1].setObj(startObj2);
obSpec[1].setSkip(new Boolean(false));
obSpec[1].setSelectSet(new SelectionSpec[] { folderTraversalSpec,
computeResourceHostTraversalSpec } );
The PropertyFilterSpec object contains two properties:
objectSet—An array of one or more ObjectSpec objects. Each object defines where you want to search
for the information you want. See “Specifying the Starting Point for a Search Using an ObjectSpec” on
page 64 for more information.
propSet—An array of one or more PropertySpec object. Each object specifies the information you want.
See “Specifying the Properties or Objects” on page 63 for more information.
66 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
return oc[0].getPropSet()[0].getVal();
}
}
In Example 5‐10, once the PropertyFilterSpec has been defined, you retrieve the information with the
RetrieveProperties operation. This operation takes the following parameters:
PropertyCollector ManagedObjectReference—The PropertyCollector is a property of the
ServiceContent object, so you can use an accessor method to get this object. In Example 5‐10, the
RetrieveServiceContent operation returns the ServiceContent object.
specSet—An array of PropertyFilterSpec objects. As described in the previous sections, this object
describes what information you want (ManagedObject and properties) and where you want to start
looking for it.
The RetrieveProperties operation returns an ObjectContent object. This object is an array, each element
of which contains the two properties that represent the two parts of the information:
obj—ManagedObjectReference. The target object for which you are searching.
propSet—(Optional) An array of objects. Each element in the array represents a target property of the
target object. Each element consists of two properties: name (the path to the property) and val (the value
of the property). Example 5‐10 uses a get method to return the value of the property.
return oc[0].getPropSet()[0].getVal();
VMware, Inc. 67
Programming Guide
Traversing Objects
To obtain a single object, there’s no need for traversal. Also, if the starting object of the collection is the same
as the target object, there’s no need for traversal.
To traverse each managed object that lies in the property hierarchy between your starting object (the obj
property of the ObjectSpec) and your target object (the type property of the PropertySpec). The objects to
be traversed include your starting object.
Figure 5-3. Retrieving Information about Performance Counters: Starting Object = Target Object
starting object (obj) PerformanceManager
perfCounter
In this case, getting to the target object requires no managed objects other than the starting object (which is the
same as the target object). As shown in Figure 5‐3, you only need a PropertySpec and ObjectSpec.
Figure 5-4. Starting Object and Target Objects—Traversals Needed for Virtual Machines
starting object (obj) rootFolder (Folder)
...
target object (type) childEntity(VirtualMachine) childEntity (VirtualMachine)
runtime.powerState runtime.powerState
In Figure 5‐4, the starting object is the rootFolder. The target object is “VirtualMachine”. In this hierarchy,
there is a Folder, a Datacenter, and another Folder object between the rootFolder and the
68 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
VirtualMachine object. Therefore, to get to the information you want (the VirtualMachine objects and the
runtime.powerState property), you need to traverse through two Folder objects and a Datacenter object.
One way to get to the target object is to use a series of modules to traverse through each managed object. Each
module would use the simple collector described in the last section to traverse one managed object in the
hierarchy. Example 5‐11 shows a simple collector that traverses and returns the rootFolder.
ObjectContent[] oc = my_conn.retrieveProperties(
my_conn.retrieveServiceContent(_svcRef).getPropertyCollector(),
new PropertyFilterSpec[] { spec } );
return rootRef;
}
In this example, the starting object is the ServiceInstance object. This is also the target object so no traversal
through other managed objects is needed here. The ServiceInstance property to be collected is
content.rootFolder. _svcRef, and _sic are defined globally. my_conn is defined during login and
connection.
To traverse through the managed objects, you write a similar module for each managed object, using the
returned value as input for the next module. For example, the next code block looks something like this:
ManagedObjectReference getNextObject(ManagedObjectReference rootRef)throws Exception {
return dcRef;
}
The returned value would be used as input for the next module, and so on until the virtual machine target is
reached and collected.
Of course, this way of traversing through managed objects with a series of simple collectors presupposes a
single datacenter. This can be complicated if you are managing multiple datacenters through VirtualCenter
Server.
Whether you are managing a single datacenter through ESX Server or multiple datacenters through
VirtualCenter Server, the better way to traverse is by constructing one or more TraversalSpec objects. The
next section describes these objects and how to use them.
VMware, Inc. 69
Programming Guide
Earlier, in discussing the ObjectSpec object (“Specifying the Starting Point for a Search Using an ObjectSpec”
on page 64), the list of properties included an optional selectSet property. This property is an array of
SelectionSpec objects (the TraversalSpec extends the SelectionSpec object). Each element in the array
represents an object to be traversed.
The TraversalSpec object has the following properties:
path—The property of the TraversalSpec target object. This is the property used to select the objects to
be traversed.
selectSet—Additional objects to traverse. The next managed object to be traversed. Represented by an
array of SelectionSpec objects.
skip—A boolean property. Similar to the skip property of the ObjectSpec (“Skipping the Starting
Object” on page 65), does the collector check this object to see if it matches the ObjectSpec target object
or not?
type—The target object to be traversed. The path property represents a property of this object. For
allowable values, see the type property of the TraversalSpec object in the VI API ReferenceGuide.
In addition, the TraversalSpec inherits the name property from the SelectionSpec. As you can see, the
TraversalSpec resembles the ObjectSpec (“Specifying the Starting Point for a Search Using an ObjectSpec”
on page 64). It acts like an “ObjectSpec” for one particular point in your traversals to your ObjectSpec target
object. It describes the object to be traversed and points the way, through the path property, to the next object
to be traversed. The next sections build a series of TraversalSpec objects to traverse the managed objects in
Figure 5‐5.
...
target object (type) childEntity(VirtualMachine) childEntity (VirtualMachine)
runtime.powerState runtime.powerState
70 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
Notice the following:
The rootFolder (rootRef) is the starting object.
The first traversal is always from the starting object.
At this stage of the tree, the value of the Folder object’s childEntity property can either be another Folder
or a Datacenter. In the case described in Figure 5‐4, the next traversal will be a Datacenter. So this
TraversalSpec checks the childEntity property of the rootFolder (a Folder object) and finds a
Datacenter. The selectSet property determines additional objects to be traversed, in this case, the property
points to a SelectionSpec named “datacenterSpec”. Example 5‐13 shows the code for traversing from the
Datacenter to the next managed object.
In Example 5‐13, this TraversalSpec checks the vmFolder property of the Datacenter (a Datacenter
object) and finds a Folder. The selectSet property determines additional objects to be traversed, in this case,
the property points to a SelectionSpec named “folderSpec.”
The folderSpec traverses through the Folder to any values of the childEntity property. At this stage in the
tree, the childEntity property can be a Folder object or a VirtualMachine object. The collector can begin
collecting the virtual machines and their power states.
VMware, Inc. 71
Programming Guide
childEntity (Datacenter)
...
target object (type) childEntity(VirtualMachine) childEntity (VirtualMachine)
runtime.powerState runtime.powerState
Use the Managed Object Browser to browse the server objects to determine the path to the vmFolder, then
invoke the FindByInventoryPath operation to return the ManagedObjectReference for the vmFolder. This
becomes your starting object. Example 5‐14 shows the code block that has the vmFolder as a starting object. In
this case, the code only uses one TraversalSpec to traverse from the starting object to the childEntity
property. In this case, the childEntity objects are the virtual machines.
Notice that the selectSet property recurses through the folderTraversalSpec, to locate any Folder
objects as children of the vmFolder.
Figure 5‐7 shows the hostFolder side of the inventory tree used in the previous discussion. In this case, where
the HostSystem is the target object (and where the starting object is the rootFolder), you need to traverse the
following managed objects:
Folder (the rootFolder starting object)
Datacenter
Another Folder object (hostFolder)
ComputeResource
ClusterComputeResource
72 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
Figure 5-7. Starting Object and Target Objects—Traversals Needed for HostSystems
rootFolder (Folder) starting object (obj)
childEntity (Datacenter)
...
childEntity(ComputerResource) childEntity(ClusterComputerResource)
resourcePool(resourcePool) resourcePool(resourcePool)
In Example 5‐15, notice that the folderSpec references several managed objects since this TraversalSpec
object is re‐used several times depending on which managed object it represents in the tree (rootFolder or
hostFolder).
VMware, Inc. 73
Programming Guide
VirtualMachine (or HostSystem) objects over a VirtualCenter Server, where multiple Datacenters are
involved, the traversals can get a bit more complicated.
Datacenter
vmFolder hostFolder vmFolder hostFolder
ResourcePool ResourcePool
Figure 5‐8 represents a VirtualCenter Server with multiple datacenters. The three dots (...) beneath the
vmFolder and hostFolder objects represent the branches of objects within those folders, as shown by the
middle Datacenter.
In a VirtualCenter Server, when you are collecting objects, you must take into account the objects that need to
be traversed at each level. For example, in Figure 5‐8, to collect virtual machines, from the rootFolder you
must traverse not only to a Datacenter object, but also to a Folder object. However, the general rule still
applies: you must traverse through each managed object that lies between your starting object and your target
object.
74 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
CAUTION Because this TraversalSpec searches the entire hierarchy to collect properties, performance can be
unacceptably slow using this approach.
// Traverses from a resource pool to a virtual machine associated with the pool.
TraversalSpec resourcePoolVmTraversalSpec = new TraversalSpec();
resourcePoolVmTraversalSpec.setName(“resourcePoolVmTraversalSpec”);
resourcePoolVmTraversalSpec.setType(“ResourcePool”);
resourcePoolVmTraversalSpec.setPath(“vm”);
resourcePoolVmTraversalSpec.setSkip(new Boolean(false));
VMware, Inc. 75
Programming Guide
return pFSpec;
}
Synchronizing Data
In addition to “Using ServiceContent Object’s searchIndex Property,” you can use the property collector to
monitor changes to managed objects on a VirtualCenter Server or ESX Server systems.
Creating a Filter
The first step in monitoring changes is to create a PropertyFilterSpec that defines the information you want
to monitor (see “Putting It All Together: The PropertyFilterSpec Object” on page 66).
Next, initiate property collection by invoking the CreateFilter method, passing to it the
PropertyFilterSpec, which will filter the information whose changes you want to monitor. For example:
ManagedObjectReference pfilter = _service.createFilter(_propCol, spec, false);
CreateFiler takes these parameters:
PropertyCollector ManagedObjectReference—Use an accessor method to get this object (the
_propCol argument shown above).
spec—The PropertyFilterSpec object that describes the information you want to monitor, described
in the earlier sections.
76 VMware, Inc.
Chapter 5 Using the PropertyCollector and SearchIndex Managed Objects
partialUpdates—For nested properties, this boolean flag specifies whether a change to a nested
property should report only the nested change or the entire specified property value.
For example, if you are monitoring changes to the power states of virtual machines (located at
runtime.powerState), set the value to true to report changes only to the nested powerState property. Set
the value to false to report changes to the enclosing runtime property.
The CheckForUpdates operation checks the objects and properties included in all the filters created during
the current session and returns immediately. The WaitForUpdate operation waits until updates are available
before the operation completes.
Both operations take the following parameters:
PropertyCollector ManagedObjectReference—Use an accessor method to get this reference.
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 or WaitForUpdates.
Both operations return an UpdateSet object which contains the following properties:
filterSet—An array of PropertyFilterUpdate objects. The set of updates that represent the changes
since the version string was passed to CheckForUpdates or WaitForUpdates.
version—A string property. The new version to pass in the next call to CheckForUpdates or
WaitForUpdates.
Example 5‐18 shows code that checks for updates and displays the results.
VMware, Inc. 77
Programming Guide
System.out.println();
}
}
}
} else {
System.out.println("No changes!");
}
for (int counter=0; counter < 10; ++counter) {
Thread.sleep(30000);
uSet = my_conn.checkForUpdates(_propCol, newVers);
if (uSet != null && uSet.getFilterSet() != null) {
PropertyFilterUpdate[] pfus = uSet.getFilterSet();
newVers = uSet.getVersion();
System.out.println("Version is: " + newVers);
for(int pfui=0; pfui<pfus.length; ++ pfui) {
System.out.println("Filter is: " + pfus[pfui].getFilter());
ObjectUpdate[] ous = pfus[pfui].getObjectSet();
78 VMware, Inc.
6
Creating a Datacenter
Managing Folders
Renaming Inventory Items
Creating a Datacenter
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 hostFol
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.
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.
VMware, Inc. 79
Programming Guide
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.
CAUTION This operation deletes the entire branch, including Folder objects, virtual machines, associated
datastore files, and removes all hosts from VirtualCenter Server management.
Managing Folders
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. For example:
ManagedObjectReference folderMoRef = my_conn.findByInventoryPath(_sic.getSearchIndex(),
"/NewDataCenter/vm/VM2");
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.
Deleting a Folder
You can use one of two methods to delete a Folder: UnregisterAndDestroy_Task or Destroy_Task.
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.
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.
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.
80 VMware, Inc.
Chapter 6 Basic Inventory Operations
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.
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.
VMware, Inc. 81
Programming Guide
82 VMware, Inc.
7
Performing Power Operations
Managing Snapshots
Migrating a Powered‐On Virtual Machine (VMotion)
Creating a Virtual Machine
Renaming a Virtual Machine
Creating Templates
Configuring a Virtual Machine
Recommending Hosts for Virtual Machines
Powering On
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
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.
VMware, Inc. 83
Programming Guide
Suspending
The SuspendVM_Task operation lets you suspend operation of the virtual machine, referenced as the sole
parameter of the operation.
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
if(powerOp.equals("on"))
ManagedObjectReference taskMoRef =
my_conn.powerOnVm(vmMoRef, hostMoRef);
else if(powerOp.equals("off"))
ManagedObjectReference taskMoRef = my_conn.powerOffVm(vmMoRef);
else if(powerOp.equals("suspend")
ManagedObjectReference taskMoRef = my_conn.suspendVm(vmMoRef);
else
System.out.println("Operation must be either \"on\", \"off\", or
\"suspend\".");
System.exit(0);
...
}
}
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 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.
The following code snippet 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 “Connecting to the Web Service” on page 60.
...
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
84 VMware, Inc.
Chapter 7 Virtual Machine Operations
pSpec.setAll(false);
pSpec.setType("Task");
pSpec.setPathSet(new String[] {"info.state"});
do {
ObjectContent[] objs = my_conn.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });
if(objs == null)
return null;
if((TaskInfoState)dProps[0].val == TaskInfoState.error)
System.out.println("Task completed with an error.");
else
System.out.println("Virtual machine has been reset.");
...
}
}
Managing Snapshots
A snapshot preserves a virtual machine at a particular point in time. This includes 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.
VMware, Inc. 85
Programming Guide
You can create snapshots, revert to any snapshot in the tree, and remove snapshots.
NOTE If the virtual machine is associated with a host on an ESX 2.5 Server, you can only create a maximum
of one snapshot.
Creating Snapshots
The CreateSnapshot_Task operation lets you create snapshots of a virtual machine. The operation takes a
reference to the VirtualMachine managed object that you want to snapshot. In addition, the operation takes
the following required parameters:
name—The name for this snapshot. The name need not be unique for this virtual machine.
description—A description of the snapshot.
memory—A boolean property. If set to TRUE, a dump of the internal state of the virtual machine (basically
a memory dump) is included in the snapshot. Memory snapshots consume time and resources, and take
longer to create.
quiesce—A boolean property. If set to TRUE and the virtual machine is powered on when the snapshot
is taken, VMware Tools is used to quiesce the file system in the virtual machine. This assures that a disk
snapshot represents a consistent state of the guest file system(s).
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.
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.
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
...
}
}
86 VMware, Inc.
Chapter 7 Virtual Machine Operations
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 the Snapshot4 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.
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.
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.
VMware, Inc. 87
Programming Guide
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.
You can define a PropertySpec object that collects these properties:
PropertySpec pspec = new PropertySpec();
setType("VirtualMachine");
setAll(Boolean.FALSE);
setPathSet(new String[] { "snapshot.rootSnapshotList.snapshot" });
See “Using the PropertyCollector and SearchIndex Managed Objects” on page 61 for details about creating
and using a property collector.
Enabling Migration
Before you can migrate a virtual machine between two different host systems, the source and target
HostSystem objects must be properly configured.
88 VMware, Inc.
Chapter 7 Virtual Machine Operations
1 Configure TCP/IP on the VMkernel.
See “Configuring TCP/IP on the VMkernel” on page 139. 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 89 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 102.
3 If you are using VMotion, enable the VMotion feature.
See “Enabling the VMotion Feature” on page 89.
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 share the same
storage (VMFS volumes) as the virtual machine.
LicenseManager managed object reference—You can obtain this managed object reference through the
ServiceContent data object, as shown in the following code snippet:
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference lmRef = _sic.getLicenseManager();
...
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 “Obtaining Managed Object References” on page 61.
featureKey—The string that indicates the feature being enabled. See EnableFeature in the VI API
ReferenceGuide for a list of entries.
HostVmotionSystem managed object reference—Obtain by using a property collector for
configManager.vMotionSystem of the HostSystem managed object. See “Using the PropertyCollector
and SearchIndex Managed Objects” on page 61.
ipConfig—The HostIpConfig data object. This object contains the information to reconfigure the IP
information.
Validating Migration
The ValidateMigration operation lets you test a migration before you actually perform the migration using
MigrateVM_Task or RelocateVM_Task.
Performing VMotion
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.
VMware, Inc. 89
Programming Guide
pool—A reference to a ResourcePool managed object. The target resource pool for the virtual machine.
If this parameter is not set, 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, the property can be unspecified 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.
Example
The code sample in Example 7‐1 uses the MigrateVM_Task operation to migrate a virtual machine while it is
still operational (a so‐called “hot” migration). The MigrateVM_Task operation can be used for both a hot
migration and a cold migration. During this operation, the virtual machine’s virtual disk files are not moved.
Example 7-1.
{
...
{
// Log on code.
...
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
ManagedObjectReference poolMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToRPool);
if(pState.equals("on"))
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.poweredOn);
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.poweredOn);
}
else
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.poweredOn);
}
elseif(pState.equals("off"))
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.poweredOff);
90 VMware, Inc.
Chapter 7 Virtual Machine Operations
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.poweredOff);
}
else
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.poweredOff);
}
elseif(pState.equals("suspended")
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority,
VirtualMachinePowerState.suspended);
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.highPriority,
VirtualMachinePowerState.suspended);
}
else
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.lowPriority,
VirtualMachinePowerState.suspended);
}
else
{
if(prior.equals("default"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef,
VirtualMachineMovePriority.defaultPriority);,
}
elseif(prior.equals("high"))
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.highPriority);
}
else
{
ManagedObjectReference taskRef = my_conn.migrateVM(vmMoRef,
poolMoRef, hostMoRef, VirtualMachineMovePriority.lowPriority);
}
}
...
}
}
VMware, Inc. 91
Programming Guide
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 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 datastore 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 with which the virtual machine should be associated. Required for an
import operation. Unless otherwise specified, the resource pool of the source virtual machine is used
for migrate or clone operations.
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.
Code Example
As described in “Migrating a Powered‐On Virtual Machine (VMotion)” on page 88, 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 RelocateVM_Task operation.
{
/**
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
/**
* Target location for the disks can be specified in a variety of ways.
* See the VirtualMachineRelocateSpec (in the VI API Reference)
* 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
* “Using the PropertyCollector and SearchIndex Managed Objects” on page 61 for more
information about
* using a PropertyCollector.
*/
92 VMware, Inc.
Chapter 7 Virtual Machine Operations
...
}
}
Create a virtual machine from scratch.
Clone an existing virtual machine.
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 99 for information
about configuring.
VMware, Inc. 93
Programming Guide
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.
import com.vmware.vimsample.clientutils.*;
import com.vmware.vimsample.vmutils.VmUtils;
import com.vmware.vim.*;
/**
* Create Virtual Machine implementation.
*/
public class VmCreate extends ClientBase implements ClientBase.Delegate {
VmUtils _vmUtils;
94 VMware, Inc.
Chapter 7 Virtual Machine Operations
return cpus;
}
return sizeMB;
}
ManagedObjectReference hostfoldermor =
_vmUtils.getHostFolder(dcmor);
ManagedObjectReference compresmor =
_vmUtils.getComputeResource(hostfoldermor);
ManagedObjectReference hostmor = _vmUtils.getHost(hostfoldermor,
getCreateOnHost());
VMware, Inc. 95
Programming Guide
ManagedObjectReference resourcePool =
_vmUtils.getResourcePool(compresmor);
ManagedObjectReference taskmor =
clientInfo.getConnection().getService().createVM_Task(
vmFolderMor, vmConfigSpec, resourcePool, hostmor
);
Object[] result =
clientInfo.getServiceUtil().waitForValues(
taskmor, new String[] { "info.state", "info.error" },
new String[] { "state" }, // info has a property - state for
// state of the task
new Object[][] { new Object[] { TaskInfoState.success,
TaskInfoState.error } }
);
if (!app.clientInfo.isHasMinimumArgs()) {
return;
}
app.run(app);
}
}
96 VMware, Inc.
Chapter 7 Virtual Machine Operations
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 “Identifying an
Existing Virtual Machine as a Template” on page 98 for more information.
Folder managed object reference—The folder in which you want to locate the new virtual machine.
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.
Creating Templates
A template is virtual machine definition that can be used to create multiple virtual machines of the same
specifications. A template can be made from an existing virtual machine by cloning the virtual machine (which
leaves the original intact), or by identifying the virtual machine as a template, which alters the configuration
of the original virtual machine. Both alternatives are covered in this section.
Identifying an Existing Virtual Machine as a Template
Cloning an Existing Virtual Machine
VMware, Inc. 97
Programming Guide
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 “Using the PropertyCollector and SearchIndex Managed Objects” on page 61.
2 Invoke the MarkAsTemplate operation.
This operation takes as its only parameter the reference to the specific virtual machine that you want to
change.
The following code snippet uses an existing virtual machine and marks it as a template.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), args[3]);
my_conn.MarkAsTemplate(vmMoRef);
...
}
}
When you invoke this operation, the config.template property of the VirtualMachine object changes to
“true”.
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 “Using the PropertyCollector and SearchIndex Managed
Objects” on page 61.
2 Clone the virtual machine (see “Cloning Virtual Machines” on page 97). The VirtualMachineCloneSpec
data object includes a boolean property called template. To make the clone a template, set this boolean
property to true.
The following code sample clones an existing VirtualMachine to use as a template.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference folderMoRef =
my_conn.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
98 VMware, Inc.
Chapter 7 Virtual Machine Operations
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.
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.
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.
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
VMware, Inc. 99
Programming Guide
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.
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.
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 VI API ReferenceGuide 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 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.
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 VI API ReferenceGuide.
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 101.
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.
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:
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 VI API ReferenceGuide 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.');
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.
1 Identify the device on which the virtual disks are stored.
For example:
/* Get the device from virtual machine of type com.vmware.vim.VirtualDisk.
The code retrieves the first such device found*/
for(int i=0;i<dev.length;i++) {
System.out.println("dev " + dev[i].getClass().getCanonicalName());
if(dev[i].getClass().getCanonicalName().equalsIgnoreCase("com.vmware.vim.VirtualDisk")) {
device = dev[i];
i = dev.length + 1;
if(device != null) {
2 Create a new backing file. Use a new file name. For example:
// Create new backing file information, using a new file name
3 Set fileOperation to create, and set Operation to edit.
Setting these two operations must be correct:
To create a new backing file, fileOperation must be create.
To edit the existing device, Operation must be edit.
For example:
dspec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create);
dspec.setOperation(VirtualDeviceConfigSpecOperation.edit);
array[0] = dspec;
4 Set this new backing file information into the virtual device. For example:
//Set the backing file information in the device
device.setBacking(diskfileBacking1);
VirtualMachineConfigSpec spec = new VirtualMachineConfigSpec();
5 Reconfigure the device. For example:
// Reconfigure operation
spec.setDeviceChange(array);
_service.reconfigVM_Task(vmmor,spec);
Caution: Using a VirtualDeviceConfigSpecFileOperation.replace operation on disks is not
supported. This operation applies only to floppy images.
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.
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 86.
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.
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.
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.
Configuring Intervals for Statistics
Querying Statistics
Querying Metadata Information
Basic Performance Counters
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, as follows:
Sample intervals must be multiples of each other—for example, five minutes for one day, ten minutes for
two days, fifteen minutes for three days, and so on. Five minutes for one day and seven minutes for two
days is not valid. Furthermore, all intervals must be divisible by each other: if you have a five minute
interval and a 15‐minute interval, you cannot create a 10‐minute‐interval (since 15 is not a multiple of 10).
The length of time the stats remain in the database must increase with each 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.
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).
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.
Querying Statistics
The following operations let you gather statistics:
QueryAvailablePerfMetric
QueryPerf
QueryPerfComposite
QueryPerfProviderSummary
Clients can collect performance data on 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.
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.
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.
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, 300, 1800, 7200, 86400);
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.
You must specify at least one entity to this query. When you invoke the QueryPerf operation, you can specify
the starting time, ending time, and maximum number of samples to be returned. The times specified should
correspond to the server time.
If the starting time is omitted, the returned metrics start from the first available metric in the system.
If 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.
If you omit the optional Interval identifier, the operation will summarize across all the intervals. For
example, say 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.
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.
QueryPerfCounter(pmMor, counterids);
Each performance counter includes:
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.
Logging a User‐Defined Event
Retrieving Historical Information
Managing Alarms
The LogUserEvent operation takes the following parameters:
EventManager managed object reference—The EventManager object is accessed from the
ServiceInstance through the ServiceContent data object. The ServiceContent data object is
returned by the RetrieveServiceContent operation, as shown in the following code snippet:
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference eMgrRef = _sic.getEventManager();
...
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.
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 120.
This sample collects all the events associated with an entity, then displays the results based on keyboard input.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
// Find the managed entity.
ManagedObjectReference meRef = my_conn.findByInventoryPath(
_sic.getSearchIndex(), PathToEntity);
/*
* These lines define the level from which events are to be collected.
* “all” (collect events pertaining to both the managed entity and
* its children), “children” (collect events pertaining to the
* children of the managed entity), and “self” (collect events
* pertaining only to the managed entity).
*/
entitySpec.setRecursion(EventFilterSpecRecursionOption.all);
...
}
}
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61 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 118 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 118 for an explanation of current position.
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.
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}"
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.
Example 9‐1 shows how to define an event message according to context.
log.logLine(clientInfo.getAppName() +
" : Successful Formating the event");
}
// <summary>
// This function formats the event message using the format strings
// in the EventDescriptionEventDetail for the event passed in
// using the passed in format requested
// </summary>
// <param name="fType">The format type you wish to display</param>
// <param name="eventDetail">Map of Event typename to
// EventDescriptionEventDetail objects</param>
// <param name="theEvent">The Event to format the message for</param>
// <returns></returns>
// The place holder used for string replacement has the following
// format:
//
// {<property-path>}
//
// Where <property-path> is the path to the data that should be used to
// replace the place holder. These are relative to the event in question
// For example, the messages for the Event type 'VmPoweredOnEvent' are:
// 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"
if("VmPoweredOnEvent".equals(typeName)) {
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;
}
}
theEvent.getComputeResource().getName());
if(theEvent.getDatacenter() != null)
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;
}
...
TaskManager managed object reference—You obtain this reference using an accessor method for the
taskManager property of the ServiceContent data object, as shown in the following code sample
snippet:
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference taskMgrRef = _sic.getTaskManager();
...
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.
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61 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 118 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 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. See“Modifying the Current Position” on page 118 for an explanation of current position and
how to modify it.
When you invoke this operation, you include the following parameters: the TaskHistoryCollector
managed object reference and the maximum number of items you want in the scrollable view. No items
are returned if you have reached the end of the collector.
Two Items
Oldest Removed Newest
{
Viewable Latest Page
Latest Page Size = 100
{
500 Tasks
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.
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.
Figure 9-3. History Collector with maxCount set at 100 (New Current Position)
Oldest
Current Position
Newest
{
{
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.
Figure 9-4. ResetCollector Sets Current Position at Beginning of Viewable Latest Page
Current Position
Oldest Newest
{
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.
Managing Alarms
Alarms let you trigger actions based on specified conditions or thresholds.
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:
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference alMgrRef = _sic.getAlarmManager();
...
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 “Using the PropertyCollector and SearchIndex Managed Objects”
on page 61.
spec—The AlarmSpec data object type. The specification that defines the alarm. See “Configuring or
Reconfiguring an Alarm” on page 120.
This operation returns a reference to an Alarm managed object.
Figure 9‐5 shows an example of how an alarm set for various levels of CPU usage might be triggered over time.
Red
90 x x x
Yellow
75 x x x
Green
CPU Usage
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 121.
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 124.
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 122.
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.
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 State Alarm Expression” on page 123 for more information about testing the state of a virtual
machine or host. See “Handling Multiple Conditions” on page 122 for information about testing for multiple
conditions.
gray—Status is unknown.
red—The entity has a problem.
yellow—The entity might have a problem.
green—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:
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
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.
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
By setting property of the AlarmSpec object, you can control 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
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.
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);
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.
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 value is “runtime.powerState”.
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 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 VI API ReferenceGuide.
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 121.
// 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!");
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.
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 “Using the PropertyCollector and SearchIndex Managed Objects” on page 61,
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 120.
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);
Managing Clusters and Resource Pools
Managing Hosts
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 135.
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61 for more information about using a
property collector.
The folder you select must be a host folder within a datacenter.
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 128.
name—The name for the new cluster.
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 VI API ReferenceGuide 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 the
DrsBehavior enumerated type in the VI API ReferenceGuide 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.
A root resource pool must always have at least as many resources as all its immediate subclasses (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 130.
ResourcePool managed object reference—The specific 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 130.
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.
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 130.
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.
The reservation property of the ResourceAllocationInfo object defines the minimum available resources of
the resource pool. The sum of the reservation properties of a parent’s immediate children must be less than or
equal to the parent’s resources. You cannot configure a resource pool’s cpu or memory reservation in such a
way that the resources are overcommitted. You can determine the unreserved amount of cpu or memory by
checking the value of the parent resource pool’s runtime.cpu.unreservedForPool property or
runtime.memory.unreservedForPool property.
For example, in the following figure, the parent resource pool has memory resources equal to 60 gigabytes.
ClusterComputeResource (DRS)
20 GB ResourcePool
60 GB
Res ool
Res ool
ourc
10 GB
P
ourc
P
e
20 GB
e
Resource
Res ool
Pool
ourc
5 GB
P
e
Resource Resource
Pool Pool
15 GB 3 GB
The sum of the children’s reservation properties equals 40 gigabytes. When you want to create another
resource pool, you check the parent’s unreservedForPool property and find that you have approximately 20
gigabytes available for the new resource pool.
NOTE Always leave a “cushion” between the sum of the children and the parent. In other words, it is
recommended that the sum of the children never equal the parent.
If the amount you want to configure for the new resource pool would overcommit the resources (the sum of
the children is greater than the parent), you must reconfigure the reservation values of the other children first,
as shown in the following figure.
ClusterComputeResource (DRS)
10 GB ResourcePool
30 GB
60 GB
Res ool
Res ool
Poo rce
ourc
5 GB
P
ou
ourc
P
l
Res
e
10 GB
e Resource
Res ool
Pool
ourc
3 GB
P
e
Resource Resource
Pool Pool
4 GB 4 GB
Notice that the minimum resources (the reservation property) of the other children are now 10 gigabytes
apiece, ensuring that the resource pool remains undercommitted. Notice also that the children of those
resource pools have been reconfigured to fit the new minimum of their parents. When a resource pool has
children, to ensure undercommitment, you must always reconfigure the children first.
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.
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 VI API ReferenceGuide 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.
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 being destroyed.
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.
ClusterComputeResource (DRS)
10 GB
Resource
Host Host Host
Resource
20 GB
Pool
Pool
4 GB
Resource
ResourcePool
Resource
Pool
1 GB
Pool
Resource 60 GB
Resource
20 GB 10 GB
Pool
5 GB
Pool
Res
ou urce
Res
our P ool rce Reso ool
Poo ce 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
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 let you 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.
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.
Res ool
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 129.
ClusterComputeResource (DRS)
3 GB
Resource
10 GB
Pool
Pool
10 GB
Resource
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.
Managing Hosts
When you add a host using the API, you can either add the host as a standalone or you can add the host to an
existing cluster of hosts. Both approaches are discussed in this section.
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61 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 137 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.
...
ClusterComputeResource ComputeResource
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61 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 127.
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 137 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.
MoveHostInto_Task—to move a single host.
MoveInto_Task—to move a set of hosts.
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.
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.
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.
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.
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.
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 a Powered‐On Virtual Machine (VMotion)” on page 88 for information about
migrating virtual machines.
See for the parameters and general information about the MoveIntoFolder_Task operation.
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 135.
MoveIntoFolder_Task—To remove a host from a cluster and make it a standalone host. See “Moving
Existing Hosts into a Folder” on page 136.
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.
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.
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 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.
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.
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 “Using
the PropertyCollector and SearchIndex Managed Objects” on page 61.
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.
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.
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.
Configuring the Service Console TCP/IP
Configuring TCP/IP on the VMkernel
Adding a Virtual Switch
Adding a Port Group to a vSwitch
Adding a Virtual NIC (VNIC)
Updating the Host’s Network Configuration
Defining the Host Network Policy
Obtaining the HostNetworkSystem Managed Object Reference
UpdateServiceConsoleVirtualNic
AddServiceConsoleVirtualNic
RemoveServiceConsoleVirtualNic
RestartServiceConsoleVNic
For more information, see “Updating the Host’s Network Configuration” on page 141.
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 140.
2 Use the AddVirtualSwitch operation to add one or more virtual switches.
See “Adding a Virtual Switch” on page 140.
3 Use the AddPortGroup operation to add a port group to a virtual switch.
See “Adding a Port Group to a vSwitch” on page 140.
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 141.
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 “Using the
PropertyCollector and SearchIndex Managed Objects” on page 61.
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 141),
then use SelectVNic to select it.
6 Use UpdateIpRouteConfig to configure a gateway.
The HostNetworkSystem managed object has several 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 “Using the PropertyCollector and
SearchIndex Managed Objects” on page 61) lets you retrieve the property information belonging to this
managed object.
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 143.
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 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 142.
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 143.
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 142.
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.
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 143.
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 “Using the PropertyCollector and SearchIndex Managed Objects” on page 61
for more information on using the property collector.
To add a port group, see “Adding a Port Group to a vSwitch” on page 140.
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.
HostNetworkSystem managed object reference—A reference to the HostNetworkSystem managed
object. See “Obtaining the HostNetworkSystem Managed Object Reference” on page 143.
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.
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 143.
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 for the Service Console
To add a virtual network interface controller (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 143.
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 “Using the PropertyCollector and SearchIndex Managed Objects” on page 61
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 143.
device—The name of the service console VNIC you are removing.
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 143.
device—The name of the service console VNIC you are restarting.
HostNetworkSystem managed object reference—A reference to the HostNetworkSystem that contains
the TCP/IP configuration. See “Obtaining the HostNetworkSystem Managed Object Reference” on
page 143.
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.
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 VI API ReferenceGuide for more information.
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 “Using the PropertyCollector and SearchIndex
Managed Objects” on page 61 or see Appendix D, “PropertyCollector Tutorial,” on page 197.
Storage Operations 12
VMware Infrastructure supports several different types of storage, including NAS, or network‐attached
storage, the most common of which is NFS (network file share); SAN, or storage‐area networks; and VMFS,
VMware’s Virtual Machine File System, a cluster file system that provides storage virtualization optimized for
virtual machines. VMFS is the default storage system for the set of files that encapsulates each virtual machine
on physical SCSI disks and partitions.
This chapter covers working with storage through the API. It includes these topics:
Creating an NAS‐Backed Datastore
Creating a VMFS‐Backed Datastore
Extending a VMFS Datastore Across Multiple Disks
Removing and Deleting Datastores
Configuring a VMFS‐Backed Datastore
Configuring iSCSI Initiators
Obtaining Managed Object References for Storage Operations
A HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
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.
This operation takes the following parameters:
HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
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 147.
This operation returns a Datastore managed object reference.
HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
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 “Using the PropertyCollector and SearchIndex
Managed Objects” on page 61 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 148.
partition—A HostDiskPartitionInfoSpecification data object.
HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
Datastore managed object reference—You can obtain this reference with a property collector. See “Using
the PropertyCollector and SearchIndex Managed Objects” on page 61.
devName—The SCSI disk device name to which you want to extend the datastore.
This operation returns an array of HostVmfsDatastoreOption data objects.
HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
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.
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.
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 151.
Datastore managed object reference—Reference to the datastore that you want to remove from the host.
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.
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 148 for an explanation of this data object.
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 147 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 irreversible change.
volumeName—The volume name of VMFS.
HostDatastoreSystem managed object reference—See “Obtaining Managed Object References for
Storage Operations” on page 151.
devName—The SCSI disk device name.
This operation returns an array of HostVmfsDatastoreOption data objects.
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.
partition—The partition number of the partition on the ScsiDisk.
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.
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.
NOTE You can use a number of operations to obtain the HostSystem managed object reference. See “Using
the PropertyCollector and SearchIndex Managed Objects” on page 61.
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 iterate
through the array to find the HBA you want to configure. For more information about using a property
collector, see “Obtaining Managed Object References” on page 61.
After you have determined the HBA you want to configure (“Determining the Host Bus Adapter” on
page 149), 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.
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.
NOTE The Media Access Control (MAC) address is not settable.
HostStorageSystem managed object reference—See “Obtaining Managed Object References for Storage
Operations” on page 151.
iScsiHbaId—The string that identifies the Host Bus Adapter. If you have not identified this string, see
“Determining the HBA ID String” on page 149.
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 DNS server addresses, the default
gateway, and the subnet mask. If the dhcpConfigurationEnabled property is set to false, the other
properties are ignored.
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 151.
enabled—Set this boolean to TRUE to enable the software initiator.
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 151.
iScsiHbaId—The string that identifies the Host Bus Adapter. If you have not identified this string, see
“Determining the HBA ID String” on page 149.
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.
HostStorageSystem managed object reference—See “Obtaining Managed Object References for Storage
Operations” on page 151.
iScsiHbaId—The string that identifies the Host Bus Adapter. If you have not identified this string, see
“Determining the HBA ID String” on page 149.
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.
This operation takes the following parameters:
HostStorageSystem managed object reference—See “Obtaining Managed Object References for Storage
Operations” on page 151.
iScsiHbaDevice—The string that identifies the Host Bus Adapter. If you have not identified this string,
see “Determining the HBA ID String” on page 149.
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.
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 151.
iScsiHbaId—The string that identifies the Host Bus Adapter. If you have not identified this string, see
“Determining the HBA ID String” on page 149.
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 151.
iScsiHbaId—The string that identifies the Host Bus Adapter. If you have not identified this string, see
“Determining the HBA ID String” on page 149.
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.
To obtain these managed object references, you can create a PropertyFilterSpec that filters for HostSystem
managed objects and the appropriate property. “Creating a Specification That Filters Objects and Properties”
on page 63 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"});
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"});
Managing Users 13
This chapter discusses the VMware Infrastructure security model and how to perform a variety of
programming tasks associated with managing users, groups, and permissions. Topics include:
Security Management
Adding and Maintaining Users and Groups (ESX only)
Querying for Users and Groups
Adding and Maintaining Authorization Roles
Setting and Maintaining Permissions on an Entity
Querying for Permissions
Obtaining a Reference to the AuthorizationManager
Security Management
You must have one or more authorization privileges before you can invoke perform actions in the VMware
Infrastructure SDK. Authorization is defined by permissions and roles. Each role is assigned one or more
authorization privileges. Each permission associates a user or group with a role that contains privileges
applied to the entity.
Privileges
Privileges are the basic individual rights required to perform actions and read properties. They are statically
defined and never change for a single version of a product. Privileges have the following format:
<group>[.<group>].privilege
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 “Managed Object Privileges Reference” on page 179 for a list of operations and the privileges required to
invoke them.
Destroy_Task
DestroyChildren
UnregisterAndDestroy
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 VI API ReferenceGuide.
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.
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.
Datacenter (N)
VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) VirtualMachine (Y) ComputerResource ComputeResource ComputerResource ComputeResource
ResourcePool ResourcePool
In this figure, a user is granted permission on the vmFolder ManagedEntity. The propagate flag is set to true.
In this case, the user can not only “see” the vmFolder ManagedEntity but can perform operations on the
entity as defined by privileges associated with the role assigned to the permission. Because of the setting of the
propagate flag, the user can also see and perform operations on the VirtualMachine entities within the
vmFolder.
However, privileges do not propagate “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.
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 159 and “Querying for the Permissions on a Specific Entity” on
page 160.
The /folder URL that returns available datacenters, requires the privilege System.View.
URLs that start with /folder and have a query string, require the privileges System.View on the root
folder, as well as Datastore.Browse and Datastore.FileManagement on the datacenter. For example:
https://vcserver01.com/folder?dcPath=MyDC&dsName=storage1
All /host URLs require the privilege Host.Config.AdvancedConfig on the HostSystem.
All /tmp/file URLs require the privilege Host.Config.SystemManagement on the HostSystem.
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 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.
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
This operation lets you remove a user from a group. The parameters include a
HostLocalAccountManager managed object reference, the user account, 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 158.
A UserDirectory managed object reference. See “Obtaining a Reference to the AuthorizationManager”
on page 160.
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.
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 VI API ReferenceGuide 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.
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 propagated
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 156 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 155 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 158.
The ID of the AuthorizationRole that contains the privileges being granted.
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 155).
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.
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 158.
A boolean that specifies whether the user is a group (TRUE) or a user (FALSE).
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 155.
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 156),
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.
An AuthorizationManager managed object reference
The ID for the role used by the permissions
_sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference _authManRef = _sic.getAuthorizationManager();
Using Properties to Determine a Task’s Capabilities
Creating a Scheduled Task
Configuring and Reconfiguring a Scheduled Task
Monitoring Tasks
Cancelling a Task
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).
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.
The following code sample snippet illustrates a PropertyFilterSpec that collects the recent tasks for a
specified virtual machine.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
// Find the managed entity on which the action is performed.
ManagedObjectReference vmRef =
my_conn.FindByInventoryPath(_sic.getSearchIndex,
PathToVm);
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.
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference schedTaskRef = _sic.getScheduledTaskManager();
...
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 “Using the PropertyCollector and SearchIndex Managed
Objects” on page 61.
spec—The ScheduledTaskSpec data object type. The specification that defines the alarm. See
“Configuring and Reconfiguring a Scheduled Task” on page 164.
This operation returns a reference to a ScheduledTask managed object.
The following sample code illustrates creating a scheduled task that performs the power‐on operation.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
// Find the managed entity on which the action is performed.
ManagedObjectReference vmRef =
my_conn.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");
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.
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.
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);
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);
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);
Monitoring Tasks
This code sample snippet uses power operations code and adds a code block that monitors the task that is
returned.
{
...
{
// Log on code. See “Connecting to the Web Service” on page 60.
...
ManagedObjectReference vmMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToVm);
ManagedObjectReference hostMoRef =
my_conn.findByInventoryPath(_sic.getSearchIndex(), PathToHost);
if(powerOp.equals("on"))
ManagedObjectReference taskMoRef =
my_conn.powerOnVm(vmMoRef, hostMoRef);
else if(powerOp.equals("off"))
ManagedObjectReference taskMoRef = my_conn.powerOffVm(vmMoRef);
else if(powerOp.equals("suspend")
ManagedObjectReference taskMoRef = my_conn.suspendVm(vmMoRef);
else
System.out.println("Operation must be either \"on\", \"off\", or
\"suspend\".");
System.exit(0);
do {
ObjectContent[] objs = _my_conn.retrieveProperties(
_sic.getPropertyCollector(),
new PropertyFilterSpec[] { pfSpec });
if(objs == null)
return null;
if((TaskInfoState)dProps[0].val == TaskInfoState.error)
System.out.println("Task completed with an error.");
else
System.out.println("Task completed successfully.");
...
}
}
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 scheduled task
to comment out or eliminate the run. See “Configuring and Reconfiguring a Scheduled Task” on page 164.
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 “Connecting to the Web Service” on page 60.
ScheduledTaskManager—ScheduledTaskManager managed object reference. To obtain this, you use an
accessor method on the scheduledTaskManager property of the ServiceContent object:
...
ManagedObjectReference _svcRef = new ManagedObjectReference();
ServiceContent _sic = my_conn.retrieveServiceContent(_svcRef);
ManagedObjectReference schedTaskRef = _sic.getScheduledTaskManager();
...
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 153.
Counter Information Categories
Complete List of Performance Counters
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.
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
NOTE This class of counters can only be queried for using the VI SDK. The information is not available
through the VI Client.
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
Statistic
Counter Name Unit Description Type Rollup Type Entity
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
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 VI
API ReferenceGuide 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
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
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 VI API ReferenceGuide. X X
DestroyChildren See DestroyChildren in the VI API ReferenceGuide. X X
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
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 VI API ReferenceGuide. X
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 VI API X X
ReferenceGuide.
MoveIntoResourcePool See MoveIntoFolder_Task in the VI API X X
ReferenceGuide.
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
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
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
RemoveVirtualSwitch Host.Config.Network X X
Rename_Task See Rename_Task in the VI API ReferenceGuide. X X
RenameCustomFieldDef Global.ManageCustomFields X
RenameCustomizationSpec VirtualMachine.Provisioning.ModifyCustSpecs X
RenameDatastore Datacenter.RenameDatastore X 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
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
1
UnregisterAndDestroy_Task Folder.Delete X X
UnregisterVM VirtualMachine.Inventory.Delete X X
UpdateAuthorizationRole Authorization.ModifyRoles X X
UpdateChildResourceConfiguration See UpdateChildResourceConfiguration in the VI X X
API ReferenceGuide.
UpdateConfig See UpdateConfig in the VI API ReferenceGuide. X X
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 VI API ReferenceGuide. X
UpdatePerfInterval Performance.ModifyIntervals 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
UpgradeVmLayout Host.Config.Storage X X
ValidateMigration See ValidateMigration in the VI API ReferenceGuide. X
Resource.AssignVMToPool required on The target
resource pool for the virtual machines.
WaitForUpdates System.View X X
XmlToCustomizationSpecItem System.View X
1. To invoke this operation on a managed entity, you must also have the same privilege associated with the parent of
the managed entity.
description System.View
roleList System.View
description System.View
ComputeResource resourcePool System.View
host System.View
encryptionKey System.View
hostFolder System.View
latestEvent System.View
maxCollector System.View
childEntity System.View
networkConfig Host.Config.Network
networkInfo Host.Config.Network
offloadCapabilities Host.Config.Network
storageDeviceInfo Host.Config.Storage
ipConfig Host.Config.Network
featureInfo Global.Licenses
name System.View
historicalInterval System.View
perfCounter System.View
description System.View
capability System.View
message System.View
messageLocaleList System.Anonymous
supportedLocaleList System.Anonymous
defaultLocale System.Anonymous
description System.View
maxCollector System.View
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 determine that VMware Tools is upgradable 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
whether the VMware Tools are running.
Invoking UpgradeTools_Task
The operation takes the following parameters:
VirtualMachine 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 API Reference. The major
faults are:
NotSupported—Upgrading tools is not supported.
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.
/**
* This is a simple standalone client whose purpose is to demonstrate the
* process for Logging into the Webservice, and upgrading the VMware Tools
* for one virtual machine.
*/
public class toolsUpgrade1 {
/**
* Create the Managed Object Reference for the service
*
* @param svcRefVal to define service reference for HostAgent or VPX
*/
public void createServiceRef() throws Exception {
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
/**
* 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 (my_conn != null) {
disconnect();
}
_sic = my_conn.retrieveServiceContent(_svcRef);
_sindex = _sic.getSearchIndex();
_propCol = _sic.getPropertyCollector();
if (_sic.getSessionManager() != null) {
my_conn.login(_sic.getSessionManager(), username, password, null);
}
}
/**
* Log's out and Disconnects from the WebService
*/
public void disconnect()throws Exception {
if (my_conn != null) {
// does not work at this time
//my_conn.logout(_svcRef);
my_conn = 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 {
_vmRef = my_conn.findByInventoryPath(_sindex, _invPath);
}
}
}
if(UpgradeOK) {
ManagedObjectReference upgradeTask =
my_conn.upgradeTools_Task(_vmRef, null);
} else
System.out.println("UpgradeTools_Task is disabled!");
}
}
}
/**
* The main entry point for the application.
*/
public static void main(String[] args) {
if (args == null || args.length != 4) {
System.out.println(
"Usage : toolsUpgrade1 <webserviceurl> <username> <password>
<inventory path>"
);
}
try {
// Create the Service Managed Object Reference
tu1.createServiceRef();
/**
* This is a simple standalone client whose purpose is to demonstrate the
* process for Logging into the Webservice, and upgrading VMware tools
* installed in the guest OS of each virtual machine in inventory
*/
public class toolsUpgrade {
/**
* Create the Managed Object Reference for the service
*
* @param svcRefVal to define service reference for HostAgent or VPX
*/
public void createServiceRef() throws Exception {
_svcRef = new ManagedObjectReference();
_svcRef.setType("ServiceInstance");
/**
* Creates an instance of the VMA proxy and establishes a connection
*
* @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 (my_conn != null) {
disconnect();
}
_sic = my_conn.retrieveServiceContent(_svcRef);
_propCol = _sic.getPropertyCollector();
_rootFolder = _sic.getRootFolder();
if (_sic.getSessionManager() != null) {
my_conn.login(_sic.getSessionManager(), username, password, null);
}
}
/**
* Log's out and Disconnects from the WebService
*/
public void disconnect()throws Exception {
if (my_conn != null) {
// does not work at this time
//my_conn.logout(_svcRef);
my_conn = null;
_sic = null;
}
}
/**
* Get all the virtual machines accessable from rootFolder
* and upgrade their tools if able
*/
public void upgradeTools()throws Exception {
datacenterVmTraversalSpec.setSkip(new Boolean(false));
datacenterVmTraversalSpec.setSelectSet(
new SelectionSpec [] { new SelectionSpec("folderTraversalSpec") });
/**
* The main entry point for the application.
*/
public static void main(String[] args) {
if (args == null || args.length != 3) {
System.out.println(
"Usage : toolsUpgrade <webserviceurl> <username> <password>"
);
}
try {
// Create the Service Managed Object Reference
tu.createServiceRef();
PropertyCollector Tutorial D
The PropertyCollector managed object lets you obtain discrete properties from specified server objects, or
entire objects. It also lets you check objects for changes, and watch for changes.
This Appendix contains these topics:
PropertyCollector Operations
Mechanics of Accessing Properties
Filtering Results
Traversal and Recursion
Reducing Network Traffic by Using the partialUpdates Flag
Several of the sample applications provided in the VI SDK package use the PropertyCollector and its
methods to obtain objects or properties. Refer to these samples in conjunction with this Appendix:
Java sample: SDK\samples\Axis\java\com\vmware\samples\general\PropertyCollector.java
C# sample: SDK\samples\DotNet\SimpleClient
PropertyCollector Operations
The PropertyCollector provides operations to retrieve properties (RetrieveProperties), check for updates
on specified objects (CheckForUpdates), and watch an object, waiting for changes (WaitForUpdates).
RetrieveProperties
The simplest use of the PropertyCollector is to invoke the RetrieveProperties operation. This operation
requires a PropertyFilterSpec object, but not a complete PropertyFilter object. Using
RetrieveProperties is like creating a temporary filter that lasts only for the duration of the operation.
Often, 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.
RetrieveProperties returns a list of ObjectContent data objects. Each ObjectContent contains 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 instance, if a client
requests a property of a VirtualMachine object named runtime.powerState, the property may be returned
with name=runtime.powerState and value=poweredOn.
CheckForUpdates
You can invoke RetrieveProperties repeatedly to get the most recent values of the desired properties, 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 are
designed to return only the updated values, using network bandwidth more efficiently.
CheckForUpdates can be invoked periodically to poll for updates to the values of properties already stored
at the client. This is similar to invoking RetrieveProperties periodically, except that CheckForUpdates
returns only the properties that have changed since the last transmission, whereas RetrieveProperties
retrieves all the properties each time, regardless of whether they changed. If you invoke CheckForUpdates
when there are no changes since the last invocation, CheckForUpdates returns an empty change list.
WaitForUpdates
The most efficient use of network resources is the WaitForUpdates operation, which implements notification
rather than the polling approach of CheckForUpdates. Rather than returning an empty change list,
WaitForUpdates does not complete until an update happens. The WaitForUpdates operation blocks a
processing thread in the client, but can be canceled from another thread with the CancelWaitForUpdates
operation.
To use the CheckForUpdates or WaitForUpdates operations, you must first create a PropertyFilter object
with the CreateFilter operation. The PropertyFilter object is created from a PropertyFilterSpec
object, which specifies the objects of interest and the properties to be collected from them.
CheckForUpdates and WaitForUpdates both return 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.
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 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 aninteger, then you get an integer. If c is a data
object type, then you get an instance of that type. If c is a ManagedObjectReference, you get an instance of a
ManagedObjectReference.
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 results in notification of changes to a.b.c.d or a.b.c.e or any other nested property at that level.
Indexed arrays are accessed in the usual manner, using an index integer. Indexed arrays are used for arrays of
data types whose position in the array does not change. For example, the roleList property of the
AuthorizationManager managed object is an array of autorization roles. Adding a new role to the array does
not change the position of existing elements in the array.
Key‐based arrays are used for information whose position is subject to change. A key‐based array (referred to
as a “hash” in Perl) uses a unique, unchanging value as a “key” to access an element’s value. Typically, the key
is specified as a string, but integers can also be used—for example, Event arrays use integers as keys.
The VMware infrastructure management object model uses key‐based arrays to keep track 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.
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.
Filtering Results
To use the PropertyCollector, you must first create a filter (PropertyFilter) that identifies the objects or
properties of interest.
PropertyFilter
Property filters allow a client to retrieve a subset of the properties of a managed object. Besides minimizing
network traffic, this can simplify processing for the client. Only the properties of interest need be requested
and processed by the client.
Property filters also enable you to specify the objects from which properties are to be retrieved. A client can
specify either a single object or a set of related objects.
A client can create any number of property filters. Each filter defines both a set of objects and a set of
properties. When the client requests property updates, the PropertyCollector draws from the union of all
the client’s property filters. A change in any of the selected properties specified by any of the filters results in
a change set entry returned to the client.
To specify objects and properties, you must defined a PropertyFilterSpec object. The
PropertyFilterSpec contains two parts:
A specification for the set of objects from which to retrieve properties. This is done with the ObjectSet
property of the filter’s PropertyFilterSpec.
A specification for the set of properties to retrieve from the selected objects. This is done with the PropSet
property of the filter’s PropertyFilterSpec.
Part of the power of the property filter is the ability to guide the selection of a set of objects in dynamic ways.
You can specify in detail how the server should traverse the inventory tree to the desired managed objects,
without the need for the client to see the contents of intervening objects.
ObjectSpec
An ObjectSpec object identifies the managed objects whose properties are returned to the client. The
ObjectSpec can be used to specify a single managed object or a set of related managed objects reached by
traversing the inventory tree.
The ObjectSet property of the PropertyFilterSpec object comprises a list of ObjectSpec objects, where
each ObjectSpec can select one or more managed objects of interest to the client. Each ObjectSpec works
independently to choose a subset of managed objects, which is then joined with the subsets specified by other
ObjectSpecs in the same property filter to form the set of managed objects from which returned properties
are retrieved.
The simplest use of an ObjectSpec is to set the obj property to a managed object reference, and set the skip
property to false, omitting the selectSet property. The result is to select only the single managed object from
which to retrieve properties.
To select a set of related managed objects, you need to use the selectSet property of the ObjectSpec. This
causes VirtualCenter or the host agent to traverse the inventory tree, starting with the managed object
specified in the obj property. Each managed object visited during the traversal may be selected for property
retrieval, or may be used to continue the traversal.
The selectSet property comprises a list of TraversalSpec objects, each of which can specify a path to
another managed object and another TraversalSpec object to continue the traversal. TraversalSpecs can
be nested as needed to identify a specific path in the inventory tree.
PropertySpec
The PropSet property of the PropertyFilterSpec object comprises a list of PropertySpec objects. A
PropertySpec object specifies properties to be returned from the set of managed objects selected by the
ObjectSpec part of the property filter.
Each PropertySpec object can specify a set of properties for a different object type. This gives you the ability
to select a number of managed objects of different types (using the ObjectSet property of the
PropertyFilterSpec) and retrieve properties that are specific to the different managed object types. For each
type of managed object from which a property is desired, the client must create a corresponding
PropertySpec object within the property filter.
The type field of the PropertySpec object is set to the type name for the desired type of managed object. See
the description of the PropertySpec object in the VMware Infrastructure SDK Reference Guide for type
property values.
The properties desired from the managed object are specified 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 leave the pathSet property empty.
To obtain a reference to an entire managed object (rather than a subset of its properties), set the PropertySpec
all property to false and leave the pathSet property empty.
To obtain one or more specific properties of a managed object, omit the all property and set the pathSet
property to the property names:
The pathSet is a list of property path names. The form of a property path name depends on whether the
property is a nested or simple value:
Paths to nested properties are specified using dot notation (the dot used as delimiter between property
names):
PropertyFilterSpec.PropSet.type
Paths to simple properties are specified as you might expect, using the property name alone, as in:
PartialUpdates
The properties of the TraversalSpec data type have the following functions:
type—The type of object to which the TraversalSpec applies. If the tree you are traversing contains an
object that extends this type, the PropertyCollector applies the base type’s TraversalSpec.
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 flag that determines whether the referenced object should be included in the set of
objects monitored by the PropertyCollector, or merely used as a step in traversing a tree of objects. This
field is relevant only if the PropertyFilterSpec contains a PropertySpec object keyed to the type of the
referenced object. Where the PropertySpecnormally causes the PropertyCollector to report
properties of the referenced object, a “true” value in this field overrides the PropertySpec. Usually, it’s
safe to omit this field.
selectSet—An array of SelectionSpec objects representing the next step of the traversal; each may be
another TraversalSpec object or may simply name a TraversalSpec object defined elsewhere.
This section describes ways to use TraversalSpec objects to traverse parts of a tree whose structure is known
in advance. These cases are presented from less complex to more complex.
For example, suppose you want to monitor the free space for all datastores within a datacenter. The free space
is available as a property of DatastoreSummary, which is a property of Datastore. The Datacenter object
contains an array of Datastore objects.
Given this structure, you must create a PropertyFilter object containing a PropertyFilterSpec object that
contains a PropertySpec object and an ObjectSpec object. The PropertySpec object needs to specify the
Datastore object type, as well as the path to the freespace property from the Datastore object:
summary.freespace. The resulting PropertySpec object tells the PropertyCollector to collect the value of
the freespace property from all Datastore objects within the object selection set specified by the
ObjectSpec object.
To create an ObjectSpec
1 Set the obj property to a reference to the Datacenter managed object.
2 Set the skip field to true. Since you know in advance that the object reference you have refers to a
Datacenter object, you need only specify how to traverse a Datacenter object to find the associated
Datastore objects. This requires setting the selectSet property of the ObjectSpec to an array
containing a single TraversalSpec object.
3 Set the type of the TraversalSpec object to Datacenter. When the PropertyCollector tries to traverse
the starting object you specified in the ObjectSpec, it will look for a matching type in the value of the type
field to determine how to traverse the Datacenter object.
4 Set the path field to datastore to traverse the array of Datastore objects. The path property of the
TraversalSpec object tells the PropertyCollector how to get to the next object in the traversal.
5 Set the selectSet property of the TraversalSpec object to an empty array (or omit it entirely)—you
don’t need a second traversal step.
The resulting set of selected objects contains all those Datastore objects 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.
For example, suppose you want to collect the UUIDs of all the virtual machines in a datacenter. You have a
reference to the datacenter, and you know that your inventory hierarchy has several folders of virtual
machines under the datacenter, and that there are no nested folders. Thus, all the VirtualMachine objects are
found exactly two levels below the Datacenter objects, and each can be reached by traversing exactly one
Folder object.
1 Set the obj property to the reference to the Datacenter object, as the starting point of the traversal.
2 Set the skip property to “true” so that the PropertyCollector starts from the correct object.
3 rom to collect properties from the starting object; or you can rely on the absence of a PropertySpec object
with a type property set to Datacenter. The PropertyCollector will not collect properties from a
Datacenter object unless you also create a PropertySpec object for datacenters.
4 Set the selectSet array to contain a single TraversalSpec object. To traverse only virtual machine
folders below the datacenter, you need only one TraversalSpec object to describe how to make the first
step of the traversal.
5 In the TraversalSpec object, set the type property to Datacenter, to match the type of the first object
you want to traverse.
6 Set the path property to the name of the property in the Datacenter object that refers to its virtual
machine folders: vmFolder.
Optionally, you can set the skip property of the TraversalSpec to “true,” to specify that the
PropertyCollector should ignore the properties of the folder (not required, however, since the
PropertyCollector does not collect properties from a Folder object unless you also create a PropertySpec
object for folders).
1 In the TraversalSpec object created to traverse the Datacenter object’s vmFolder property, add a
TraversalSpec object to its selectSet array.
2 In this TraversalSpec object, set the type property to Folder.
3 Set the path property of this TraversalSpec object to childEntity. This is the name of the Folder
property that refers to the folder’s virtual machines.
4 Leave the skip property of this TraversalSpec object unset, or set it to a “false” value. If you set it to a
“true” value, it will cause the PropertyCollector to ignore any PropertySpec object that applies to
VirtualMachine objects.
5 The selectSet property of this TraversalSpec object should be an empty array or omitted, because you
don’t need to traverse beyond the VirtualMachine objects.
To collect a specific property from the VirtualMachine objects, use a PropertySpec object.
1 Define a PropertySpec object.
2 Set the type property to VirtualMachine. This causes the PropertyCollector to collect properties
from VirtualMachine objects in the selection set.
3 Leave the all property unset, because you want to collect only a subset of properties from
VirtualMachine objects.
4 Set the pathSet property to config.uuid, because the UUID is found in the uuid property of the config
property of the VirtualMachine object.
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 example, suppose you want to create a PropertyFilterSpec that contains an ObjectSpec designed to
traverse a managed entity hierarchy, starting from any arbitrary object in that hierarchy and selecting all
managed entities below and including the starting object. You don’t know in advance the type of the starting
object, so you need to create an ObjectSpec with a list of TraversalSpec objects, at least one for each
managed entity type (Folder, Datacenter, ComputeResource, ResourcePool, ClusterComputeResource,
VirtualMachine, HostSystem).
1 Set the obj property to the starting object.
2 Set the skip property to a false value, or omit it.
3 Add seven TraversalSpec objects to the selectSet array. Although there are only four types of objects
to traverse, you need extra TraversalSpec objects because some objects have two paths to traverse, but
only a single path can be specified in a TraversalSpec.
a One TraversalSpec object has type Datacenter and name TraverseDC1. Set the path property to
hostFolder.
b One TraversalSpec object has the type Datacenter and name TraverseDC2. Set the path property
to vmFolder.
c One TraversalSpec object has the type Folder and name TraverseFolder. Set the path property
to childEntity.
d One TraversalSpec object has the type ComputeResource and name TraverseCR1. Set the path
property to resourcePool.
e One TraversalSpec object has the type ComputeResource and name TraverseCR2. Set the path
property to host.
f One TraversalSpec object has the type ResourcePool and name TraverseRP1. Set the path
property to resourcePool.
g One TraversalSpec object has the type ResourcePool and name TraverseRP2. Set the path
property to vm.
Each TraversalSpec object needs a selectSet array, containing SelectionSpec objects—not
TraversalSpec objects—that simply name the types of objects that could be encountered at the next traversal
step. The PropertyCollector uses the names to identify the next TraversalSpec object to apply.
Because a Folder can be followed by another Folder, a Datacenter, or a ComputeResource,
TraverseFolder needs five SelectionSpec objects. Their names are TraverseFolder, TraverseDC1,
TraverseDC2, TraverseCR1, and TraverseCR2. Each SelectionSpec object invokes the name of a
TraversalSpec object defined elsewhere in the PropertyFilter.
A Datacenter object can be followed only by a folder object, so TraverseDC1 needs an array of one
SelectionSpec object, named TraverseFolder.
Similarly, TraverseDC2 needs an array of one SelectionSpec object, named TraverseFolder.
A ComputeResource object can be followed either by a ResourcePool or a HostSystem. There is no need to
traverse a HostSystem, but there are two different ResourcePool TraversalSpecs to cover, so TraverseCR1
needs an array of two SelectionSpec objects, named TraverseRP1 and TraverseRP2.
TraverseCR2 can lead only to a HostSystem object, so there is no need for it to have a selectSet array.
TraverseRP1 can lead only to another ResourcePool, but there are two paths out of ResourcePool, so it
needs an array of two SelectionSpec objects, named TraverseRP1 and TraverseRP2.
TraverseRP2 can lead only to VirtualMachine objects, so there is no need for it to have a selectSet array.
After creating one or more PropertySpec objects, you can use the PropertyCollector to collect properties
from all the selected managed entities—for instance, the name, configuration status, and a reference to each
managed entity.
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 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 into the range of the new filter because toolsVersion is a nested
property of VirtualMachineSummary.GuestInfo. A change to a data object is by definition a change to one
of its nested properties, since a data object has no single value of its own.
When the change set is returned to the client, it could include a copy of the entire data object called
summary.guest, or it could return only the nested property (toolsVersion) that changed. The choice is
determined by the partialUpdates flag. If the flag is set to true, only the nested property is returned; if the
flag is set to false, the whole property specified in the property filter is returned.
A ComputeResource
AddAuthorizationRole 158 renaming 81
AddHost_Task 135 standalone host, adding 135
AddPortGroup 140 connecting hosts 137
AddServiceConsoleVirtualNic 142 console preferences 99
AddStandaloneHost_Task 135 CPU
AddVirtualSwitch 140 allocating (resource pools) 130
affinity rule 129 allocation 100
alarm conditions, multiple 122 configuring processors 99
AlarmAction 124 feature mask 100
alarms usage (metric alarm condition) 121
actions, defining 124 usage (resource pools), limiting 131
condition statuses 121 cpuAffinity 99
conditions, defining 121 CreateAlarm 120
creating 120 CreateCluster 127
deleting 126 CreateCollectorForEvents 111
disabling 126 CreateDatacenter 79
metric alarm expressions 121 CreateFolder 80
state alarm expressions 123 CreateGroup 157
AlarmSetting 123 CreateResourcePool 129
AlarmTriggeringAction 124 CreateSnapshot_Task 86
annotation (property) 103 CreateUser 157
anti-affinity rule 129 CreateVM_Task 93
AssignUserToGroup 157
authorization role
D
adding 158 Datacenter
creating 79
B deleting 80
backing devices 101 renaming 81
Datastore
C defining 103
cancelable (TaskInfo property) 167 datastore files
CloneVM_Task 97 deleting virtual machine files 80
cloning virtual machines unregistering virtual machines 80
as a template (sample code) 98 debug mode, enabling 103
CloneVM_Task 97 default power operations, defining 103
ClusterComputeResource Destroy_Task
creating 127 deleting a datacenter 80
clusters deleting a folder 80
configuring/reconfiguring 128 DestroyChildren 132
creating 127 destroying resource pools 132
DRS, enabling for 128 Development workstation, defined 13
HA, enabling for 128 deviceChange 100
more efficient resource usage 138 disk usage (metric alarm condition) 121
moving hosts into 135 duplicate UUIDs 104
removing hosts from 137
VirtualMachineCloneSpec 97
VirtualMachineConfigSpec 93
VirtualMachineConsolePreferences 99
VirtualMachineDefaultPowerOpInfo 103
VirtualMachineFileInfo 103
VirtualMachineFlagInfo 103
VirtualMachineRelocationSpec 92
vlanId 141
vmFolder
as root of datacenter 79
VMkernel
updating TCP/IP configuration 142
VMkernel, configuring TCP/IP 139
VMotion 88
VmToolsUpgradeFaul 189
VMware DRS
enabling 128
VMware Tools, upgrading 189
VNIC
adding 141
see Virtual Network Interface Card (VNIC)
W
Web Services Interoperability Organization (WS-I) Basic
Profile 1.0 28
WSDL (web services description language), defined 28