VMware vSphere Web Services SDK - 6.0 Programming Guide

vSphere Web Services SDK
Programming Guide
vSphere Web Services SDK 6.0
This document supports the version of each product listed and supports all subsequent versions until the document is replaced by a new edition. To check for more recent editions of this document, see http://www.vmware.com/support/pubs.
EN-001411-02
vSphere Web Services SDK Programming Guide
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
Copyright © 2011-2015 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 is a registered trademark or trademark 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.
3401 Hillview Ave. Palo Alto, CA 94304 www.vmware.com
2 VMware, Inc.

Contents

About This Book 11
1 VMware vSphere and vSphere Management APIs 13
Virtualization and VMware vSphere Components 13 vSphere Development Tools 14
vSphere Web Services SDK 14 CIM APIs 14 vSphere SDK for Perl 14 vSphere PowerCLI 14
VIX API 14 SDK Developer Setup 15 SDK Samples 15 UML Diagrams Used in This Guide 15
2 vSphere API Programming Model 17
vSphere Client-Server Architecture 17 vSphere API as a Web Service 18
WSDL Files and the Client-Side Proxy Interface 18
Network Access to the vSphere Web Service 19
Language-Specific Classes and Methods 19
Mapping XML Data Types to Java and C# Data Types 20 Access to Managed Objects 21 Access to vSphere Server Data 21
Obtaining Information from a Server 22
Working with Data Structures 22
Accessing Property Values 22
Unset Optional Properties 25
Escape Character in Name and Path Properties 25
3 Client Applications 27
vCenter Server Connections 27 Establishing a Single Sign On Session with a vCenter Server 28
LoginByToken (C# Example) 28
LoginByToken (Java Example) 33 Establishing a Session with Username and Password Credentials 38
Overview of a Java Sample Application 38 Web Server Session Token 41
Accessing the HTTP Endpoint with JAX-WS 42
Accessing the vSphere Server 43
Closing the Connection 44
Using the Java Samples as Reference 44 Multiple Versions of the vSphere API 45 Identifying the API Version Supported by the Server 46 Java and C# Sample Applications 46
Java Samples 46
C# Samples 46
VMware, Inc. 3
vSphere Web Services SDK Programming Guide
4 Datacenter Inventory 49
Inventory Overview 49 Inventory Hierarchies and ServiceInstance 50
Folders in the Hierarchy 50
ESXi Inventory Hierarchy 51 Accessing Inventory Objects 51 Creating Inventory Objects 52 Privileges Required for Inventory Management 52
Privileges 53
Permissions 53 Managed and Standalone ESX/ESXi Hosts 54
5 Property Collector 57
Introduction to the PropertyCollector 57
Data Retrieval 58
Inventory Traversal and Object Selection 58 vSphere Data Objects for Property Collection 58 vSphere Methods for Property Collection 58 PropertyCollector Example (RetrievePropertiesEx) 59 Inventory Traversal 66
TraversalSpec Traversal 66
SelectionSpec Traversal 72 Client Data Synchronization (WaitForUpdatesEx) 77
Property Filters 77
WaitForUpdatesEx 77 Server Data Transmission 79 PropertyCollector Performance 79 SearchIndex 79
6 Authentication and Authorization 81
Objects for Authentication and Authorization Management 81 Authentication and Authorization for ESXi and vCenter Server 82
ESXi User Model 82
vCenter Server User Model 83
vSphere Security Model 83
Setting Up Users, Groups, and Permissions 84 Obtaining User and Group Information from UserDirectory 85 Managing ESXi Users with HostLocalAccountManager 86 Managing Roles and Permissions with AuthorizationManager 86
Using Roles to Consolidate Sets of Privileges 88
Modifying Sample Roles to Create New Roles 89
Granting Privileges Through Permissions 89 Authenticating Users Through SessionManager 91
Using VMware Single Sign On for vCenter Server Sessions 91 Using the Credential Store for Automated Login 91
Credential Store Methods 92
Credential Store Backing File 92
Credential Store Samples 93
Specifying Roles and Users with the Credential Store 93 Managing Licenses with LicenseManager 94
7 Hosts 95
Host Management Objects 95 Retrieving Host Information 95
4 VMware, Inc.
Configuring and Reconfiguring Hosts 96 Managing the Host Lifecycle 97
Reboot and Shutdown 97
Using Standby Mode 97
Disconnecting and Reconnecting Hosts 97 Querying and Changing the Host Time 98 Querying Virtual Machine Memory Overhead 98
8 Storage 99
Storage Management Objects 99 Introduction to Storage 100
How Virtual Machines Access Storage 100
Datastores 101 Choosing the Storage API to Use 102 Configuring Disk Partitions 103 Multipath Management 104 Configuring iSCSI Storage 104 Creating and Managing Datastores 106
Accessing Datastores 107
Creating and Modifying a VMFS Datastore 107
Removing and Updating Datastores 109
Managing VMFS Datastores with HostStorageSystem 109 Managing VMFS Volume Copies (Resignaturing) 109 Managing Diagnostic Partitions 110
Retrieving Diagnostic Partition Information 111
Creating a Diagnostic Partition 111 Sample Code Reference 111
Contents
9 vSphere Networks 113
Virtual Switches 113 Using a Distributed Virtual Switch 114
Distributed Virtual Switch Configuration 115
Backup, Rollback, and Query Operations 116 VMware Standard Virtual Switch 116
vNetwork Standard Switch Environment 117
Setting Up Networking with vSS 118
Defining the Host Network Policies 120
NIC Teaming 120
Setting Up IPv6 Networking 121
Adding Networking Services 122 Sample Code Reference 122
10 Virtual Machine Configuration 125
VirtualMachine Management Objects and Methods 125 Creating Virtual Machines and Virtual Machine Templates 126
Creating a Virtual Machine Using VirtualMachineConfigSpec 126
Creating Virtual Machine Templates 127
Cloning a Virtual Machine 127
Converting a Template to a Virtual Machine 128
Accessing Information About a Virtual Machine 128 Configuring a Virtual Machine 129
Name and Location 130
Hardware Version 130
Boot Options 131
VMware, Inc. 5
vSphere Web Services SDK Programming Guide
Operating System 131
CPU and Memory Information 132
Networks 133
Fibre Channel NPIV Settings 133
File Locations 134 Adding Devices to Virtual Machines 134 Performing Virtual Machine Power Operations 135 Registering and Unregistering Virtual Machines 136 Customizing the Guest Operating System 137 Installing VMware Tools 137 Upgrading a Virtual Machine 138
11 Virtual Machine Management 139
Virtual Machine Migration 139
Cold Migration 140
Migration with VMotion 140
Using Storage VMotion 140 Snapshots 140
Creating a Snapshot 141
Reverting to a Snapshot 141
Deleting a Snapshot 142 Linked Virtual Machines 142
Linked Virtual Machines and Disk Backings 142
Creating a Linked Virtual Machine 143
Removing Snapshots and Deleting Linked Virtual Machines 144
Relocating a Virtual Machine in a Linked Virtual Machine Group 144
Promoting a Virtual Machine's Disk 145
Performing Advanced Manipulation of Delta Disks 145
12 Virtual Applications 147
About Virtual Applications 147
Management Overview 147
Direct and Linked Children 148
OVF Packages 148 Creating a VirtualApp 149 Managing VirtualApp Children 149 Exporting a Virtual Application 150
VirtualApp and OvfManager Methods 150
VirtualApp Data Structures 151
OvfManager Data Structures 152
Example of Generating an OVF Package 152 Importing an OVF Package 154 Virtual Application Life Cycle 154
Powering a Virtual Application On or Off 154
Unregistering a Virtual Application 155
Suspending a Virtual Application 155
Destroying a Virtual Application 155
13 Resource Management 157
Resource Management Objects 157 Introduction to Resource Management 158 Resource Allocation 158
Resource Pool Hierarchies 158
Resource Pool Management Guidelines 159
6 VMware, Inc.
Cluster Overview 159 Creating and Configuring Resource Pools 160
Understanding Expandable Reservation 160
Deleting Child Resource Pools 161
Moving Resource Pools or Virtual Machines Into a Resource Pool 162 Introduction to VMware DRS and VMware HA Clusters 162
VMware DRS 162
VMware HA 162 Creating and Configuring Clusters 163
Creating a Cluster 163
Adding a Host to a Cluster 164
Reconfiguring a Cluster 164 Managing DRS Clusters 164 Managing HA Clusters 165
Using VMware HA and DRS Together 166
14 Tasks and Scheduled Tasks 167
Creating Tasks 167
Session Persistence 167
Cancelling a Task 168
Using TaskInfo to Determine Task Status 168
Monitoring TaskInfo Properties 169 Accessing and Manipulating Multiple Tasks 170
Gathering Data with a ViewManager Object 170
Gathering Data with a TaskManager Interface 177 Understanding the ScheduledTaskManager Interface 179
Scheduling Tasks 180
Cancelling a Scheduled Task 182 Using a TaskHistoryCollector 183
Creating a TaskHistoryCollector Filter 183
Managing the HistoryCollector 183 Sample Code Reference 184
Contents
15 Events and Alarms 185
Event and Alarm Management Objects 185 Understanding Events 185
Managing Events with EventManager 186
Event Data Objects 187
Formatting Event Message Content 187
Creating Custom Events 188 Using an EventHistoryCollector 188
Creating an EventHistoryCollector Filter 188
Managing the HistoryCollector 189 Using Alarms 189
Obtaining a List of Alarms 189
Creating an Alarm 190 Defining Alarms Using the AlarmSpec Data Object 190
Specifying Alarm Trigger Conditions with AlarmExpression 191
Specifying Alarm Actions 192
Deleting or Disabling an Alarm 193 Sample Code Reference 193
16 vSphere Performance 195
vSphere Performance Data Collection 195
VMware, Inc. 7
vSphere Web Services SDK Programming Guide
PerformanceManager Objects and Methods 197 Retrieving vSphere Performance Data 198
Performance Counter Example (QueryPerf) 199
Large-Scale Performance Data Retrieval 206
Using the QueryPerf Method as a Raw Data Feed 206
Comparison of Query Methods 207
Retrieving Summary Performance Data 207 Performance Counter Metadata 208 Performance Intervals 208 vSphere Performance and Data Storage 210
Modifying Historical Intervals 210
Modifying Performance Counter Collection Levels 210 Sample Code Reference 211
A Diagnostics and Troubleshooting 213
Troubleshooting Best Practices 213 Overview of Configuration Files and Log Files 214
ESX/ESXi Log File 214
Virtual Machine Log Files 215
vCenter Server Log Files 216 Modifying the Log Level to Obtain Detailed Information 216
Setting the Log Level on ESX/ESXi Systems 216
Generating Logs 217
Setting the Log Level on vCenter Server Systems 217 Using DiagnosticManager 217 Using the MOB to Explore the DiagnosticManager 219 Generating Diagnostic Bundles 220
B Managed Object Browser 221
Using the MOB to Explore the Object Model 221
Accessing the MOB 221
Using the MOB to Navigate the VMware Infrastructure Object Model 222 Using the MOB to Invoke Methods 222
Passing Primitive Datatypes to Method 222
Passing Arrays of Primitives to Methods 223
Passing Complex Structures to Methods 223
C HTTP Access to vSphere Server Files 227
Introduction to HTTP Access 227 URL Syntax for HTTP Access 228
Datastore Access (/folder) 228
Host File Access (/host) 229
Update Package Access (/tmp) 230
Privilege Requirements for HTTP Access 230
D Privileges Reference 231
Privileges Required to Invoke Operations 231 Privileges Required to Read Properties 239 Privileges Defined for the Administrator Role 240
E Sample Program Overview 245
Java Sample Programs (JAXWS Bindings) 245 C# Sample Programs 249
Axis 4.1 252
8 VMware, Inc.
Index 255
Contents
VMware, Inc. 9
vSphere Web Services SDK Programming Guide
10 VMware, Inc.

About This Book

The vSphere Web Services SDK Programming Guide provides information about developing applications using theVMware® vSphere Web Services SDK 6.0.
VMware provides different APIs and SDKs for various applications and goals. The vSphere Web Services SDK targets developers who create client applications for managing VMware VMware ESX/ESXi and VMware vCenter Server systems.
To view the current version of this book as well as all VMware API and SDK documentation, go to
http://www.vmware.com/support/pubs/sdk_pubs.html.
Revision History
This book is revised with each release of the product or when necessary. A revised version can contain minor or major changes. Ta bl e 1 summarizes the significant changes in each version of this book.
Tabl e 1. Revision History
Revision Date Description
04Sep2015 Updated information about migrating VMs with VMotion across data centers.
12Mar2015 vSphere 6.0 - Rewrote “Exporting a Virtual Application” section in Virtual Applications chapter.
19Sep2013 vSphere 5.5 – Added a C# example of using LoginByToken; clarified limitation for HA clusters.
10Sep2012 vSphere 5.1 – Added information about using the SessionManager.LoginByToken method; added
information about distributed virtual switches.
24AUG2011 vSphere 5.0 - Revised performance manager chapter. Added information about: unset properties, using
vCenter to access host data, and using the QueryConfigOption to add devices; emphasized ListView instead of TaskManager; clarified limits and limitations of Linked Virtual Machines; updated samples in chapters 3,5,14, and 16; replaced information about Axis bindings with JAX-WS; and updated paths to samples supplied with SDK.
13JUL2010 Restructured manual and added chapters about host, storage, and networking. Revised property
collector chapter and added appendix about HTTP access.
07MAY2009 vSphere Web Services SDK 4.0 Programming Guide.
®
vSphere components available on
Intended Audience
This book is intended for anyone who needs to develop applications using the vSphere Web Services SDK. Developers typically create client applications using Java or C# (in the Microsoft .NET environment) targeting VMware vSphere. An understanding of Web Services technology and some programming background in one of the stub languages (C# or Java) is required.
VMware Technical Publications Glossary
VMware Technical Publications provides a glossary of terms that might be unfamiliar to you. For definitions of terms as they are used in VMware technical documentation go to http://www.vmware.com/support/pubs.
VMware, Inc. 11
vSphere Web Services SDK Programming Guide
Document Feedback
VMware welcomes your suggestions for improving our documentation. Send your feedback to
docfeedback@vmware.com.
12 VMware, Inc.
1

VMware vSphere and vSphere Management APIs

VMware vSphere supports robust, fault-tolerant virtualized applications, networking, and storage. vSphere offers many optional components and modules such as VMware High Availabiltiy and VMware VMotion. The VMware vSphere Web Services SDK gives Web services developers programmatic access to vSphere components.
The chapter includes the following topics:
“Virtualization and VMware vSphere Components” on page 13
“vSphere Development Tools” on page 14
“SDK Developer Setup” on page 15
“SDK Samples” on page 15
“UML Diagrams Used in This Guide” on page 15

Virtualization and VMware vSphere Components

VMware software products virtualize computing resources, including CPU, memory, storage, and networks. Virtualization provides an abstraction layer between computing resources, physical storage, and networking hardware, and the applications that use the resources.
1
VMware vSphere includes ESXi, vCenter Server, and several additional server products. The base products support running and managing virtual machines. With additional licenses, you can take advantage of the vSphere distributed resource management (DRS), disaster recovery, and high availability (HA) features.
The ESXi hypervisor is capable of supporting multiple virtual machines and other virtual components,
such as storage and networks.
vCenter Server provides central management for all of the components of a virtualized environment,
including multiple ESX/ESXi host systems, clusters, storage, and distributed virtual switches. It is distributed in two package formats:
Windows-based software services.
Linux-based VMware vCenter Server Appliance.
vSphere Web Client is a GUI to manage vSphere. It provides the UI platform that you use to integrate your
solution with vSphere. The vSphere Web Client also includes a server-side Java platform. You can develop Java plugins that use the vSphere Web Services SDK to communicate with vSphere servers. See the vSphere Web Client SDK for more information about building UI and service plugins for the vSphere Web Client.
For more information about ESXi and vCenter Server, see the VMware vSphere documentation page on the VMware Web site. If you are new to VMware vSphere or new to the vSphere Web Services SDK, see one of these vSphere administrator documents for background information about vSphere:
vSphere Virtual Machine Administration Guide
VMware, Inc. 13
vSphere Web Services SDK Programming Guide
vCenter Server and Host Management Guide
vSphere Resource Management Guide

vSphere Development Tools

VMware supports SDKs and scripting tools for managing vSphere.

vSphere Web Services SDK

The vSphere Web Services SDK is the most comprehensive of the available management APIs. The SDK works against both ESX/ESXi and vCenter Server systems. As a Web Services SDK, the SDK is language neutral. The SDK includes stubs and examples for Java and C# and a comprehensive documentation set including an API Reference generated from the source.

CIM APIs

The VMware CIM APIs provide a CIM (Common Information Model) interface for developers building management applications. With the VMware CIM APIs, developers can use standards-based CIM-compliant applications to manage ESX/ESXi hosts.
The CIM APIs include:
CIM SMASH/Server Management API – profiles compatible with the DMTF System Management
Architecture for Server Hardware (SMASH) initiative. SMASH profiles allow CIM clients to monitor system health of a managed server.
CIM Storage Management API – profiles compatible with the Storage Management Initiative
Specification (SMI-S) of the Storage Network Industry Association. SMI-S profiles allow CIM clients to explore the virtual machines on an ESX/ESXi host, and associated storage resources.

vSphere SDK for Perl

The vSphere SDK for Perl is an easy-to-use Perl scripting interface to the vSphere API. Administrators and developers can work with vSphere API objects using vSphere SDK for Perl subroutines. Administrators can use the utility applications included with vSphere SDK for Perl.
The vSphere SDK for Perl also includes the Web Services for Management component for writing scripts that retrieve CIM data from the ESX/ESXi host using CIMOM, a service that provides standard CIM management functions. The vSphere SDK for Perl also includes subroutines for managing the VMware Credential Store and an example application that illustrates credential store use.
vSphere SDK for Perl is bundled with the vSphere Command-Line Interface (vSphere CLI). The vSphere CLI command set allows you to run common system administration commands against ESX/ESXi systems from an administration server of your choice.

vSphere PowerCLI

VMware vSphere PowerCLI provides a Windows PowerShell interface to the vSphere API. vSphere PowerCLI includes PowerShell Cmdlets for administering vSphere components. In addition, the vSphere PowerCLI package includes the vSphere SDK for .NET for developers who want to create their own applications.

VIX API

The VIX API is a library for writing scripts and programs to manipulate virtual machines. It is high-level, easy to use, and practical for both script developers and application programmers. This API is well suited for dedicated IT personnel in an organization building their own in-house tools. It might also be used by software vendors using VIX to integrate VMware products with their own products or to build management products for virtual machines.
14 VMware, Inc.
Chapter 1 VMware vSphere and vSphere Management APIs
Figure 1-1 gives an overview of the different vSphere APIs and CLIs and illustrates how they fit into the virtual
infrastructure.
Figure 1-1. vSphere APIs and CLIs

SDK Developer Setup

Before you can start developing applications with the vSphere Web Services SDK, you must download the software and set up your system. The Developers Setup Guide has complete instructions for Java and C# development and discusses a simplified secure setup for development environments.

SDK Samples

The SDK includes a set of samples that illustrate much of the SDK features. Two sample sets are available:
Java samples use the generated Java stubs that are shipped with the SDK.
C# samples use the generated C# stubs that are shipped with the SDK.
Both sample sets include a set of utility applications that are used by the sample code.
The code fragments in this guide are in part based on the Java sample applications, but present code that does not require utility applications to run.
See Appendix E, “Sample Program Overview,” on page 245 for lists of samples for the two languages and a brief explanation of what each sample does.

UML Diagrams Used in This Guide

This guide uses UML (unified modeling language) diagrams to illustrate the API objects and their relationships. The guide includes class diagrams and instance diagrams. Figure 1-2 shows the UML notation used for managed objects and data objects. The diagrams use a tilde (~) if an object has no properties or methods. Ellipses (...) means some properties or methods are omitted.
Figure 1-2. Legend for UML Class Diagrams
VMware, Inc. 15
vSphere Web Services SDK Programming Guide
16 VMware, Inc.
2

vSphere API Programming Model

The vSphere API is implemented as a language-neutral Web service. The API is based on a remote procedure call mechanism that client applications use to access services and components on ESX, ESXi, and vCenter Server systems.
This chapter includes the following topics:
“vSphere Client-Server Architecture” on page 17
“vSphere API as a Web Service” on page 18
“Access to Managed Objects” on page 21
“Access to vSphere Server Data” on page 21

vSphere Client-Server Architecture

VMware vSphere client applications participate in a distributed architecture that uses an asynchronous communications model. This architecture is based on server-side managed objects, client-side managed object references, and data objects.
Managed objects exist on a vSphere server (ESX/ESXi or vCenter Server system). They represent vSphere
services and components. Services include PropertyCollector, SearchIndex, PerformanceManager, and ViewManager. Components include inventory objects such as VirtualMachine, Datastore, and Folder.
2
Managed object references are client application references to server-side managed objects. Your client
application uses ManagedObjectReference objects when it invokes operations on a server. A ManagedObjectReference is guaranteed to be unique and persistent during an object's lifetime. The reference persists after an object has moved within the inventory, across sessions, and across server restarts. If you remove an object, for example, a virtual machine, from the inventory, and then put it back, the reference changes.
Data objects contain information about managed objects. Your client application sends data objects to and
receives data objects from a vSphere server. Examples are the different specification and capability objects such as VirtualMachineConfigSpec and HostCapability.
Figure 2-1 shows a vSphere server and client application. The client has a managed object reference to a virtual
machine on the server, and a copy of the GuestInfo data object for the virtual machine. A client must maintain its copy of a data object because, depending on the type of client request, a vSphere server might send property data for a data object as a set of name-value pairs associated with a managed object reference. See the description of the ObjectContent data object in the vSphere API Reference.
VMware, Inc. 17
vSphere Web Services SDK Programming Guide
vSphere server
VirtualMachine
managed object
vSphere client application
GuestInfo
data object
GuestInfo
data object
managed object
reference to a
VirtualMachine
data objects
network
connection
Figure 2-1. vSphere Server and Client
The VMware vSphere application model uses an asynchronous client-server communication model in most cases. Methods are nonblocking and return a reference to a Task managed object. See Chapter 14, “Tasks and
Scheduled Tasks,” on page 167.

vSphere API as a Web Service

The vSphere API is a language-neutral Web service that runs on ESX/ESXi and vCenter Server systems. The vSphere API complies with the Web Services Interoperability Organization (WS-I) Basic Profile 1.0. The WS-I Basic Profile 1.0 includes support for:
XML Schema 1.0
SOAP 1.1
WSDL 1.1
For information about the WS-I Basic Profile 1.0, go to the Web Services Interoperability Organization (WS-I) Web site at http://www.ws-i.org.
Web services support operations, which are the same as methods in other programming languages. The vSphere API Web service provides access to all operations necessary for monitoring and managing vSphere components, such as compute resources, virtual machines, networks, storage, and so on.

WSDL Files and the Client-Side Proxy Interface

The vSphere Web Services SDK provides a set of WSDL (Web Services Description Language) files that define the vSphere Web Services API. Web-services development tools such as JAX-WS wsimport, or Microsoft .NET wsdl.exe use these WSDL files to generate client-side proxy code (stubs).
The client proxy provides a language-specific vSphere API, for example, using Java or C#. The proxy facilitates remote method invocation, organization of object data, and other aspects of distributed, object-oriented, applications programming. Your client application calls proxy interface methods. The client proxy uses SOAP (Simple Object Access Protocol) to exchange WSDL messages with a vSphere server.
Figure 2-2 is a representation of a client application that uses the client proxy interface to call a method. The
client proxy interface is based on the WSDL definitions.
18 VMware, Inc.
Chapter 2 vSphere API Programming Model
client application
vSphere Server
method execution
method invocation
SOAP-encoded WSDL
network
connection
WSDL2Java,
wsdl.exe, or
other tool
WSDL
files
client
proxy
interface
(Java, C#,
or other)
Figure 2-2. Client-Server Communication Through a Client Proxy Interface
To use the VMware client proxy interface, you must import the vSphere API client libraries in to your client application using the following Java and C# statements.
C# using VimApi; Java import com.vmware.vim25.*;
I
MPORTANT The vSphere Web Services SDK includes Java client-side proxy code that was generated using
the JAX-WS toolkit. If the versions of Java and JAX-WS on your development platform are the same as those used to generate the proxy interface shipped in the SDK, you do not have to generate client-side proxy code from the WSDL. See the Developer’s Setup Guide for information about configuring a development environment for the vSphere Web Services SDK.

Network Access to the vSphere Web Service

Your client application can use the vSphere API to communicate with vSphere servers over HTTPS (HTTP over an encrypted Secure Sockets Layer connection) at port 443. HTTPS is the default protocol. You can configure the server to support HTTP. Use HTTP access only for test or development environments, not for production. See the Developer’s Setup Guide for details.

Language-Specific Classes and Methods

The SOAP tools generate language-specific classes and methods that match the WSDL definitions. The tools also produce objects and methods that are not in the WSDL files.
Generated objects. The additional objects provide access to the vSphere Web Service to establish the
client-server connection (VimServiceLocator, AppUtil) and declare the methods defined for the vSphere API (VimPortType, VimService).
Generated methods. The additional methods are accessor (getter) and mutator (setter) methods for
properties. For Java, the method names are constructed by adding get and set prefixes to a property name, and changing the first character of the property name to upper case.
VMware, Inc. 19
vSphere Web Services SDK Programming Guide
Tab le 2- 1 identifies client proxy definitions for the vSphere Web Services SDK WSDL.
Tabl e 2-1 . Client Proxy Definitions
Element Access Java C#
Access to vSphere Web service (HTTPS/HTTP)
Access to vSphere API methods
Access to vSphere API properties
vSphere API data objects
VimServiceLocator class AppUtil class
VimPortType class VimService class
get
PropertyName
methods defined for data objects
Data objects in the vSphere API (see the vSphere API Reference) defined as objects in the proxy interface
The following code fragments show getter and setter method declarations for the AfterStartupTaskScheduler.minute property.
Java
public int getMinute() {
return minute; }
public void setMinute(int minute) {
this.minute = minute; }
and set
PropertyName
get and set methods defined for properties
C#
public int minute {
set; get; }
You can extrapolate the getter and setter methods that are available in the client proxy interface from the vSphere API Reference. For example, the ScsiLun data object has a displayName property. For the Java API, you can use a setDisplayName method to assign a string value to the property, and obtain the string value by using the getDisplayName method. The vSphere Web Services SDK includes Java and C# sample code that illustrates using the proxy interfaces. See Chapter 3, “Client Applications,” on page 27.

Mapping XML Data Types to Java and C# Data Types

In this guide, the UML class and object diagrams use the primitive data type names such as string and integer, without the XML Schema definition namespace prefix (xsd:). The vSphere API Reference contains the complete data type name, such as xsd:string. The data types map to the primitive data types of the programming language used for the client application.
Tab le 2- 2 lists some of the more common XML primitive data type mappings.
Tabl e 2-2 . Standard XML Schema Primitives to Java and .NET Data Type Mappings
XML Schema Java .NET Data Type
xsd:base64binary byte[] Byte[]
xsd:boolean boolean Boolean
xsd:byte byte SByte
xsd:dateTime java.util.Calendar DateTime
xsd:decimal java.math.BigDecimal Decimal
xsd:double double Double
xsd:float float Single
xsd:int int Int32
xsd:string java.lang.String String
20 VMware, Inc.

Access to Managed Objects

Your client application obtains access to managed objects through the ServiceInstance managed object and its associated ServiceContent data object. The ServiceContent data object contains managed object references to services and manager entities, and to the root folder of the inventory.
The ServiceInstance managed object is the root object of the inventory on both ESX/ESXi and vCenter Server systems. The server creates the ServiceInstance, and creates the manager entities that provide services in the virtual environment. Examples of manager entities are LicenseManager, PerformanceManager, and ViewManager.
The ServiceInstance is the primary point of access to the server inventory. Your client application starts by connecting to a server and creating a reference to the ServiceInstance. After you have connected to the server, you can call the ServiceInstance.RetrieveServiceContent method to a ServiceContent data object. ServiceContent provides access to the vSphere managed object services. See “Overview of a Java
Sample Application” on page 38 for an example of connecting to a server and using the ServiceInstance
reference to retrieve the ServiceContent object.
Figure 2-3 shows the object model for the ServiceInstance and ServiceContent objects. The figure shows
some of the ServiceContent managed object references and the target objects of the references. Each managed object reference identifies a specific managed object on the server with its type and a value. (The value property is an opaque string.)
Figure 2-3. ManagedObjectReference Data Object
Chapter 2 vSphere API Programming Model

Access to vSphere Server Data

To obtain information about the virtual infrastructure, you retrieve managed object properties. Managed object properties can be simple data types, such as integer or string data, or they can be complex types such as data objects that contain sets of properties.
VMware, Inc. 21
vSphere Web Services SDK Programming Guide

Obtaining Information from a Server

With a reference to a managed object, you can obtain information about the state of the server-side inventory objects and populate client-side data objects based on the values. You can use one of the following approaches:
Use an accessor (getter) method. The client proxy interface provides accessor methods for each data object
property. You can use these accessor methods to obtain the values of the object. See “Language-Specific
Classes and Methods” on page 19 for information about client proxy interface accessor methods.
Use a PropertyCollector to navigate to a selected point on the server and obtain values from specific
properties. See Chapter 5 for more information about PropertyCollector.
Use 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.
I
MPORTANT You can use API methods to operate on managed objects in the vSphere inventory. A method
that updates properties in one managed object may also update properties in other managed objects. The Server performs asynchronous updates to the inventory. There is no guarantee that the inventory will be completely updated when the method returns to the caller. Use the PropertyCollector method WaitForUpdatesEx to obtain property changes.

Working with Data Structures

Properties contain information about the server-side objects at a given point in time. The value of a property can be of one of the following types:
Simple data types, such as a string, boolean, or integer (or other numeric) audiotape. 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 managed object references (a type of data object) to virtual machines hosted by that physical machine. As another example, the SessionManager managed object has a sessionList property that is an array of UserSession data objects.
Enumerated types (enumeration, 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 three possible string values—poweredOn, poweredOff, or suspended.
The type of a property is often a string, but the property actually expects one of the values an enumeration encapsulates. For example, when you set VirtualMachineConfigSpec.guestid you can specify one of the elements of the VirtualMachineGuestOSIdentifier as a string.
Complex (or composite) data types. For example, the HostProfileConfigInfo object contains data
objects, an array of data objects, and an array of strings.

Accessing Property Values

To use the composite data structures and arrays that contain Server data:
Use dot notation to access nested properties in composite data structures.
Cast unconstrained property values (xsd:anyType) to array types.
Use keys or index values as appropriate to access array values.
Nested Properties and Property Paths in Composite Data Structures
vSphere Data objects can include properties that are defined as composite data types, such as data objects. The embedded data objects can also contain properties that are data objects. Properties can nest to several levels.
22 VMware, Inc.
Chapter 2 vSphere API Programming Model
For example, the following figure shows a UML class diagram of the VirtualMachine managed object, which has a runtime property that is defined as an xsd:dateTime data type. VirtualMachine also has a summary property that is a VirtualMachineSummary data object. The VirtualMachineSummary data object contains a config property that is a VirtualMachineConfigSummary data object.
Figure 2-4. VirtualMachine Managed Object and Nested Properties
To refer to a nested property, use dot notation to separate the object names in the sequence that defines the path to the property. Your code must handle the type referenced at the end of the sequence.
For example, you can compare the property referenced by the path summary.config.guestId (a string value) to the property referenced in the path summary.config (the complete VirtualMachineSummary data object).
Tab le 2- 3 shows examples of property references and the corresponding data types for some of the properties
of the VirtualMachine managed object shown in Figure 2-4.
Tabl e 2-3 . Nested Properties and Data Types
Reference Data Type
summary VirtualMachineSummary data object
summary.config VirtualMachineConfigSummary data object
summary.config.guestID string
xsd:anyType Arrays
The vSphere API uses xsd:anyType unconstrained type declarations. A vSphere client must map values of xsd:anyType to explicit data types. An xsd:anyType value can represent a single data value or it can
represent an array. The WSDL for the vSphere API defines array types for all of the data values that a vSphere client can send or receive as arrays. The array types use the prefix "ArrayOf". An example of an array type is ArrayOfString for string values.
When a client sends data to a vSphere Server, the client must use explicit datatypes. For example, a client can define a MethodAction for a ScheduledTask. The vSphere API defines arguments to the action (the MethodActionArgument.value property) as type xsd:anyType. If the action takes an array argument, the client must set the corresponding MethodAction.argument[].value to the appropriate ArrayOf... type.
When a client receives xsd:anyType data from a vSphere Server, it must cast the data to an explicit type. For example, the PropertyCollector method RetrievePropertiesEx returns a set of ObjectContent data objects. The ObjectContent.propSet property is a list of DynamicProperty objects that contains the requested property values. Each DynamicProperty object contains a name-value pair. The value property (DynamicProperty.val) is of type xsd:anyType. It can represent a single object or an array of objects.
When the returned value is a single object such as an Event, ManagedObjectReference, or String, you can cast it directly to a variable of the appropriate type. However, when the value is an array of objects you cannot cast the anyType value directly to an array variable.
VMware, Inc. 23
vSphere Web Services SDK Programming Guide
When the PropertyCollector returns array data, it sends it as an xsd:anyType value. The language-specific bindings contain definitions for array objects such as ArrayOfEvent, ArrayOfManagedObjectReference, and ArrayOfString, and corresponding "get" methods. To extract the actual array from a property of type xsd:anyType, cast DynamicProperty.val to the appropriate array type and use the matching get method – for example, getEvent(), getManagedObjectReference(), or getString().The following sections provide examples of how to cast returned values for a few of the array types. The code uses the JAX-WS-generated Java bindings for the VMware vSphere Web Services SDK WSDL. Each of the code fragments uses this logic:
Use the DynamicProperty.getVal() method to retrieve the anyType property value.
Specify the appropriate array type to cast the anyType value.
Use the corresponding get method to assign the result of the cast operation to a list variable.
Event Array Example
/* * Handling arrays of Event objects. * Cast the return value to ArrayOfEvent and use getEvent(). */ List[] eventList = ((ArrayOfEvent) dynamicProp.getVal()).getEvent();
ManagedObjectReference Array Example
/* * Handling arrays of ManagedObjectReference objects. * Cast the return value to ArrayOfManagedObjectReference and use getManagedObjectReference(). */ List[] morList =
((ArrayOfManagedObjectReference)dynamicProp.getVal()).getManagedObjectReference();
String Array Example
/* * Handling arrays of strings. * Cast the return value to ArrayOfString and use getString(). */ List[] stringList = ((ArrayOfString) dynamicProp.getVal()).getString();
Indexed Array and Key-Based Array Properties
The VMware vSphere data structures include array properties, which can be indexed arrays or key-based arrays.
Indexed arrays are accessed by using an index integer. Indexed arrays are used for arrays of data types
whose positions in the array do 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 a Perl hash or a Python dictionary) uses a unique, unchanging value as a key to access an element’s value. Typically, the key is a string, but integers can also be used. For example, Event arrays use integers as keys. Nested properties can also refer to entries in a key-based array. For example, a.b.c["xyz"] refers to the property c that has the key value of xyz.
The vSphere management object model uses key-based arrays to track 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 of the components of an array.
24 VMware, Inc.
Chapter 2 vSphere API Programming Model

Unset Optional Properties

Many of the Data Objects in the vSphere Web Services SDK have optional properties that may be set by your client application or by a Server process or event. If you retrieve a data object that has a optional property that is unset, the Server will not return a value for the optional property. If you call an accessor function to retrieve the property value, the value returned by the function depends on the programming language that you are using.
For example, if you are programming in Java or C#, the value you will receive for an unset property is “null”.
Figure 2-5 shows part of the Properties table for the HostFirewallInfo Data Object in the vSphere Web Services
SDK API Reference. When you look at properties in the vSphere Web Services SDK API Reference, you can see that optional properties are marked with a red asterisk.
In this example, that the defaultPolicy property is always returned, but the ruleset property will be returned as a null value if it has not been set.
Figure 2-5. Data Object - HostFirewallInfo Properties
Since Data Objects are part of many different constructs, there is no standard scenario for when an optional property should be set, what will happen if an optional property is left unset, or what you should do if a null value is returned.

Escape Character in Name and Path Properties

The percent sign (%) is used as an escape character to embed special characters in strings. For example, %2f (or %2F) is interpreted as the slash (/) character. To include a percent sign as a literal in a string, use %%.The path to the inventory starts from the root folder (ServiceContent.rootFolder property), denoted by the slash character.
Tabl e 2-4 . Special Characters
Character Description Representation in URL
%Percent sign %25
/ Slash %2F, %2f
\ Backslash %5C, %5c
-Dash %2D, %2d
. Dot %2E, %2e
Double quotation mark %2B, %2b
VMware, Inc. 25
vSphere Web Services SDK Programming Guide
26 VMware, Inc.
3

Client Applications

This chapter includes the following topics:
“vCenter Server Connections” on page 27
“Establishing a Single Sign On Session with a vCenter Server” on page 28
“Establishing a Session with Username and Password Credentials” on page 38
“Web Server Session Token” on page 41
“Multiple Versions of the vSphere API” on page 45
“Identifying the API Version Supported by the Server” on page 46
“Helper Classes for C# Sample Applications” on page 46

vCenter Server Connections

Every vCenter Server client application must connect to the Server and pass user account credentials to authenticate to the Server. After the connection has been established, the client application can use vSphere services to access the virtual environment.
vSphere uses SSL certificates, HTTP tokens, and vCenter Single Sign On tokens to authenticate a client and support a persistent connection between the client and vCenter Server. The following table provides an overview of these elements.
Tabl e 3-1 . Security Elements for Client-Server Connections
Security Element Description
SSL certificates vSphere Servers use standard X.509 version 3 (X.509v3) certificates to encrypt session
information sent over Secure Socket Layer (SSL) protocol connections. In a production environment, client applications verify the vSphere Server certificate during the connection sequence. The examples in this chapter and the examples in the vSphere Web Services SDK accept all certificates.
HTTP tokens A vSphere Server uses an HTTP token to identify a client session. The Server provides the
Client authentication
vCenter Single Sign On token
Client authentication
username/password
HTTP token in its response to a client connection request. Subsequent messages between the client and the Server include the HTTP token in the HTTP header.
vSphere supports vCenter Single Sign On. A vCenter client can obtain a vCenter Single Sign On token from a vCenter Single Sign On Server and use that token to login to a vCenter Server.
Username/password authentication for client-server connections has been deprecated as of vSphere 5.1.
3
VMware, Inc. 27
vSphere Web Services SDK Programming Guide

Establishing a Single Sign On Session with a vCenter Server

vSphere uses single sign on to provide a single point of authentication for clients. vSphere includes the vCenter Single Sign On Server. To use vCenter Single Sign On, your client obtains a SAML token (Security Assertion Markup Language) from the vCenter Single Sign On Server and passes the token to the vCenter Server in the login request. The token represents the client and contains claims that support client authentication. Components in the vSphere environment perform operations based on the original authentication. For information about obtaining a vCenter Single Sign On token from the vCenter Single Sign On Server, see vCenter Single Sign On Programming Guide.
To use single sign on, your client calls the LoginByToken method. Your client must send a SAML token to the vCenter Server by embedding the token in the SOAP header for the LoginByToken request. During the login sequence, your client must save and restore the HTTP session cookie. The vCenter Single Sign On SDK contains sample code that demonstrates how to use the LoginByToken method.
The following sections describe examples of using the LoginByToken method to establish a vCenter Single Sign On session with a vCenter Server.
“LoginByToken (C# Example)” on page 28
“LoginByToken (Java Example)” on page 33

LoginByToken (C# Example)

The following sections describe a C# example of using the LoginByToken method.
vCenter Server Single Sign On Session
After you obtain a SAML token from the vCenter Single Sign On Server, you can use the vSphere API method LoginByToken to establish a single sign on session with a vCenter Server. To establish a vCenter Server session that is based on SAML token authentication, the client must embed the SAML token in the SOAP header of the LoginByToken request. The C# LoginByToken example uses the following .NET services to support a single sign on session.
Tabl e 3-2 . Microsoft .NET Elements for vCenter Single Sign On Sessions
.NET Element / Namespace vCenter Single Sign On Usage
SecurityPolicyAssertion
Microsoft.Web.Services3.Security
SendSecurityFilter
Microsoft.Web.Services3.Security
ServicePointManager
System.net
ConfigurationManager
System.Configuration
CookieContainer
System.Net
The sample creates a custom policy assertion derived from the SecurityPolicyAssertion class. The custom assertion contains the SAML token and X509 certificate.
The sample defines a custom output filter derived from the SendSecurityFilter class. The custom filter adds the token and certificate to the outgoing SOAP message.
The sample uses the ServicePointManager to specify SSL3 and HTTP 100-Continue behavior.
The sample uses the ConfigurationManager to specify certificate metadata (password and certificate type).
The sample uses the CookieContainer class to manage vCenter session cookies.
Persistent vCenter Sessions
A persistent vCenter session relies on a session cookie. When the vCenter Server receives a connection request (SessionManager.RetrieveServiceContent), the Server creates a session cookie and returns it in the HTTP header of the response. The client-side .NET framework embeds the cookie in HTTP messages that the client sends to the Server.
28 VMware, Inc.
Chapter 3 Client Applications
The LoginByToken request includes the SAML token and client certificate security assertions for client authentication. After successful login, the authentication overhead is no longer needed. The client resets the VimService context to eliminate the security overhead. Subsequent client requests will contain the session cookie, which is enough to support the persistent, authenticated session.
Sample Code
The code examples in the following sections show how to use the LoginByToken method with a holder-of-key security token. The code examples are based on the LoginByTokenSample project contained in the vCenter Single Sign On SDK. The project is located in the dotnet samples directory (SDK/ssoclient/dotnet/cs/samples/LoginByToken).
Project file – LoginByToken.csproj
Sample code – LoginByTokenSample.cs
SOAP header manipulation code – CustomSecurityAssertionHok.cs
Using LoginByToken
The example program uses the following elements and general steps:
LoginByTokenSample Constructor
Token Acquisition
Security Policies
Connection and Login
LoginByTokenSample Constructor
The LoginByTokenSample class constructor creates the following elements to set up access to the vCenter Server.
VimService object – Provides access to vSphere API methods and support for security policies and
session cookie managment. It also stores the vCenter Server URL.
CookieContainer – Provides local storage for the vCenter session cookie.
ManagedObjectReference – Manually created ManagedObjectReference to retrieve a
ServiceInstance at the beginning of the session.
The following code fragment shows the LoginByTokenSample constructor.
Example 3-1. LoginByTokenSample Constructor
// Global variables private VimService _service; private ManagedObjectReference _svcRef; private ServiceContent _sic; private string _serverUrl;
public LoginByTokenSample(string serverUrl) { _service = new VimService(); _service.Url = serverUrl; _serverUrl = serverUrl; _service.CookieContainer = new System.Net.CookieContainer(); _svcRef = new ManagedObjectReference(); _svcRef.type = "ServiceInstance"; _svcRef.Value = "ServiceInstance"; }
VMware, Inc. 29
vSphere Web Services SDK Programming Guide
Token Acquisition
The client must obtain a SAML token from a vCenter Single Sign On Server. See the vCenter Single Sign On Programming Guide.
Security Policies
The LoginByToken sample creates a custom policy assertion that is derived from the .NET class SecurityPolicyAssertion. The assertion class gives the .NET framework access to the SAML token and the
X509 certificate.
The sample performs the following operations to set up the security policy and message handling.
Sets the ServicePointManager properties to specify SSL3 and HTTP 100-Continue response handling.
100-Continue response handling supports more efficient communication between the client and vCenter Server. When the client-side .NET framework sends a request to the Server, it sends the request header and waits for a 100-Continue response from the Server. After it receives that response, it sends the request body to the Server.
Creates an X509Certificate2 object, specifies the certificate file, and imports the certificate. The
certificate file specification indicates a PKCS #12 format file (Public-Key Cryptography Standards) –
PfxCertificateFile. The file contains the client’s private key and public certificate. The PfxCertificateFile setting is defined in the app.config file in the LoginByToken project. The
definition specifies the location of the file.
Creates a custom security assertion to store the SAML token and the certificate. The token and certificate
will be included in the policy data for the LoginByToken request.
Defines a custom output filter that is derived from the .NET class SendSecurityFilter.
Custom Security Assertion The following code fragment shows the LoginByTokenSample class method GetSecurityPolicyAssertionForHokToken. The method returns a CustomSecurityAssertionHok
instance which overrides the .NET class SecurityPolicyAssertion. The security assertion contains the SAML token and the X509 certificate token. This code is taken from the LoginByToken project file
samples/LoginByToken/CustomSecurityAssertionHok.cs.
Example 3-2. Setting Up Security Policies
private SecurityPolicyAssertion GetSecurityPolicyAssertionForHokToken(XmlElement xmlToken) {
//When this property is set to true, client requests that use the POST method //expect to receive a 100-Continue response from the server to indicate that //the client should send the data to be posted. This mechanism allows clients //to avoid sending large amounts of data over the network when the server, //based on the request headers, intends to reject the request ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
X509Certificate2 certificateToBeAdded = new X509Certificate2(); string certificateFile = ConfigurationManager.AppSettings["PfxCertificateFile"]; string password = ConfigurationManager.AppSettings["PfxCertificateFilePassword"]; certificateToBeAdded.Import(certificateFile, password ?? string.Empty,
var customSecurityAssertion = new CustomSecurityAssertionHok(); customSecurityAssertion.BinaryToken = xmlToken; customSecurityAssertion.TokenType = strSamlV2TokenType; customSecurityAssertion.SecurityToken = new X509SecurityToken(certificateToBeAdded);
X509KeyStorageFlags.MachineKeySet);
return customSecurityAssertion; }
Custom Output Filter The following code fragment shows the custom output filter for the custom security assertion. The custom filter provides three methods:
30 VMware, Inc.
Chapter 3 Client Applications
CustomSecurityClientOutputFilterHok class constructor – Creates token and message signature objects
for the SOAP message.
SecureMessage – An override method for the .NET method SendSecurityFilter.SecureMessage. The
override method adds the SAML token and message signature to the .NET Security element.
CreateKeyInfoSignatureElement – Creates an XML document that specifies the SAML token type and ID.
Example 3-3. Output Filter for the Custom SecurityPolicyAssertion
internal class CustomSecurityClientOutputFilterHok : SendSecurityFilter { IssuedToken issuedToken = null; string samlAssertionId = null; MessageSignature messageSignature = null;
/// Create a custom SOAP request filter. /// (Save the token and certificate.) public CustomSecurityClientOutputFilterHok(CustomSecurityAssertionHok parentAssertion) : base(parentAssertion.ServiceActor, true) { issuedToken = new IssuedToken(parentAssertion.BinaryToken,
samlAssertionId = parentAssertion.BinaryToken.Attributes.GetNamedItem("ID").Value; messageSignature = new MessageSignature(parentAssertion.SecurityToken); }
parentAssertion.TokenType);
/// Secure the SOAP message before its sent to the server. public override void SecureMessage(SoapEnvelope envelope, Security security) { //create KeyInfo XML element messageSignature.KeyInfo = new KeyInfo(); messageSignature.KeyInfo.LoadXml(CreateKeyInfoSignatureElement());
security.Tokens.Add(issuedToken); security.Elements.Add(messageSignature); }
/// Helper method to create a custom key info signature element. /// Returns Key info XML element. private XmlElement CreateKeyInfoSignatureElement() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(@"<root><SecurityTokenReference
xmlns=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-
1.0.xsd""
xmlns:wsse=""http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd""
<KeyIdentifier
@"</KeyIdentifier></SecurityTokenReference></root>"); return xmlDocument.DocumentElement; } }
wsse:TokenType=""http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#S AMLV2.0"">
xmlns=""http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-
1.0.xsd""
ValueType=""http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID "">" + samlAssertionId +
Connection and Login
The following code fragment performs the following actions:
Calls the LoginByTokenSample class method GetSecurityPolicyAssertionForHokToken (see
“Security Policies” on page 30) and adds the security policy to the VimService object.
VMware, Inc. 31
vSphere Web Services SDK Programming Guide
The VimService object contains the following data:
vCenter Server URL.
SAML token (stored in the security policy assertion).
X509 certificate (stored in the security policy assertion).
Calls the RetrieveServiceContent method. The method establishes the connection with the vCenter
Server and it returns a session cookie. The session cookie is stored in the cookie container in the VimService object.
Calls the LoginByToken method. The .NET framework uses the security policy assertion and the session
cookie to construct the login request.
Calls the LoginByTokenSample class method resetService to create a new VimService object.
Example 3-4. Connection and Login
// Construct the security policy assertion SecurityPolicyAssertion securityPolicyAssertion = null; securityPolicyAssertion = GetSecurityPolicyAssertionForHokToken(xmlToken);
// Setting up the security policy for the request Policy policySAML = new Policy(); policySAML.Assertions.Add(securityPolicyAssertion);
// Setting policy of the service _service.SetPolicy(policySAML);
_sic = _service.RetrieveServiceContent(_svcRef); if (_sic.sessionManager != null) { _service.LoginByToken(_sic.sessionManager, null); } resetService();
The following code fragment shows the resetService method. The method creates a new VimService object and a new cookie container. The method also obtains a new instance of the session cookie.
Example 3-5. The resetService method
/// Resetting the VimService without the security policies /// as we need the policy only for the LoginByToken method /// and not the other method calls. resetService also maintains the /// authenticated session cookie post LoginByToken. /// /// This method needs to be called only after successful /// login private void resetService() { var _cookie = getCookie(); _service = new VimService(); _service.Url = _serverUrl; _service.CookieContainer = new CookieContainer(); if (_cookie != null) { _service.CookieContainer.Add(_cookie); } }
/// Method to save the session cookie private Cookie getCookie() { if (_service != null)
32 VMware, Inc.
Chapter 3 Client Applications
{ var container = _service.CookieContainer; if (container != null) { var _cookies = container.GetCookies(new Uri(_service.Url)); if (_cookies.Count > 0) { return _cookies[0]; } } } return null; }

LoginByToken (Java Example)

The following example is based on the LoginByTokenSample.java file contained in the vCenter Single Sign On SDK. The SDK contains Java code that supports HTTP and SOAP header manipulation.
“Client Support for a vCenter Single Sign On Session with a vCenter Server” on page 33
“Saving the vCenter Server Session Cookie” on page 34
“Using LoginByToken” on page 36
“Restoring the vCenter Server Session Cookie” on page 37
Client Support for a vCenter Single Sign On Session with a vCenter Server
After you obtain a SAML token from the vCenter Single Sign On Server, you can use the vSphere API method LoginByToken to establish a vCenter Single Sign On session with a vCenter Server. At the beginning of the session, your client is responsible for the following tasks:
Maintain the vCenter session cookie. During the initial connection, the Server produces an HTTP session
cookie to support the persistent connection. Operations during the login sequence will reset the request context so your client must save this cookie and re-introduce it at the appropriate times.
Insert the vCenter Single Sign On token and a timestamp into the SOAP header of the LoginByToken
message.
The example program uses these general steps:
1Call the RetrieveServiceContent method to establish an HTTP connection with the vCenter Server and
save the HTTP session cookie. The client uses an HTTP header handler method to extract the cookie from the vCenter Server response.
2Call the LoginByToken method to authenticate the vCenter session. To send the token to the vCenter
Server, the client uses a handler to embed the token and a time stamp in the SOAP header for the message. To identify the session started with the RetrieveServiceContent method, the client uses a handler to embed the session cookie in the HTTP header.
3 Restore the session cookie.
HTTP and SOAP Header Handlers
To use a vCenter Single Sign On token to login to a vCenter Server, the example uses header handlers to manipulates the HTTP and SOAP header elements of the login request. After establishing a handler, subsequent requests automatically invoke the handler.
An extraction handler obtains the HTTP session cookie provided by the vCenter Server. After setting up
the handler, a call to the RetrieveServiceContent method will invoke the handler to extract the cookie from the Server response.
Insertion handlers put the vCenter Single Sign On token and a timestamp into the SOAP header and the
session cookie into the HTTP header of the login request.
The following figure shows the use of handlers to manipulate header elements when establishing a vCenter Single Sign On session with a vCenter Server.
VMware, Inc. 33
vSphere Web Services SDK Programming Guide
timestamp
vCenter Single
Sign On token
vCenter
client
RetrieveServiceContent( )
session cookie
session cookieHTTP header:
session cookie
HTTP header:
LoginByToken( )
SOAP header:
timestamp
vCenter Single
Sign On token
extraction handler
insertion handler
insertion handler
insertion handler
vCenter
Server
Figure 3-1. Starting a vCenter Session
I
MPORTANT Every call to the vCenter Server will invoke any message handlers that have been established.
The overhead involved in using the SOAP and HTTP message handlers is not necessary after the session has been established. The example saves the default message handler before setting up the SOAP and HTTP handlers. After establishing the session, the example will reset the handler chain and restore the default handler.
The example code also uses multiple calls to the VimPortType.getVimPort method to manage the request context. The getVimPort method clears the HTTP request context. After each call to the getVimPort method, the client resets the request context endpoint address to the vCenter Server URL. After the client has obtained the session cookie, it will restore the cookie in subsequent requests.
Sample Code
The code examples in the following sections show how to use the LoginByToken method with a holder-of-key security token. The code examples are based on the sample code contained in the vCenter Single Sign On SDK. The files are located in the Java samples directory (SDK/ssoclient/java/JAXWS/samples):
LoginByToken sample:
samples/com/vmware/vsphere/samples/LoginByTokenSample.java
Header cookie handlers:
samples/com/vmware/vsphere/soaphandlers/HeaderCookieHandler.java samples/com/vmware/vsphere/soaphandlers/HeaderCookieExtractionHandler.java
SOAP header handlers. These are the same handlers that are used in the vCenter Single Sign On example in vCenter Single Sign On Programming Guide. The SOAP handler files are contained in the vCenter Single Sign On SDK and are located in the sso client soaphandlers directory:
SDK/ssoclient/java/JAXWS/samples/com/vmware/sso/client/soaphandlers
Saving the vCenter Server Session Cookie
The code fragment in this section establishes an HTTP session with the vCenter Server and saves the HTTP session cookie.
34 VMware, Inc.
Chapter 3 Client Applications
VimService.getHandlerResolver( )
HeaderHandler Resolver
VimService
HeaderCookieExtractionHandler
VimPortType
VimService
Request Context
VimService
VimPortType
ServiceContent
HeaderCookieExtractionHandler.getCookie ( )
The following sequence describes these steps and shows the corresponding objects and methods.
1Use the getHandlerResolver method to
save the default message handler. To use the HTTP and SOAP message handlers, you must first save the default message handler so that you can restore it after login. The HTTP and SOAP message handlers impose overhead that is unneccessary after login.
2 Set the cookie handler. The
HeaderCookieExtractionHandler method retrieves the HTTP cookie.
3 Get the VIM port. The VIM port provides
access to the vSphere API methods, including the LoginByToken method.
4 Set the request context endpoint address to
the vCenter Server URL.
5 Retrieve the ServiceContent. This method
establishes the HTTP connection and sets the session cookie.
6 Extract the cookie and save it for later use.
The following example shows Java code that saves the session cookie.
Example 3-6. Saving the vCenter Server Session Cookie
/* * The example uses a SAML token (obtained from a vCenter Single Sign On Server) * and the vCenter Server URL. * The following declarations indicate the datatypes; the token datatype (Element) corresponds * to the token datatype returned by the vCenter Single Sign On Server. * * Element token; -- from vCenter Single Sign On Server * String vcServerUrl; -- identifies vCenter Server * * First, save the default message handler. */
HandlerResolver defaultHandler = vimService.getHandlerResolver();
/* * Create a VIM service object. */ vimService = new VimService();
/* * Construct a managed object reference for the ServiceInstance. */ ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
VMware, Inc. 35
SVC_INST_REF.setType("ServiceInstance"); SVC_INST_REF.setValue("ServiceInstance");
vSphere Web Services SDK Programming Guide
HeaderHandler Resolver
WsSecurityUserCertificateSignatureHandler (key, certificate, ID)
TimestampHandler
SamlTokenHandler (SAML token)
HeaderCookieHandler (session cookie)
VimPortType
VimService
Request Context
VimService
VimPortType.LoginByToken ( )
/* * Create a handler resolver. * Create a cookie extraction handler and add it to the handler resolver. * Set the VIM service handler resolver. */ HeaderCookieExtractionHandler cookieExtractor = new HeaderCookieExtractionHandler(); HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver(); handlerResolver.addHandler(cookieExtractor); vimService.setHandlerResolver(handlerResolver);
/* * Get the VIM port for access to vSphere API methods. This call clears the request context. */ vimPort = vimService.getVimPort();
/* * Get the request context and set the connection endpoint. */ Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
/* * Retrieve the ServiceContent. This call establishes the HTTP connection. */ serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
/* * Save the HTTP cookie. */ String cookie = cookieExtractor.getCookie();
Using LoginByToken
The code fragment in this section sets up the message handlers and calls the LoginByToken method. The following sequence describes the steps and shows the corresponding objects and methods.
1 Create a new HeaderHandlerResolver.
Then set the message security handlers for cookie insertion and for inserting the SAML token and credentials in the SOAP header.
2 Get the VIM port.
3 Set the connection endpoint in the HTTP
request context.
4 Call the LoginByToken method. The
method invocation executes the handlers to insert the elements into the message headers. The method authenticates the session referenced by the session cookie.
36 VMware, Inc.
The following examples shows Java code that calls the LoginByToken method.
VimService.setHandlerResolver ( )
VimPortType
VimService
Request Context
VimService
RequestContext.get () RequestContext.put ( )
Example 3-7. Using LoginByToken
/* * Create a handler resolver and add the handlers. */ HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver(); handlerResolver.addHandler(new TimeStampHandler()); handlerResolver.addHandler(new SamlTokenHandler(token)); handlerResolver.addHandler(new HeaderCookieHandler(cookie)); handlerResolver.addHandler(new WsSecuritySignatureAssertionHandler(
userCert.getPrivateKey(), userCert.getUserCert(), Utils.getNodeProperty(token, "ID")));
vimService.setHandlerResolver(handlerResolver);
/* * Get the Vim port; this call clears the request context. */ vimPort = vimService.getVimPort();
/* * Retrieve the request context and set the server URL. */ Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
Chapter 3 Client Applications
/* * Call LoginByToken. */ UserSession us = vimPort.loginByToken(serviceContent.getSessionManager(), null);
Restoring the vCenter Server Session Cookie
After you log in, you must restore the standard vCenter session context. The code fragment in this section restores the default message handler and the session cookie. As the cookie handler has been replaced by the default handler, the client resets the session cookie by calling request context methods to access the context fields directly. The following sequence describes these steps and shows the corresponding objects and methods.
1 Restore the default message handler. The
handlers used for LoginByToken are not used in subsequent calls to the vSphere API.
2 Get the VIM port.
3 Set the connection endpoint in the HTTP
request context.
4 Set the HTTP request header (vCenter
session cookie).
The following example shows Java code that restores the vCenter session. This code requires the vCenter URL and the cookie and default handler that were retrieved before login. See “Sample Code” on page 34.
VMware, Inc. 37
vSphere Web Services SDK Programming Guide
Example 3-8. Restoring the vCenter Server Session
/* * Reset the default handler. This overwrites the existing handlers, effectively removing them. */ vimService.setHandlerResolver(defaultHandler); vimPort = vimService.getVimPort();
/* * Restore the connection endpoint in the request context. */ // Set the validated session cookie and set it in the header for once, // JAXWS will maintain that cookie for all the subsequent requests
Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext(); ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, vcServerUrl); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
/* * Reset the cookie in the request context. */ Map<String, List<String>> headers = (Map<String, List<String>>)
if (headers == null) { headers = new HashMap<String, List<String>>(); } headers.put("Cookie", Arrays.asList(cookie)); ctxt.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
ctxt.get(MessageContext.HTTP_REQUEST_HEADERS);

Establishing a Session with Username and Password Credentials

You can specify username and password credentials to establish a session with a vCenter Server. This method of establishing a session has been deprecated as of vSphere 5.1. The following steps describe how a client application specifies username and password credentials for access to a vCenter Server.
1 Create a connection to the vSphere server Web service.
2 Instantiate a local proxy object for reference to ServiceInstance. Use this local proxy object to retrieve
the ServiceContent object from the server. ServiceContent contains a reference to the root folder for the inventory and references to the managed objects that provide the vSphere services.
3 Instantiate a local proxy object for access to vSphere API methods.
4 Log in to the server using appropriate credentials (user account, password, and optionally the locale).
5 Access server-side objects to retrieve data and perform management operations.
6 Close the connection.

Overview of a Java Sample Application

This section includes an example of a complete client application that demonstrates the basic client capability. The sample client application prints out the product name, server type, and product version to demonstrate that it is connected and able to retrieve information from the server.
While Example 3-9, “Java Test Client Application,” on page 39 is a complete client application that demonstrates the basic clien t capa bility, it uses a slightly differe nt for mat than t he Java sample files in the SDK\ directory. This example, and the Java samples that are included with your vSphere Web Service SDK, have been compiled using JAX-WS bindings.
Most of the vSphere Web Services SDK samples do not handle exceptions, and they accept all security certificates. Use the samples as examples for extracting the types of data you want to view, but do not use these security or exception techniques in your production applications.
38 VMware, Inc.
Chapter 3 Client Applications
Example 3-9 is a stand-alone application that accepts command-line arguments for the vSphere server name
(DNS name or IP address), user name, and password.
To build a simple vSphere client application
1 Import the vSphere Web Services API libraries:
import com.vmware.vim25.*;
2 Import the necessary Java (and JAX-WS connection, bindings, and SOAP) libraries:
import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.SOAPFaultException;
3 Create the TestClient class:
public class TestClient {
4 Include the class variable declarations/definitions. Use a TrustManager class to accept all certificates, as
shown in “Accessing the HTTP Endpoint with JAX-WS” on page 42. This is not appropriate for a production environment. Production code should implement certificate support.
5 Use the vSphere Web Services APIs to create the connection, as shown in “Accessing the vSphere Server”
on page 43.
6 Retrieve data from the vSphere or vCenter server. In this example, we are just going to print out the
product name, server type, and product version to prove that the client is connected and working correctly.
System.out.println(serviceContent.getAbout().getFullName()); System.out.println("Server type is " + serviceContent.getAbout().getApiType()); System.out.println("API version is " + serviceContent.getAbout().getVersion());
7 Use the VimPort object to close the connection, as shown in “Closing the Connection” on page 44. Always
close your server connections to maintain security.
Java Client Example
Example 3-9 shows the complete sample client application code, without the explanation steps.
Example 3-9. Java Test Client Application
import com.vmware.vim25.*; import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.SOAPFaultException;
public class TestClient {
// Authentication is handled by using a TrustManager and supplying // a host name verifier method. (The host name verifier is declared // in the main function.) // See Example 3-10 for more details.
private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
public boolean isServerTrusted( java.security.cert.X509Certificate[] certs) { return true;
VMware, Inc. 39
vSphere Web Services SDK Programming Guide
}
public boolean isClientTrusted( java.security.cert.X509Certificate[] certs) { return true; }
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; }
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } }
public static void main(String[] args) { try {
// Server URL and credentials.
String serverName = args[0]; String userName = args[1]; String password = args[2]; String url = "https://"+serverName+"/sdk/vimService";
// Variables of the following types for access to the API methods // and to the vSphere inventory. // -- ManagedObjectReference for the ServiceInstance on the Server // -- VimService for access to the vSphere Web service // -- VimPortType for access to methods // -- ServiceContent for access to managed object services
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); VimService vimService; VimPortType vimPort; ServiceContent serviceContent;
// Declare a host name verifier that will automatically enable // the connection. The host name verifier is invoked during // the SSL handshake.
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true; } }; // Create the trust manager.
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm;
// Create the SSL context
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
// Create the session context
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
// Initialize the contexts; the session context takes the trust manager.
sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null);
// Use the default socket factory to create the socket for the secure connection
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set the default host name verifier to enable the connection.
HttpsURLConnection.setDefaultHostnameVerifier(hv);
40 VMware, Inc.
// Set up the manufactured managed object reference for the ServiceInstance
SVC_INST_REF.setType("ServiceInstance"); SVC_INST_REF.setValue("ServiceInstance");
// Create a VimService object to obtain a VimPort binding provider. // The BindingProvider provides access to the protocol fields // in request/response messages. Retrieve the request context // which will be used for processing message requests.
vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
// Store the Server URL in the request context and specify true // to maintain the connection between the client and server. // The client API will include the Server's HTTP cookie in its // requests to maintain the session. If you do not set this to true, // the Server will start a new session with each request.
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
// Retrieve the ServiceContent object and login
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); vimPort.login(serviceContent.getSessionManager(),
userName, password, null);
Chapter 3 Client Applications
// print out the product name, server type, and product version
System.out.println(serviceContent.getAbout().getFullName()); System.out.println("Server type is " + serviceContent.getAbout().getApiType()); System.out.println("API version is " + serviceContent.getAbout().getVersion());
// close the connection
vimPort.logout(serviceContent.getSessionManager());
} catch (Exception e) { System.out.println(" Connect Failed "); e.printStackTrace();
} }//end main() }// end class TestClient
Use the following command to compile the code for Example 3-9, “Java Test Client Application,” on page 39, after you have saved it as a .java file:
c:>javac -classpath path-to-vim25.jar TestClient.java
Use the following command to execute the compiled class (binary) file:
c:>java -classpath path-to-vim25.jar TestClient web-service-url user-name user-password

Web Server Session Token

As with other Web services, the vSphere Web service maintains session state for each client connection by using a token in the HTTP header to identify the session. The vSphere server returns a session token to the client in its response to the client connection request. Subsequent messages between client and server automatically include the token.
Each of the stand-alone samples in the SDK\vsphere-ws\java\JAX-WS\samples\com\vmware\ uses the JAX-WS TrustAllTrustCertificates class, as discussed in Example 3-10 to ignore certificates, obtain a session token, and then connect to the server.
CAUTION We do not recommend that you trust all certificates in a production environment. Instead, you can look at the sample code to see how the JAX-WS libraries are used when making the connection, but set up an SSL policy that allows connection only with trusted certificates.
VMware, Inc. 41
vSphere Web Services SDK Programming Guide
The logic for getting a cookie and putting it in the header looks like this:
//cookie logic List cookies = (List) headers.get("Set-cookie"); cookieValue = (String) cookies.get(0); StringTokenizer tokenizer = new StringTokenizer(cookieValue, ";"); cookieValue = tokenizer.nextToken(); String path = "$" + tokenizer.nextToken(); String cookie = "$Version=\"1\"; " + cookieValue + "; " + path;
// set the cookie in the new request header Map map = new HashMap(); map.put("Cookie", Collections.singletonList(cookie));
((BindingProvider) vimPort).getRequestContext().put( MessageContext.HTTP_REQUEST_HEADERS, map);

Accessing the HTTP Endpoint with JAX-WS

The steps for accessing any HTTP endpoint with JAX-WS bindings are listed at the beginning of Example 3-10,
“Obtaining a Session Token - Code Fragments from VMPromoteDisks.java,” on page 44. These steps include
the vSphere Web Services SDK Server URL, vSphere server object, and variables.
1 In this example we use a TrustManager class to accept all certificates. This is not appropriate for a
production environment. Production code should implement certificate support.
private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return;
}
}
2 Include the Server URL and credentials as arguments in the main method:
public static void main(String[] args) { try {
String serverName = args[0]; String userName = args[1]; String password = args[2]; String url = "https://"+serverName+"/sdk/vimService";
3 Declare variables of the following types for access to vSphere server objects:
ManagedObjectReference for the ServiceInstance.
42 VMware, Inc.
Chapter 3 Client Applications
VimService object for access to the Web service.
VimPortType object for access to all of the methods defined in the vSphere API.
ServiceContent for access to the managed object services on the server.
The following Java code fragment shows these variable declarations:
ManagedObjectReference SVC_INST_REF
VimService vimService;
VimPortType vimPort;
ServiceContent serviceContent;
4 Declare a host name verifier that will automatically enable the connection. The host name verifier is
invoked during the SSL handshake.
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
5 Instantiate the trust manager object.
// Create the trust manager.
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new TrustAllTrustManager();
trustAllCerts[0] = tm;
6 Create the SSL context
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
7 Create the session context
javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
8 Initialize the contexts; the session context takes the trust manager.
sslsc.setSessionTimeout(0);
sc.init(null, trustAllCerts, null);
9 Use the default socket factory to create the socket for the secure connection
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
10 Set the default host name verifier to enable the connection.
HttpsURLConnection.setDefaultHostnameVerifier(hv);

Accessing the vSphere Server

The steps that use the vSphere Web Services APIs to create the connection are:
1 Create a managed object reference for the ServiceInstance object on the server.
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
SVC_INST_REF.setType("ServiceInstance");
SVC_INST_REF.setValue("ServiceInstance");
2 Create a VimService object to obtain a VimPort binding provider. The BindingProvider object provides
access to the protocol fields in request/response messages. Retrieve the request context which will be used
for processing message requests.
The VimServiceLocator and VimPortType objects provide access to vSphere servers. The getVimPort
method returns a VimPortType object that provides access to the vSphere API methods.
vimService = new VimService();
vimPort = vimService.getVimPort();
Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
VMware, Inc. 43
vSphere Web Services SDK Programming Guide
3 Store the Server URL in the request context and specify true to maintain the connection between the client
and server. The client API will include the Server's HTTP cookie in its requests to maintain the session. If
you do not set this to true, the Server will start a new session with each request.
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
4 Retrieve the ServiceInstance content (the ServiceContent data object) and log in to the server.
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(),
userName, password, null);
isConnected = true;

Closing the Connection

Use the VimPort object again to close the connection. Always close your server connections to maintain security.
vimPort.logout(serviceContent.getSessionManager());
} catch (Exception e) {
System.out.println(" Connect Failed ");
e.printStackTrace();
}
}//end main()
}// end class TestClient

Using the Java Samples as Reference

The following code fragment from the SDK\vsphere-ws\java\JAX-WS\samples\com\vmware\vm\ VMPromoteDisks.java sample shows another implementation of the server connection. Review the
stand-alone Java samples that are shipped with your vSphere Web Services SDK, and use similar code to get a session token for your client application.
Example 3-10. Obtaining a Session Token - Code Fragments from VMPromoteDisks.java
. . .
private static String cookieValue = ""; private static Map headers = new HashMap();
. . .
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm; javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
...
private static void connect() throws Exception {
HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }; trustAllHttpsCertificates(); HttpsURLConnection.setDefaultHostnameVerifier(hv);
44 VMware, Inc.
SVC_INST_REF.setType(SVC_INST_NAME); SVC_INST_REF.setValue(SVC_INST_NAME);
vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); headers = (Map) ((BindingProvider) vimPort).getResponseContext().get( MessageContext.HTTP_RESPONSE_HEADERS); vimPort.login(serviceContent.getSessionManager(), userName, password, null); isConnected = true;
propCollectorRef = serviceContent.getPropertyCollector(); rootRef = serviceContent.getRootFolder(); }
...
Chapter 3 Client Applications

Multiple Versions of the vSphere API

When a client application connects to a Web service running on an vSphere server (ESX/ESXi or vCenter Server system), the server detects the version of the API that was used to develop the client and makes available only those operations supported by the client.
Client applications convey information about the API version used in the SOAP messages that they send to a vSphere server. These SOAP messages include a versionID in the soapAction attribute. The details are handled transparently by the SOAP toolkit and the client proxy code. The server adjusts its behavior based on the client’s version information, exposing the API version that the client supports to the client.
Starting with vSphere 4.0, information about the supported API versions is contained in an XML file, vimServiceVersions.xml, located on the server (Example 3-11).
Example 3-11. Service-Versions File (vimServiceVersions.xml)
<?xml version="1.0" encoding="UTF-8" ?>
- <!-- Copyright 2008-2010 VMware, Inc. All rights reserved. -->
- <namespaces version="1.0">
- <namespace> <name>urn:vim25</name> <version>5.0</version>
- <priorVersions> <version>2.5u2</version> <version>2.5</version>
</priorVersions> </namespace>
- <namespace> <name>urn:vim2</name> <version>2.0</version>
</namespace>
</namespaces>
If you are developing a client application that must support multiple server versions at the same time (ESX/ESXi 5.0 and ESX/ESXi 3.x, for example), you must obtain information about the API versions that are supported on the server and provide logic in your code to use or not use features, based upon the version information.
VMware, Inc. 45
vSphere Web Services SDK Programming Guide

Identifying the API Version Supported by the Server

One approach to targeting multiple versions of the API from the same client application code is to check for the existence of the server versions file on the server. If you do not find a vimServiceVersions.xml file on the server, the server is older than ESX/ESXi 4.x, vCenter Server 4.x.

Java and C# Sample Applications

The vSphere Web Services SDK includes sample applications, written in Java and C#, that demonstrate features of the vSphere API and object model (see Appendix E, “Sample Program Overview,” on page 245). Most of the samples do not handle exceptions, and they accept all security certificates. So use the applications as examples for extracting the types of data you want to view, but do not use the helper classes, trust store methods or exception handling techniques in your production environment.

Java Samples

The Java samples in your vSphere Web Services SDK include .java files that you can compile and then run using any Java editor or IDE. The samples accept command-line arguments for the vSphere server name (DNS name or IP address), user name, and password.

C# Samples

The C# samples in your vSphere Web Services SDK include a .cs file and three project files in each directory (.proj, 2008.proj, and 2010.proj) so you can run them using Microsoft’s Visual Studio.
Like the Java samples, the C# samples also accept command-line arguments for the vSphere server name (DNS name or IP address), user name, and password, and they accept all certificates to establish the SSL handshake.
Unlike the Java samples, the C# samples use the helper classes discussed in “Helper Classes for C# Sample
Applications” on page 46.
Helper Classes for C# Sample Applications
The C# sample applications included with the vSphere Web Services SDK include C# helper classes that handle the details of creating sessions, obtaining session tokens, saving the session token as a string to a file, and reusing the session. The Microsoft .NET Web services implementation uses the Cookie class to handle the session information from the server.
46 VMware, Inc.
Chapter 3 Client Applications
The helper classes (listed in Tab le 3-3 ) handle command-line input such as common parameters, server name, and other details. These helper classes are located in the unpacked C# version of the SDK download, in this location:
C# Helper Classes %SDKHOME%\vsphere-ws\dotnet\cs\samples\AppUtil
Tab le 3 -3 lists the helper classes available for C#.
Tabl e 3-3 . Helper Classes for C# Sample Applications
AppUtils Functional Description
AppUtil.cs Convenient methods you can use to handle user input from command line.
Catches errors (faults). Logs output to console.
AppUtil.csproj Convenient methods you can use to handle user input from command line.,
built to run on versions of Microsoft Visual Studio that were released before
2008.
ArgumentHandlingException.cs Convenient methods you can use to handle exceptions.
CertPolicy.cs Convenient methods you can use to customize certificate error messages.
ClientUtil.cs Convenient methods you can use to handle user input from command line.
CustomSecurity.cs Convenient methods you can use to override the SOAP security filter.
CustomSecurityAssertionBearer.cs Convenient methods you can use to create a custom policy assertion that
Log.cs Convenient methods you can use to create a log file or send log output to the
OptionSpec.cs Helper class for handling default and custom command-line arguments.
PropertyManager.cs Convenient methods you can use to listen for Property Manager updates.
ServiceUtil.cs Wrapper methods for the vimService methods (the local proxy code
SvcConnection.cs Convenient methods you can use to create a web service connection handler.
TrustAllCertificatePolicy.cs Creates an instance of local proxy for connecting to the server, and obtains
VersionUtil.cs Convenient methods you can use to retrieve the namespace and API version.
VMUtils.cs Convenient methods you can use to create a virtual machine configuration
Catches errors (faults). Logs output to console.
applies security to a SOAP message exchange.
console.
methods) for API 2.0 and prior releases.
managed object references to several needed managed objects— ServiceInstance, ServiceContent, rootFolder.
spec.
VMware, Inc. 47
vSphere Web Services SDK Programming Guide
48 VMware, Inc.
4

Datacenter Inventory

The vSphere inventory is a representation of the vSphere datacenter and the objects in the datacenter. Knowing how the objects in the datacenter relate to each other helps you traverse the inventory hierarchy and access the objects you want to manipulate.
The chapter includes the following topics:
“Inventory Overview” on page 49
“Inventory Hierarchies and ServiceInstance” on page 50
“Accessing Inventory Objects” on page 51
“Creating Inventory Objects” on page 52
“Privileges Required for Inventory Management” on page 52
“Managed and Standalone ESX/ESXi Hosts” on page 54

Inventory Overview

The vSphere inventory contains the following types of objects:
Systems in the datacenter: Host, VirtualMachine, and VirtualApp.
4
Support components: ComputeResource, Datastore, Network, and virtual devices.
Organizational components: Folder and Datacenter
When you manage the virtual infrastructure, you access objects and their properties and methods based on their location in the inventory. Understanding the inventory structure is therefore critical for any programming task. You always start with the ServiceInstance associated with a session, which is the root object of the inventory, and traverse the inventory hierarchy from there. See Chapter 5, “Property Collector,” on page 57. How you access objects depends on whether your client application is connected to a vCenter Server or an ESX/ESXi system.
VMware, Inc. 49
vSphere Web Services SDK Programming Guide

Inventory Hierarchies and ServiceInstance

When you start a session, vSphere creates a ServiceInstance with one root folder, one Datacenter, and four folders that hold the different types of inventory objects.
When you access a vCenter Server System, the hierarchy shown in Figure 4-1 allows you to traverse the inventory.
Figure 4-1. vCenter Server Inventory Hierarchy
CAUTION If your ESX/ESXi hosts are managed by a vCenter Server, you must always access your hosts through the vCenter server. The vCenter server keeps track of all synchronous and asynchronous operations, and will have the latest status and inventory information about each ESX/ESXi host. Therefore, connecting directly to a host that is managed by a vCenter Server may give you incorrect or incomplete data.
When you have ESX/ESXi hosts that are not managed by a vCenter Server, your application can connect to each host directly.

Folders in the Hierarchy

If your installation includes a vCenter Server system, you can create additional datacenters under the root folder. For everyDatacenter object, the server automatically creates the following Folder objects:
A folder for VirtualMachine, template, and VirtualApp objects.
A folder for a ComputeResource hierarchy.
A folder for Network, DistributedVirtualSwitch, and DistributedVirtualPortgroup objects.
A folder for Datastore objects.
In a large deployment, the nested structure allows you to organize the objects in the datacenter into an easily manageable structure by using multiple folders and datacenters.
For a standalone ESX/ESXi system, only a single datacenter is supported, and the Folder managed entity does not support creating additional Folder objects or Datacenter objects.
50 VMware, Inc.

ESXi Inventory Hierarchy

When you access an ESXi host directly, rather than accessing the host through a vCenter Server system, the hierarchy shown in Figure 4-2 allows you to traverse the inventory.
Figure 4-2. ESXi Inventory Hierarchy
Chapter 4 Datacenter Inventory

Accessing Inventory Objects

To retrieve information from an inventory object, you start with ServiceInstance, the root object of the inventory. You access an object using a TraversalSpec in conjunction with a property collector, using the properties that identify an object’s position in the hierarchy.
Every managed entity has a parent property that identifies its relative position in the inventory hierarchy.
The Folder managed object has a childEntity property that identifies objects in a folder instance.
Figure 4-3 shows the childEntity and folder properties that define the default objects in the inventory of a
standalone ESX/ESXi system. The inventory begins with the ServiceContent.rootFolder property. The rootFolder has a childEntity that consists of a managed object reference to a Datacenter managed object.
VMware, Inc. 51
vSphere Web Services SDK Programming Guide
Figure 4-3. Instance Diagram of Root Folders in an Inventory

Creating Inventory Objects

The Folder managed entity provides methods for creating instances of the following managed entities.
Datacenter DistributedVirtualSwitch VirtualMachine Cluster Folder
When you create these objects, they are automatically created in the folder you invoked the creation method from.
While some managed entities are created through a method on the Folder managed entity, other managed entities are instantiated directly. For example, the HostDatastoreSystem has methods for creating datastores such as CreateNasDatastore and CreateVmfsDatastore.
IMPORTANT When you create an inventory object, you must stay within the bounds of the host’s capabilities, accessible through the HostSystem.capability property, which is a HostCapability data object. For example, a HostCapability object might have the maxSupportedVMs property specified.

Privileges Required for Inventory Management

Navigating the inventory requires a user account that can connect to the server and obtain a valid session. The user identity associated with the session is called a principal. When a client application attempts to access an object in the inventory, the server checks the permission object or objects and compares the permissions with the principal’s privileges.
52 VMware, Inc.
Chapter 4 Datacenter Inventory
For example, creating a virtual machine requires that the principal associated with the session have the following privileges:
The VirtualMachine.Inventory.Create privilege on the folder in which to create the virtual machine.
The Resource.AssignVMToPool privilege on the resource pool from which the virtual machine obtains
its allocation of CPU and memory resources.
Reading the perfCounter property of the PerformanceManager managed object requires the System.View privilege on the root folder.
I
MPORTANT Some privileges are specific to objects on vCenter Server or specific to ESX/ESXi. For example,
the Alarm.Create privilege associated with AlarmManager is available only through vCenter Server systems.
See Chapter 6, “Authentication and Authorization,” on page 81 for more information on authentication, authorization, roles, and user identity.

Privileges

A privilege is a system-defined requirement associated with a VMware vSphere managed object. Privileges are static and do not change for a version of a product. Privileges for vSphere components are defined as follows:
<group>[.<group>].privilege
For example:
Datacenter.Create Host.Config.Connection Host.Config.Snmp

Permissions

Permissions are the associations of roles with privileges on a specified managed entity. You use permissions to specify which users can access which managed entity.
A child entity inherits the permissions of its parent if the parent’s propagate property is set to true. A permission that is set directly on a child overrides the permission in the parent. To grant permission to all child entities of a Datacenter object, assign permissions to the Datacenter object and set the Permission object’s propagate property to true.
Figure 4-4 shows that users root and vpxuser both have permissions on the rootFolder of the inventory.
The vpxuser is the account created on a host by the vCenter Server system when that host is added to the vCenter Server system. The vCenter Server needs access to the inventory objects of the host systems that it manages, so the vpxuser account is granted privileges to the rootFolder of each host.
IMPORTANT See Chapter 6, “Authentication and Authorization,” on page 81 for a detailed discussion of privileges, permissions, and user management.
VMware, Inc. 53
vSphere Web Services SDK Programming Guide
Figure 4-4. Inventory and Permissions

Managed and Standalone ESX/ESXi Hosts

You can run ESX/ESXi as a managed or standalone ESX/ESXi host.
Standalone ESX/ESXi hosts are standalone hosts with limited capabilities. The inventory of a standalone
host can support multiple virtual machines and multiple resource pools, but it contains a single default datacenter and a single root folder. The default datacenter and root folder are not visible in the vSphere Client, but they exist in the inventory of a standalone host and they are visible in the MOB.
Managed ESX/ESXi hosts have been added to the vCenter Server inventory. Available features depend on
the licenses available for that host. For example, you can configure two or more hosts for VMware DRS resource management or VMware HA failover protection.
54 VMware, Inc.
Chapter 4 Datacenter Inventory
Tab le 4 -1 summarizes the differences between the number of objects that an inventory can contain. See also Figure 4-2, “ESXi Inventory Hierarchy,” on page 51 and Figure 4-1, “vCenter Server Inventory Hierarchy,” on
page 50.
Tabl e 4-1 . Standalone ESX/ESXi and vCenter Server Inventories
ManagedEntity Subtype ESX/ESXi Inventory vCenter Server Inventory
ClusterComputeResource None. Multiple instances supported.
ComputeResource Exactly one only. Multiple instances supported.
Datacenter Exactly one only. Cannot be destroyed.
Tra ns par en t.
Datastore Multiple instances supported. Multiple instances supported.
DistributedVirtualSwitch Multiple instances supported. Multiple instances supported.
Folder Exactly one only. Cannot be destroyed.
Tra ns par en t.
HostSystem Exactly one only. Multiple instances supported.
Network Multiple instances supported. Multiple instances supported.
ResourcePool Multiple instances supported. Multiple instances supported.
VirtualApp None. Multiple instances supported.
VirtualMachine Multiple instances supported. Multiple instances supported.
Multiple instances supported.
Multiple instances supported.
VMware, Inc. 55
vSphere Web Services SDK Programming Guide
56 VMware, Inc.
5

Property Collector

vSphere servers provide the PropertyCollector service for accessing data and monitoring changes. Use the PropertyCollector to obtain references to managed objects, to obtain values of managed object properties,
and to monitor and retrieve modified property values.
This chapter includes the following topics:
“Introduction to the PropertyCollector” on page 57
“vSphere Data Objects for Property Collection” on page 58
“vSphere Methods for Property Collection” on page 58
“PropertyCollector Example (RetrievePropertiesEx)” on page 59
“Inventory Traversal” on page 66
“Client Data Synchronization (WaitForUpdatesEx)” on page 77
“Server Data Transmission” on page 79
“PropertyCollector Performance” on page 79
“SearchIndex” on page 79
5

Introduction to the PropertyCollector

The PropertyCollector service interface provides a way to monitor and retrieve information about managed objects, such as whether a virtual machine is powered on or whether a host in a cluster is offline.
The PropertyCollector uses one or more filters to determine the scope of collection and it has methods to retrieve data. A filter uses a set of data objects that specify the following information:
Starting point for inventory traversal during the collection operation.
Inventory traversal path.
Objects and properties from which data will be collected.
A vSphere server creates a default PropertyCollector for every session, and allows you to create multiple, additional PropertyCollector objects. Create additional PropertyCollector objects, using one per thread, to perform mutually independent collection operations.
VMware, Inc. 57
vSphere Web Services SDK Programming Guide

Data Retrieval

There are two ways to retrieve data:
Property retrieval as a single operation uses the RetrievePropertiesEx and
ContinueRetrievePropertiesEx methods. These methods perform a single collection operation.
Incremental property retrieval, also referred to as property monitoring, uses the WaitForUpdatesEx
method. The initial call to this method retrieves a baseline set of managed object property values. Subsequent calls retrieve changes in property values since the last retrieval. Use WaitForUpdatesEx to monitor changes to the inventory or any managed object properties.
N
OTE The PropertyCollector does not guarantee the order of data that it returns in response to a request
for data.

Inventory Traversal and Object Selection

PropertyCollector filter properties identify object properties and paths that define inventory traversal. For example, you can retrieve the properties for a VirtualMachine object and specify a traversal path using the VirtualMachine.network property to obtain the properties for the associated Network objects.
You can use vSphere view objects (for example, ContainerView) in filters to simplify traversal specification. A view maintains a subset of inventory objects, so if there is a change in the inventory hierarchy, you do not have to recreate the view. Use a view to specify a set of objects that the PropertyCollector can use for data collection.
For information about the vSphere inventory, see Chapter 4, “Datacenter Inventory,” on page 49.

vSphere Data Objects for Property Collection

Tab le 5 -1 provides an overview of the PropertyCollector data objects. For more detailed descriptions, see
the vSphere API Reference.
Tabl e 5-1 . PropertyCollector Data Objects
Data Object Description
PropertyFilterSpec Provides access to object and property selection data. A PropertyFilterSpec must
have at least one ObjectSpec and one PropertySpec.
ObjectSpec Identifies the starting object for property collection. An ObjectSpec also identifies
TraversalSpec Identifies the type of object for property collection. It also provides one or more paths
SelectionSpec Acts as a placeholder reference to a TraversalSpec.
PropertySpec Identifies properties for collection.
View objects Identify a subset of the vSphere inventory objects.
additional objects for collection.
for inventory traversal.

vSphere Methods for Property Collection

The PropertyCollector supports the following approaches to obtaining objects and properties from the server:
If your client application does not keep a synchronized representation of server state, use the
RetrievePropertiesEx method. RetrievePropertiesEx instantiates a filter, collects the specified objects and properties, and returns the data to your client application as an ObjectContent data object. The server does not add the filter to the PropertyCollector.filter array. The server destroys the filter after returning the results to your client.
If your application maintains a synchronized representation of server state, use the CreateFilter and
WaitForUpdatesEx methods. WaitForUpdatesEx returns descriptions of property changes, organized
by the filter that identified the properties.
58 VMware, Inc.
Chapter 5 Property Collector
In either case, you create a PropertyFilterSpec data object to specify the objects and properties you want to retrieve from the server.
Tab le 5 -2 shows the PropertyCollector methods organized by the context in which you use them. For more
information about these methods, see the vSphere API Reference.
Tabl e 5-2 . PropertyCollector Methods
Method Context Method Description
Monitor properties using different filters
Single collection operation
Incremental collection or monitoring operation
General CreateFilter Creates a new instance of a PropertyFilter managed
CreatePropertyCollector Creates a new PropertyCollector object to monitor
properties using different filters. The vSphere server handles requests for a PropertyCollector instance independently of any other instances of the
PropertyCollector on the server.
DestroyPropertyCollector Destroys an instance of a PropertyCollector that was
created by a call to CreatePropertyCollector from your client application.
RetrievePropertiesEx Retrieves property data for the specified managed objects.
ContinueRetrievePropertiesEx Retrieves additional property data for an operation
started by RetrievePropertiesEx.
CancelRetrievePropertiesEx Cancels a RetrievePropertiesEx or
ContinueRetrievePropertiesEx operation.
WaitForUpdatesEx Retrieves changes to property data since the last
WaitForUpdatesEx cycle. WaitForUpdatesEx blocks
until it can satisfy the request or until the request times out. WaitForUpdatesEx supports chunked data transmission (see “Server Data Transmission” on page 79).
CancelWaitForUpdatesEx Cancels a WaitForUpdatesEx operation.
object.

PropertyCollector Example (RetrievePropertiesEx)

Example 5-1 is a simple PropertyCollector example written in Java. The example uses a ContainerView
for efficient access to the inventory and a PropertyFilterSpec that contains one ObjectSpec, one TraversalSpec, and one PropertySpec. The program performs the following tasks:
Accepts command line arguments for the vSphere server name (DN S na me o r IP a ddr ess ), u ser nam e, a nd
password.
Connects to a vSphere server.
Uses a ContainerView to create a subset of the inventory; the subset contains only virtual machines.
Uses the RetrievePropertiesEx method for a single retrieval operation.
Collects the names of all of the virtual machines in the inventory and prints the names using the standard
output stream.
The following procedure uses code fragments from Example 5-1. The complete example includes server connection code; this procedure only describes the task of using the PropertyCollector. For a description of server connection, see “To build a simple vSphere client application” on page 39.
VMware, Inc. 59
vSphere Web Services SDK Programming Guide
To use the PropertyCollector for a single retrieval operation
1 Get references to the ViewManager and the PropertyCollector.
In the example, sContent is the variable for the ServiceContent data object. sContent provides the methods to retrieve the managed object references to the vSphere services.
ManagedObjectReference viewMgrRef = sContent.getViewManager(); ManagedObjectReference propColl = sContent.getPropertyCollector();
2 Create a container view for virtual machines.
methods is the variable for the VimPortType object. VimPortType defines the Java methods that correspond to the vSphere API methods. The createContainerView parameters container (the inventory root folder, returned by the method sContent.getRootFolder) and type (“Virtual Machine”) direct the ViewManager to select virtual machines, starting at the root folder. The value true for the recursive parameter extends the selection beyond the root folder so that the ViewManager will follow child folder paths to add virtual machines to the view. The container view provides references to all virtual machines in the inventory.
List<String> vmList = new ArrayList<String>(); vmList.add("VirtualMachine");
ManagedObjectReference cViewRef = methods.createContainerView(viewMgrRef,
sContent.getRootFolder(), vmList, true );
3 Create an object specification to define the starting point for inventory navigation.
The ObjectSpec.obj property identifies the starting object (the container view). This example collects only virtual machine data, so the skip property is set to true to ignore the container view itself during collection.
ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(cViewRef); oSpec.setSkip(true);
4 Create a traversal specification to identify the path for collection.
The TraversalSpec properties type and path determine path traversal. TraversalSpec.type identifies an object type. TraversalSpec.path identifies a property in the type object. The PropertyCollector uses the path object to select additional objects.
This example uses a single TraversalSpec to walk the list of virtual machines that are available through the container view. The following code fragment specifies the ContainerView object for the
TraversalSpec.type property and the view property in the ContainerView for the TraversalSpec.path property. The skip property is set to false, so the PropertyCollector will collect data from the path objects (the virtual machines in the container view).
TraversalSpec tSpec = new TraversalSpec(); tSpec.setName("traverseEntities"); tSpec.setPath("view"); tSpec.setSkip(false); tSpec.setType("ContainerView");
5Add the TraversalSpec to the ObjectSpec.selectSet array.
oSpec.getSelectSet().add(tSpec);
6 Identify the properties to be retrieved.
The example program creates a PropertySpec data object to specify the properties to be collected. The type property is set to VirtualMachine to match the object selections in the container view. The pathSet property identifies one or more properties in the type object.
60 VMware, Inc.
Chapter 5 Property Collector
This example specifies the VirtualMachine.name property.
PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); pSpec.getPathSet().add("name");
7 Add the object and property specifications to the property filter specification.
A PropertyFilterSpec must have at least one ObjectSpec and one PropertySpec.
PropertyFilterSpec fSpec = new PropertyFilterSpec(); fSpec.getObjectSet().add(oSpec); fSpec.getPropSet().add(pSpec);
8 Create a list for the filters and add the spec to it.
List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>(); fSpecList.add(fSpec);
9 Retrieve the data.
To invoke a single property collection operation, call the RetrievePropertiesEx method. The example application passes the populated PropertyFilterSpec and an empty options structure to the method. The default for the RetrieveOptions.maxObjects specifies that no maximum for the number of objects that can be returned is set. The PropertyCollector can impose a maximum. If the number of collected objects is greater than the maximum, the PropertyCollector returns a token value in the
RetrieveResult data object and this token is used to retrieve the remaining properties using the ContinueRetrievePropertiesEx API method. For more information, see “Server Data Transmission”
on page 79.
RetrieveOptions ro = new RetrieveOptions(); RetrieveResult props = methods.retrievePropertiesEx(propColl,fSpecList,ro);
10 Print the virtual machine names.
The following code fragment walks the list of ObjectContent objects returned in the RetrieveResult object. For each object (ObjectContent), the inner loop prints the name-value pairs.
if (props != null) {
for (ObjectContent oc : props.getObjects()) { String vmName = null; String path = null; List<DynamicProperty> dps = oc.getPropSet();
if (dps != null) {
for (DynamicProperty dp : dps) { vmName = (String) dp.getVal(); path = dp.getName();
System.out.println(path + " = " + vmName); } } } } }//end collectProperties()
VMware, Inc. 61
vSphere Web Services SDK Programming Guide
PropertyFilterSpec
objectSet
propSet
ObjectSpec
obj
selectSet
[...]
[...]
type=”VirtualMachine”
pathSet=”name”
PropertySpec
[...]
TraversalSpec
path=”view”
type=“ContainerView”
[...]
ContainerView
container
type =“VirtualMachine”
view [ ]
[...]
Root
Folder
Server Inventory
Virtual
Machine
Folder
Virtual
Machine
Folder
Virtual
Machine
name
Virtual
Machine
name
Figure 5-1 shows the objects used in Example 5-1. The figure represents properties that identify inventory elements
directly or indirectly. It does not show all the properties for the different objects.
Figure 5-1. Property Filter Specification
Example 5-1. Simple PropertyCollector Example (Java)
import com.vmware.vim25.*;
import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.SOAPFaultException;
// PropertyCollector example // command line input: server name, user name, password
public class PCollector {
private static void collectProperties(VimPortType methods,
ServiceContent sContent) throws Exception {
// Get references to the ViewManager and PropertyCollector ManagedObjectReference viewMgrRef = sContent.getViewManager(); ManagedObjectReference propColl = sContent.getPropertyCollector();
// use a container view for virtual machines to define the traversal // - invoke the VimPortType method createContainerView (corresponds // to the ViewManager method) - pass the ViewManager MOR and // the other parameters required for the method invocation // - createContainerView takes a string[] for the type parameter; // declare an arraylist and add the type string to it List<String> vmList = new ArrayList<String>(); vmList.add("VirtualMachine");
62 VMware, Inc.
ManagedObjectReference cViewRef = methods.createContainerView(viewMgrRef,
sContent.getRootFolder(), vmList, true);
// create an object spec to define the beginning of the traversal; // container view is the root object for this traversal ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(cViewRef); oSpec.setSkip(true);
// create a traversal spec to select all objects in the view TraversalSpec tSpec = new TraversalSpec(); tSpec.setName("traverseEntities"); tSpec.setPath("view"); tSpec.setSkip(false); tSpec.setType("ContainerView");
// add the traversal spec to the object spec; // the accessor method (getSelectSet) returns a reference // to the mapped XML representation of the list; using this // reference to add the spec will update the list oSpec.getSelectSet().add(tSpec);
// specify the property for retrieval (virtual machine name) PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); pSpec.getPathSet().add("name");
Chapter 5 Property Collector
// create a PropertyFilterSpec and add the object and // property specs to it; use the getter method to reference // the mapped XML representation of the lists and add the specs // directly to the list PropertyFilterSpec fSpec = new PropertyFilterSpec(); fSpec.getObjectSet().add(oSpec); fSpec.getPropSet().add(pSpec);
// Create a list for the filters and add the spec to it List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>(); fSpecList.add(fSpec);
// get the data from the server RetrieveOptions ro = new RetrieveOptions(); RetrieveResult props = methods.retrievePropertiesEx(propColl,fSpecList,ro);
// go through the returned list and print out the data if (props != null) {
for (ObjectContent oc : props.getObjects()) { String vmName = null; String path = null; List<DynamicProperty> dps = oc.getPropSet();
if (dps != null) {
for (DynamicProperty dp : dps) { vmName = (String) dp.getVal(); path = dp.getName();
System.out.println(path + " = " + vmName); }
}
} } }//end collectProperties()
VMware, Inc. 63
vSphere Web Services SDK Programming Guide
// Authentication is handled by using a TrustManager and supplying
// a host name verifier method. (The host name verifier is declared
// in the main function.)
//
// For the purposes of this example, this TrustManager implementation
// will accept all certificates. This is only appropriate for
// a development environment. Production code should implement certificate support.
private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
String authType) throws java.security.cert.CertificateException { return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
String authType) throws java.security.cert.CertificateException { return;
}
}
public static void main(String [] args) throws Exception {
// arglist variables
String serverName = args[0];
String userName = args[1];
String password = args[2];
String url = "https://"+serverName+"/sdk/vimService";
// Variables of the following types for access to the API methods
// and to the vSphere inventory.
// -- ManagedObjectReference for the ServiceInstance on the Server
// -- VimService for access to the vSphere Web service
// -- VimPortType for access to methods
// -- ServiceContent for access to managed object services
ManagedObjectReference SVC_INST_REF = new ManagedObjectReference();
VimService vimService;
VimPortType vimPort;
ServiceContent serviceContent;
// Declare a host name verifier that will automatically enable
// the connection. The host name verifier is invoked during
// the SSL handshake.
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true; } };
// Create the trust manager. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm;
64 VMware, Inc.
Chapter 5 Property Collector
// Create the SSL context javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
// Create the session context javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
// Initialize the contexts; the session context takes the trust manager. sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null);
// Use the default socket factory to create the socket for the secure connection javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set the default host name verifier to enable the connection. HttpsURLConnection.setDefaultHostnameVerifier(hv);
// Set up the manufactured managed object reference for the ServiceInstance SVC_INST_REF.setType("ServiceInstance"); SVC_INST_REF.setValue("ServiceInstance");
// Create a VimService object to obtain a VimPort binding provider. // The BindingProvider provides access to the protocol fields // in request/response messages. Retrieve the request context // which will be used for processing message requests. vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
// Store the Server URL in the request context and specify true // to maintain the connection between the client and server. // The client API will include the Server's HTTP cookie in its // requests to maintain the session. If you do not set this to true, // the Server will start a new session with each request. ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
// Retrieve the ServiceContent object and login serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(),
userName,
password,
null);
// retrieve data collectProperties( vimPort, serviceContent );
// close the connection vimPort.logout(serviceContent.getSessionManager());
} }
VMware, Inc. 65
vSphere Web Services SDK Programming Guide

Inventory Traversal

Example 5-1 uses a ContainerView to specify the objects that start the collection process. This is the simplest
way to set up a filter, using a single reference to a view to provide the PropertyCollector with access to a set of objects. To select objects from the inventory, a filter includes TraversalSpec and possibly SelectionSpec objects. Use these objects to make object selections based on the references in a view, and to extend inventory traversal beyond those objects (or beyond the object specified in ObjectSpec.obj).

TraversalSpec Traversal

Use a TraversalSpec object to identify a managed object type and a traversal property in that type. TraversalSpec contains the following properties:
type – identifies an inventory object type.
path – specifies a managed object reference property in the type object. This property provides the
traversal path extending from this object.
selectSet – specifies an optional list of selection objects for additonal object traversal paths. The
PropertyCollector applies the TraversalSpec objects in the selectSet array to the result of the traversal (the target of TraversalSpec.path). The selectSet array can also contain SelectionSpec objects; a SelectionSpec is a reference to a TraversalSpec. See “SelectionSpec Traversal” on page 72.
skip – indicates whether to collect properties for the path object.
During inventory traversal, the PropertyCollector applies the PropertySpec object or objects (PropertyFilterSpec.propSet) to objects. Inventory traversal begins with the object identified by ObjectSpec.obj and continues by following TraversalSpec paths. If PropertySpec.type matches the current object type, and the skip property is false, the PropertyCollector sends the PropertySpec.pathSet properties to your client.
Figure 5-2 is a representation of a PropertyFilterSpec that defines traversal of VirtualMachine objects.
The filter uses a ContainerView as a starting point. The TraversalSpec for the ContainerView specifies the view property for access to the view’s virtual machines. The figure shows TraversalSpec objects that extend navigation from a VirtualMachine object to the associated Network and ResourcePool objects. The PropertyCollector applies these TraversalSpec objects to each of the VirtualMachine objects in the view list. The figure also shows the PropertySpec objects for collecting data from VirtualMachine, Network, and ResourcePool objects.
66 VMware, Inc.
Figure 5-2. Inventory Navigation
PropertyFilterSpec
objectSet[ ]
propSet[ ]
ObjectSpec
selectSet[ ]
[...]
[...]
obj=”VirtualMachine”
pathSet[ ]=”name”
PropertySpec
obj=”Network”
pathSet[ ]=”summary.accessible”
PropertySpec
[...]
obj=”ResourcePool”
pathSet[ ]=“runtime.cpu.maxUsage”
“runtime.memory.maxUsage”
PropertySpec
[...]
[VirtualMachine folder]
[Network folder]
network
name
resourcePool
[...]
summary
Network
[...]
runtime
[ComputeResource folder]
ResourcePool
[...]
TraversalSpec
path=”view”
selectSet[ ]
[...]
Server Inventory
VirtualMachine
type=“ContainerView”
TraversalSpec
path=”resourcePool”
[...]
type=”VirtualMachine”
TraversalSpec
path=”network”
[...]
type=”VirtualMachine”
[...]
Chapter 5 Property Collector
Example 5-2 shows a Java code fragment, based on Example 5-1, “Simple PropertyCollector Example (Java),”
on page 62, that implements the inventory traversal shown in Figure 5-2.
To define inventory traversal
1 Create a ContainerView for virtual machines.
2 Create an ObjectSpec that uses the container view as the collection starting point.
3 Create a TraversalSpec be applied to the ContainerView to select VirtualMachine objects.
VMware, Inc. 67
vSphere Web Services SDK Programming Guide
4 Create additional TraversalSpec objects to select additional objects.
The SelectSet list for the container view TraversalSpec has two TraversalSpec objects. Both specify a VirtualMachine object context. One object uses the network property to extend traversal to the
Network managed object. The other uses the resourcePool property to extend traversal to the ResourcePool managed object.
5Create PropertySpec objects to retrieve VirtualMachine, Network, and ResourcePool properties.
To retrieve properties that are embedded in data objects, the PropertySpec.PathSet property uses dot notation to specify the property paths.
Example 5-2. Inventory Traversal
import com.vmware.vim25.*;
import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.SOAPFaultException;
// PropertyCollector example // command line input: server name, user name, password
public class PCollector_traversal {
private static void collectProperties(VimPortType methods,
ServiceContent sContent) throws Exception {
// Get references to the ViewManager and PropertyCollector ManagedObjectReference viewMgrRef = sContent.getViewManager(); ManagedObjectReference propColl = sContent.getPropertyCollector();
// use a container view for virtual machines to define the traversal // - invoke the VimPortType method createContainerView (corresponds // to the ViewManager method) - pass the ViewManager MOR and // the other parameters required for the method invocation // (use a List<String> for the type parameter's string[]) List<String> vmList = new ArrayList<String>(); vmList.add("VirtualMachine");
ManagedObjectReference cViewRef =
methods.createContainerView(viewMgrRef,
sContent.getRootFolder(),
vmList,
true);
// create an object spec to define the beginning of the traversal; // container view is the root object for this traversal ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(cViewRef); oSpec.setSkip(true);
// create a traversal spec to select all objects in the view TraversalSpec tSpec = new TraversalSpec(); tSpec.setName("traverseEntities"); tSpec.setPath("view"); tSpec.setSkip(false); tSpec.setType("ContainerView");
// add the traversal spec to the object spec; // the accessor method (getSelectSet) returns a reference // to the mapped XML representation of the list; using this // reference to add the spec will update the selectSet list oSpec.getSelectSet().add(tSpec);
68 VMware, Inc.
// extend from virtual machine to network TraversalSpec tSpecVmN = new TraversalSpec(); tSpecVmN.setType("VirtualMachine"); tSpecVmN.setPath("network"); tSpecVmN.setSkip(false);
// extend from virtual machine to resourcepool TraversalSpec tSpecVmRp = new TraversalSpec(); tSpecVmRp.setType("VirtualMachine"); tSpecVmRp.setPath("resourcePool"); tSpecVmRp.setSkip(false);
// add the network and resource pool traversal specs // to the virtual machine traversal; // the accessor method (getSelectSet) returns a reference // to the mapped XML representation of the list; using this // reference to add the spec will update the selectSet list tSpec.getSelectSet().add(tSpecVmN); tSpec.getSelectSet().add(tSpecVmRp);
// specify the properties for retrieval // (virtual machine name, network summary accessible, rp runtime props); // the accessor method (getPathSet) returns a reference to the mapped // XML representation of the list; using this reference to add the // property names will update the pathSet list PropertySpec pSpec = new PropertySpec(); pSpec.setType("VirtualMachine"); pSpec.getPathSet().add("name");
Chapter 5 Property Collector
PropertySpec pSpecNs = new PropertySpec(); pSpecNs.setType("Network"); pSpecNs.getPathSet().add("summary.accessible");
PropertySpec pSpecRPr = new PropertySpec(); pSpecRPr.setType("ResourcePool"); pSpecRPr.getPathSet().add("runtime.cpu.maxUsage"); pSpecRPr.getPathSet().add("runtime.memory.maxUsage"); pSpecRPr.getPathSet().add("runtime.overallStatus");
// create a PropertyFilterSpec and add the object and // property specs to it; use the getter methods to reference // the mapped XML representation of the lists and add the specs // directly to the objectSet and propSet lists PropertyFilterSpec fSpec = new PropertyFilterSpec(); fSpec.getObjectSet().add(oSpec); fSpec.getPropSet().add(pSpec); fSpec.getPropSet().add(pSpecNs); fSpec.getPropSet().add(pSpecRPr);
// Create a list for the filters and add the spec to it List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>(); fSpecList.add(fSpec);
// get the data from the server RetrieveOptions ro = new RetrieveOptions(); RetrieveResult props = methods.retrievePropertiesEx(propColl,fSpecList,ro);
// go through the returned list and print out the data if (props != null) {
for (ObjectContent oc : props.getObjects()) {
String value = null;
String path = null;
List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) {
for (DynamicProperty dp : dps) {
path = dp.getName(); if (path.equals("name")) {
VMware, Inc. 69
vSphere Web Services SDK Programming Guide
value = (String) dp.getVal();
} else if (path.equals("summary.accessible")) {
// summary.accessible is a boolean
value = String.valueOf( dp.getVal() );
} else if (path.equals("runtime.cpu.maxUsage")) {
// runtime.cpu.maxUsage is an xsd:long
value = String.valueOf( dp.getVal() );
} else if (path.equals("runtime.memory.maxUsage")) {
// runtime.memory.maxUsage is an xsd:long
value = String.valueOf( dp.getVal() );
} else if (path.equals("runtime.overallStatus")) {
// runtime.overallStatus is a ManagedEntityStatus enum
value = String.valueOf( dp.getVal() );
}
System.out.println(path + " = " + value);
} }
} } }//end collectProperties()
// Authentication is handled by using a TrustManager and supplying // a host name verifier method. (The host name verifier is declared // in the main function.) // // For the purposes of this example, this TrustManager implementation // will accept all certificates. This is only appropriate for // a development environment. Production code should implement certificate support. private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null; }
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true; }
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true; }
public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return; }
public void checkClientTrusted(java.security.cert.X509Certificate[] certs,
String authType)
throws java.security.cert.CertificateException {
return; } }
70 VMware, Inc.
public static void main(String [] args) throws Exception {
// arglist variables String serverName = args[0]; String userName = args[1]; String password = args[2]; String url = "https://"+serverName+"/sdk/vimService";
// Variables of the following types for access to the API methods // and to the vSphere inventory. // -- ManagedObjectReference for the ServiceInstance on the Server // -- VimService for access to the vSphere Web service // -- VimPortType for access to methods // -- ServiceContent for access to managed object services ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); VimService vimService; VimPortType vimPort; ServiceContent serviceContent;
// Declare a host name verifier that will automatically enable // the connection. The host name verifier is invoked during // the SSL handshake. HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
};
Chapter 5 Property Collector
// Create the trust manager. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm;
// Create the SSL context javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
// Create the session context javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
// Initialize the contexts; the session context takes the trust manager. sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null);
// Use the default socket factory to create the socket for the secure connection javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set the default host name verifier to enable the connection. HttpsURLConnection.setDefaultHostnameVerifier(hv);
// Set up the manufactured managed object reference for the ServiceInstance SVC_INST_REF.setType("ServiceInstance"); SVC_INST_REF.setValue("ServiceInstance");
// Create a VimService object to obtain a VimPort binding provider. // The BindingProvider provides access to the protocol fields // in request/response messages. Retrieve the request context // which will be used for processing message requests. vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
// Store the Server URL in the request context and specify true // to maintain the connection between the client and server. // The client API will include the Server's HTTP cookie in its // requests to maintain the session. If you do not set this to true, // the Server will start a new session with each request. ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
VMware, Inc. 71
vSphere Web Services SDK Programming Guide
PropertyFilterSpec
objectSet[ ]
ObjectSpec
selectSet[ ]
[...]
[...]
TraversalSpec
path=”vm”
selectSet[ ]
ObjectSpec
selectSet[ ]
[...]
TraversalSpec
path=”vm”
selectSet[ ]
type=“DataStore”
ObjectSpec
selectSet[ ]
[...]
TraversalSpec
path=”resourcePool”
name=”vmTraversal”
type=“VirtualMachine”
name=”vmTraversal”
SelectionSpec
name=”vmTraversal”
SelectionSpec
type=“Network”
// Retrieve the ServiceContent object and login serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF);
vimPort.login(serviceContent.getSessionManager(),
userName,
password,
null);
// retrieve data collectProperties( vimPort, serviceContent );
// close the connection vimPort.logout(serviceContent.getSessionManager());
} }

SelectionSpec Traversal

The selectSet array in ObjectSpec and TraversalSpec objects can include TraversalSpec objects and SelectionSpec objects. SelectionSpec is the base class for TraversalSpec objects. SelectionSpec defines the name property. You can use a SelectionSpec object in a selectSet array as a reference to a named TraversalSpec object. By using SelectionSpec references, you can reuse a TraversalSpec and you can
define recursive traversal.
Simple Reference SelectionSpec
Use SelectionSpec references to avoid writing duplicate TraversalSpec declarations. The TraversalSpec identified in a SelectionSpec reference must be within the same PropertyFilterSpec. Figure 5-3 shows the use of SelectionSpec references to a virtual machine TraversalSpec. The SelectionSpec references are associated with Network and Datastore traversals.
Figure 5-3. SelectionSpec Reference
72 VMware, Inc.
Chapter 5 Property Collector
TraversalSpec
path=”childEntity”
selectSet
name=”folderTraversal”
SelectionSpec
type=“Folder”
name=”folderTraversal”
If the ObjectSpec.selectSet array contains a SelectionSpec, the referenced TraversalSpec must identify the same object type. TraversalSpec.type must match the type of the object specified in
ObjectSpec.obj. The PropertyCollector applies the TraversalSpec to the object and use the TraversalSpec.path property to extend its traversal.
Recursive Traversal
Use a SelectionSpec to apply a TraversalSpec to the results of its own traversal. To use a recursive filter construction, create a SelectionSpec that specifies the name of a TraversalSpec and add it to the named TraversalSpec selection set. The recursive construction extends inventory traversal beyond the paths directly represented by TraversalSpec objects.
You can use recursive traversal on any inventory objects that can be nested. See “Inventory Hierarchies and
ServiceInstance” on page 50 for a general representation of the structure of an inventory. For example, on a
vCenter Server, folders can nest to arbitrary depths. To describe a traversal path through a succession of folders, you can add a SelectionSpec to the Folder TraversalSpec. The SelectionSpec must reference the TraversalSpec. Figure 5-4 shows a representation of a TraversalSpec and its associated SelectionSpec for nested folder traversal.
Figure 5-4. Recursive TraversalSpec and SelectionSpec
Example 5-3, “Nested Folder Traversal,” on page 74 shows a Java code fragment that creates a recursive filter
for nested folder traversal.
To define recursive inventory traversal
1Use the SearchIndex managed object to retrieve the managed object reference for the top-level virtual
machine folder.
This folder is used as the beginning of the inventory traversal. For more information see “SearchIndex” on page 79.
2 Create an ObjectSpec object that references the top-level virtual machine folder.
3 Create a SelectionSpec object that references the Folder TraversalSpec by name.
4 Create a named TraversalSpec for Folder objects.
The TraversalSpec.path property identifies the Folder.childEntity property for traversal to any child objects.
5Add the SelectionSpec to the TraversalSpec to create the recursive filter.
6Add the TraversalSpec to the ObjectSpec.
7 Create a PropertySpec for the Folder name.
8 Add the object and property specifications to the PropertyFilterSpec.
9Call the RetrievePropertiesEx method.
VMware, Inc. 73
vSphere Web Services SDK Programming Guide
Example 5-3. Nested Folder Traversal
import com.vmware.vim25.*;
import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; import javax.xml.ws.BindingProvider; import javax.xml.ws.soap.SOAPFaultException;
// PropertyCollector example // command line input: server name, user name, password
public class nestedTraversal {
private static void collectProperties(VimPortType methods,
ServiceContent sContent) throws Exception {
// Get reference to the PropertyCollector
ManagedObjectReference propColl = sContent.getPropertyCollector();
// get the top-level vm folder mor ManagedObjectReference sIndex = sContent.getSearchIndex();
ManagedObjectReference rootVmFolder =
methods.findByInventoryPath(sIndex,"datacenter1/vm");
// create an object spec to define the beginning of the traversal; // root vm folder is the root object for this traversal ObjectSpec oSpec = new ObjectSpec(); oSpec.setObj(rootVmFolder); oSpec.setSkip(true);
// folder traversal reference SelectionSpec sSpecF = new SelectionSpec(); sSpecF.setName("traverseFolder");
// create a folder traversal spec to select childEntity TraversalSpec tSpecF = new TraversalSpec(); tSpecF.setType("Folder"); tSpecF.setPath("childEntity"); tSpecF.setSkip(false); tSpecF.setName("traverseFolder");
// use the SelectionSpec as a reflexive spec for the folder traversal; // the accessor method (getSelectSet) returns a reference to the // mapped XML representation of the list; using this reference // to add the spec will update the list tSpecF.getSelectSet().add(sSpecF);
// add folder traversal to object spec oSpec.getSelectSet().add(tSpecF);
// specify the property for retrieval (folder name) PropertySpec pSpec = new PropertySpec(); pSpec.setType("Folder"); pSpec.getPathSet().add("name");
// create a PropertyFilterSpec and add the object and // property specs to it; use the getter method to reference // the mapped XML representation of the lists and add the specs // directly to the lists PropertyFilterSpec fSpec = new PropertyFilterSpec(); fSpec.getObjectSet().add(oSpec); fSpec.getPropSet().add(pSpec);
74 VMware, Inc.
Chapter 5 Property Collector
// Create a list for the filter and add the spec to it List<PropertyFilterSpec> fSpecList = new ArrayList<PropertyFilterSpec>(); fSpecList.add(fSpec);
// get the data from the server RetrieveOptions ro = new RetrieveOptions(); RetrieveResult props = methods.retrievePropertiesEx(propColl,fSpecList,ro);
// go through the returned list and print out the data if (props != null) {
for (ObjectContent oc : props.getObjects()) {
String folderName = null;
String path = null;
List<DynamicProperty> dps = oc.getPropSet(); if (dps != null) {
for (DynamicProperty dp : dps) {
folderName = (String) dp.getVal();
path = dp.getName();
System.out.println(path + " = " + folderName);
}
} } }
}//end collectProperties()
// Authentication is handled by using a TrustManager and supplying // a host name verifier method. (The host name verifier is declared // in the main function.) // // For the purposes of this example, this TrustManager implementation // will accept all certificates. This is only appropriate for // a development environment. Production code should implement certificate support. private static class TrustAllTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { return true; }
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { return true; }
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; }
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; }
}
public static void main(String [] args) throws Exception {
// arglist variables String serverName = args[0]; String userName = args[1]; String password = args[2]; String url = "https://"+serverName+"/sdk/vimService";
// Variables of the following types for access to the API methods // and to the vSphere inventory.
VMware, Inc. 75
vSphere Web Services SDK Programming Guide
// -- ManagedObjectReference for the ServiceInstance on the Server // -- VimService for access to the vSphere Web service // -- VimPortType for access to methods // -- ServiceContent for access to managed object services ManagedObjectReference SVC_INST_REF = new ManagedObjectReference(); VimService vimService; VimPortType vimPort; ServiceContent serviceContent;
// Declare a host name verifier that will automatically enable // the connection. The host name verifier is invoked during // the SSL handshake. HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
} };
// Create the trust manager. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; javax.net.ssl.TrustManager tm = new TrustAllTrustManager(); trustAllCerts[0] = tm;
// Create the SSL context javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
// Create the session context javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext();
// Initialize the contexts; the session context takes the trust manager. sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null);
// Use the default socket factory to create the socket for the secure connection javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Set the default host name verifier to enable the connection. HttpsURLConnection.setDefaultHostnameVerifier(hv);
// Set up the manufactured managed object reference for the ServiceInstance SVC_INST_REF.setType("ServiceInstance"); SVC_INST_REF.setValue("ServiceInstance");
// Create a VimService object to obtain a VimPort binding provider. // The BindingProvider provides access to the protocol fields // in request/response messages. Retrieve the request context // which will be used for processing message requests. vimService = new VimService(); vimPort = vimService.getVimPort(); Map<String, Object> ctxt = ((BindingProvider) vimPort).getRequestContext();
// Store the Server URL in the request context and specify true // to maintain the connection between the client and server. // The client API will include the Server's HTTP cookie in its // requests to maintain the session. If you do not set this to true, // the Server will start a new session with each request. ctxt.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url); ctxt.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
// Retrieve the ServiceContent object and login serviceContent = vimPort.retrieveServiceContent(SVC_INST_REF); vimPort.login(serviceContent.getSessionManager(), userName, password, null);
76 VMware, Inc.
// retrieve data collectProperties( vimPort, serviceContent );
// close the connection vimPort.logout(serviceContent.getSessionManager());
} }

Client Data Synchronization (WaitForUpdatesEx)

To maintain a client-side representation of server object state (by monitoring the properties for the inventory), use the CreateFilter and WaitForUpdatesEx methods. The WaitForUpdatesEx method supports an incremental retrieval model.
I
MPORTANT The filters you use for incremental retrieval persist for the duration of the session or until you
destroy them.

Property Filters

A PropertyCollector can have one or more associated PropertyFilter objects. A PropertyFilter has one or more associated PropertyFilterSpec objects. A PropertyFilterSpec that is used with the RetrievePropertiesEx method has a limited lifespan; the server destroys the filter after returning results to your client. For a sequence of incremental property collection operations, the WaitForUpdatesEx method relies on PropertyFilterSpec objects that are available for multiple calls to the method.
Chapter 5 Property Collector
To create persistent property filter specifications, use the CreateFilter method. When you call CreateFilter, you pass a PropertyFilterSpec object to the method. The method adds the new filter to the PropertyCollector associated with the method invocation and returns a reference to the new filter. After
you have created the filter, you can add additional PropertyFilterSpec objects. You cannot share a filter with a PropertyCollector in another session.

WaitForUpdatesEx

The WaitForUpdatesEx method supports a polling mechanism for property collection that is based on a specified wait time.
Specify the following parameters when you call WaitForUpdatesEx:
Managed object reference to a PropertyCollector instance.
version value that identifies a sequence value. The first time you call WaitForUpdatesEx, specify an
empty string (““) to retrieve a complete set of results for the specified properties. Your subsequent calls should use the version value returned in the previous call. If you don’t include the version value, the server returns everything. For more information about data versions, see “Server Data Transmission” on page 79.
options specifying the amount of data to transmit in a single response (the
WaitOptions.maxObjectUpdates property) and the number of seconds the PropertyCollector should wait for updates (the WaitOptions.maxWaitSeconds property).
The value of the WaitOptions.maxWaitSeconds property determines whether the PropertyCollector uses an instant retrieval or a polling model. When you call WaitForUpdatesEx with a wait time of 0, it checks for updates and returns immediately. When you call WaitForUpdatesEx with a wait time greater than 0, the method waits until the specified time or until a change. WaitForUpdatesEx blocks your process until updates occur or until it times out. The time-out is affected by the maxWaitSeconds value, the amount of time it takes to collect updated property values, and PropertyCollector policy.
VMware, Inc. 77
vSphere Web Services SDK Programming Guide
If the property collection operation times out, and there are no updates to the requested properties, the PropertyCollector returns null for the WaitForUpdatesEx response.
maxWaitSeconds is an optional property. If you do not specify a value, the PropertyCollector waits as
long as possible for updates. Therefore, if maxWaitSeconds is unset, the waitForUpdatesEx method will block the thread after all of the data has been retrieved, waiting for the TCP connection with the vSphere server to timeout. Your code can handle this in one of the following ways: call waitForUpdatesEx from a separate thread; look for specific updates and then stop calling the method; or change the TCP connection timeout [BindingProviderProperties.CONNECT_TIMEOUT].)
maxWaitSeconds set to zero specifies an immediate call and response. The PropertyCollector checks
for updates for all properties specified by the union of all filters associated with that instance of the PropertyCollector. The PropertyCollector returns any results or null if there have been no updates.
maxWaitSeconds greater than zero specifies a wait followed by polling. The PropertyCollector returns
null if no updates are available within maxWaitSeconds.
Tab le 5 -3 lists some of the advantages and disadvantages of these two operations.
Tabl e 5-3 . WaitForUpdatesEx Operations Compared
Operation Advantages Disadvantages
MaxWaitSeconds=0 Returns only properties that have changed
since the version specified. Returns changed data only, providing better network utilization than RetrieveProperties.
MaxWaitSeconds>0 Blocks thread until an update occurs. Efficient
use of network resources. The only operation that you can cancel.
Returns an empty set even when nothing has changed on the server. Depending on your client application, this might be inefficient.
Blocks processing thread until updates occur. However, this call can be cancelled so you can monitor the time the operation is taking and cancel if necessary.
The WaitForUpdatesEx method returns an UpdateSet data object, the composite data structure shown in
Figure 5-5.
Figure 5-5. UpdateSet Data Object Returned by WaitForUpdates Operations
78 VMware, Inc.

Server Data Transmission

Property collection can involve the retrieval of large amounts of data, depending on the number of properties implied in the collection request. The vSphere server supports segmented data transmission, or chunking, when it sends collected data to a client. If the amount of collected data exceeds the chunk size, the server returns a chunk of data in a single response, and indicates additional data can be retrieved. For information about chunk size, see the description of the RetrieveOptions.maxObjects and WaitOptions.maxObjectUpdates properties in the vSphere API Reference.
The WaitForUpdatesEx method returns an UpdateSet data object. The UpdateSet.truncated
property indicates whether you must call WaitForUpdatesEx again to retrieve additional data. If truncated is true, the WaitForUpdatesEx method returns a version string to identify chunked data.
When your client application receives an indication that additional data are available, it must send the returned UpdateSet.version string in the subsequent call to WaitForUpdatesEx to retrieve the next chunk of data.
The RetrievePropertiesEx method returns a RetrieveResult data object. The
RetrieveResult.token property indicates whether you must call the ContinueRetrievePropertiesEx method to retrieve additional data. If the token property has a value,
it identifies chunked data. When your client application receives an indication that additional data are available, it must send the returned token in the subsequent call to ContinueRetrievePropertiexEx to retrieve the next chunk of data.
Version strings and tokens are sequenced. Your client application must keep track of the sequence of values. If an error interrupts the collection operation, resume the operation by using the version string or token that was submitted before the interruption.
Chapter 5 Property Collector

PropertyCollector Performance

These factors can affect the performance of a PropertyCollector for any given session:
Number of objects
Number of properties
Density of property data (composite, nested data objects)
Frequency of changes to the objects and properties on the server
Depth of traversal (number of properties traversed)
In addition, a vSphere server is affected by the number of PropertyCollector instances and the number of filters each instance is supporting across all sessions on the server.
To minimize PropertyCollector overhead and the amount of network traffic for your client application, use
View objects with the PropertyCollector. Example 5-1 illustrates using views with the PropertyCollector.

SearchIndex

The SearchIndex managed object provides a set of methods to retrieve references to managed objects in the vSphere inventory. You can search by managed objects inventory path, IP address, datastore path, DNS name, and various other identifying attributes. For example, if you know the IP address of a virtual machine, you can obtain its managed object reference by using the SearchIndex.FindByIp method. You can use SearchIndex to obtain the reference to a server object, and then use that reference as the starting object for property collection. See the sample applications SearchIndex.java and SearchIndex.cs for more information about using SearchIndex. See the vSphere API Reference for more information about SearchIndex methods.
VMware, Inc. 79
vSphere Web Services SDK Programming Guide
80 VMware, Inc.
6

Authentication and Authorization

VMware vSphere implements mechanisms to ensure that only valid users can access virtual infrastructure components.Each property and method in the API has an associated privilege requirement, and only uses with corresponding privileges can access the entities. This chapter discusses approaches to securing the system and the related service interfaces. The chapter also discusses the user model, which is different in ESXi systems and vCenter Server systems.
The chapter includes the following topics:
“Objects for Authentication and Authorization Management” on page 81
“Authentication and Authorization for ESXi and vCenter Server” on page 82
“Setting Up Users, Groups, and Permissions” on page 84
“Obtaining User and Group Information from UserDirectory” on page 85
“Managing ESXi Users with HostLocalAccountManager” on page 86
“Managing Roles and Permissions with AuthorizationManager” on page 86
“Authenticating Users Through SessionManager” on page 91
“Using the Credential Store for Automated Login” on page 91
6
“Managing Licenses with LicenseManager” on page 94
See the vSphere Datacenter Administration Guide for a list of required privileges for common tasks and best practices for roles and permissions. See Appendix D, “Privileges Reference,” on page 231 for lists of privileges required to invoke operations and to read properties, and privileges defined for the administrator role.

Objects for Authentication and Authorization Management

VMware vSphere includes the following interfaces for authenticating users and protecting virtual infrastructure components from unauthorized access:
HostLocalAccountManager is used to create and manage user accounts on ESXi systems. Authenticated
users can view objects or invoke operations on the server depending on the permissions associated with their account. See “Managing ESXi Users with HostLocalAccountManager” on page 86.
AuthorizationManager protects vSphere components from unauthorized access. Access to components
is role-based: Users are assigned roles that encompass the privileges needed to view and perform operations on vSphere objects. AuthorizationManager has operations for creating new roles, modifying roles, setting permissions on entities, and handling the relationship between managed objects and permissions.
UserDirectory provides a look-up mechanism that returns user-account information to
AuthorizationManager or to another requestor, such as a client application. See “Obtaining User and
Group Information from UserDirectory” on page 85.
VMware, Inc. 81
vSphere Web Services SDK Programming Guide
SessionManager provides an interface to the authentication infrastructure on the target server system
(see “Authenticating Users Through SessionManager” on page 91).
For vCenter Server systems, SessionManager supports single sign-on based on SSO tokens obtained
from a VMware SSO Server. See “Establishing a Single Sign On Session with a vCenter Server” on
page 28.
For ESXi systems, SessionManager supports authenticating user accounts as defined on the host
system, such as accounts created using vSphere Client or accounts created programmatically through
the HostLocalAccountManager API.
Even if a user is authorized to perform operations on a vSphere object, the operation fails if the licenses
for the host or the feature have not been assigned. You use LicenseManager and LicenseAssignmentManager to manage the licenses. See “Managing Licenses with LicenseManager” on
page 94.

Authentication and Authorization for ESXi and vCenter Server

Several server-side mechanisms authenticate a human user when a client application, such as the vSphere Client or a vSphere Web Services SDK application, connects to the server. Because ESXi uses Linux-based authentication, and vCenter Server is a Windows service, the two systems use different approaches for handling user accounts. Figure 6-1 shows the two different user management mechanisms associated with the VMware vSphere server.
Figure 6-1. Managed Objects for Handling User Accounts
These services work together to ensure that only authenticated users can connect to ESXi or vCenter Server systems, and that they can access only those objects—folders, virtual machines, datacenters, virtual services, and so on—for which they have the required privileges and which they are authorized to use or to view.
In addition, the vSphere Web Services SDK supports automated login through a credential store. See “Using
the Credential Store for Automated Login” on page 91.

ESXi User Model

When users enter their user account and credential from a client application, the server consults the appropriate user account store and validates the authenticity of the user account and the associated credential. Currently, the credential consists of a password, but vSphere also supports certificates, such as X.509 certificates. Authenticated users can then access objects they are authorized to use. Authentication succeeds if a user identity exists as a user account on the target system or in a supported directory service.
82 VMware, Inc.
Chapter 6 Authentication and Authorization
ESXi leverages standard Linux infrastructure, including the Linux pluggable authentication module (PAM) mechanism for user account creation and management. The VMware authentication daemon (vmware-authd) is implemented as a PAM module. You can create and manage user accounts on an ESXi system by using HostLocalAccountManager.

vCenter Server User Model

vCenter Server is a Windows-based service that uses native Windows facilities and the Windows user model for identification and authentication. The vCenter Server Web service is associated with the Windows user account that was logged in to the machine for the vCenter Server installation process. This vCenter Server administrator account must be a member of the local Windows Administrator group on the machine. VMware recommends creating a dedicated Windows user account for installing and managing the vCenter Server system.
Other vCenter Server users who connect to the Web service must also have a Windows account on the local Administrator group.
IMPORTANT Even if a user with the same name exists on an ESXi host and a vCenter Server system, the two users have different accounts.
For details, see the Datacenter Administration Guide in the VMware vSphere documentation set.
Organizations that are using Microsoft Active Directory can use the user identities contained in a Windows 2003 Server domain controller or Active Directory service across their virtual infrastructure. Microsoft Active Directory identities are supported for all clients that run vSphere Web Services SDK applications from Windows-based systems.
A vCenter Server client uses a SAML token to establish a single sign on session with the Server. See
“Establishing a Single Sign On Session with a vCenter Server” on page 28.

vSphere Security Model

While the details of authentication and authorization differ between ESXi and vCenter Server, the model itself is the same for both system. It relies on privileges, roles, and permissions.
Privileges
A privilege is a system-defined requirement associated with a VMware vSphere object. Privileges are defined by VMware. Privileges are static, and do not change for a single version of a product. Each managed object has one or more privileges that a principal (user, group member) must have to invoke an operation or to view a property. For example, managed entities such as Folder and VirtualMachine require the principal to have the System.Read privilege on the entity to view the values of its properties.
The vSphere API Reference includes information about privileges required to invoke operations and to view properties on the Required Privileges labels on the documentation page for each managed object. Privileges for vSphere components are defined as follows:
<group>[.<group>].privilege
For example:
Datacenter.Create Host.Config.Connection Host.Config.Snmp
A privilege might be specific to vCenter Server or to ESXi systems. For example, the Alarm.Create privilege is defined on vCenter Server. Setting alarms is done through the AlarmManager service interface, which requires a running vCenter Server system.
Privilege requirements apply to system objects regardless of how a given client application attempts to access server content (vSphere Client, CLI, or SDK). For example, you can use the following URL to access virtual machine datastore files:
https://<hostname>/folder[/<path>]/?dcPath=<datacenter_path>[&dsName=<datastore_name>]
VMware, Inc. 83
vSphere Web Services SDK Programming Guide
The URL accesses a Datastore object in the inventory. You must have privileges to access each object in the hierarchy, corresponding to the elements of the URL.
Tabl e 6-1 . Privileges Required for Datastore Objects Apply Regardless of Access Mechanism
Object Associated with File URL Element Required Privileges
Root folder /folder System.View
Datacenter ?dcPath Datastore.Browse
Datastore &dsName Datastore.Browse
Host /host Host.Config.AdvancedConfig
Roles
A role is a predefined set of privileges. Users are granted privileges to objects through roles (see “Using Roles
to Consolidate Sets of Privileges” on page 88). When you assign a user or group permissions, you pair the user
or group with a role and associate that pairing with an inventory object. A single user might have different roles for different objects in the inventory.
For example, if you have two resource pools in your inventory, Pool A and Pool B, you might assign a particular user the role Virtual Machine User on Pool A and the role ReadOnly on Pool B. These assignments allow that user to turn on virtual machines in Pool A. In Pool B, the user can view the status of virtual machines, but cannot turn on virtual machines.
Datastore.FileManagement
Datastore.FileManagement
/tmp/ Host.Config.SystemManagement
Table D-3, “Privileges Granted to the Administrator Role,” on page 240 shows a complete list of privileges
encompassed by the Administrator role as defined on a vCenter Server 4.0 system.
Permissions
In vSphere, a permission consists of a user or group and an assigned role for an inventory object, such as a virtual machine or ESXi host. Permissions grant users the right to perform the activities specified by the role on the object to which the role is assigned.
For example, to configure memory for an ESXi host, a user must be granted a role that includes the Host.Configuration.Memory privilege. By assigning different roles to users or groups for different objects, you can control the tasks that users can perform in your vSphere environment.
Many tasks require permissions on more than one object.

Setting Up Users, Groups, and Permissions

Setting up users, groups, and permissions consists of these tasks:
1 Get information about privilege requirements and privileges associated with system and sample roles.
Find out which operations on vSphere objects require which privileges. See the API Reference.
Find out which operations the system roles and sample roles can perform. See Table 6-2, “System and
Sample Roles,” on page 88.
2 If necessary, create additional roles (sets of privileges). See “Modifying Sample Roles to Create New
Roles” on page 89.
84 VMware, Inc.
Chapter 6 Authentication and Authorization
3 Retrieve information about existing users and groups (see “Obtaining User and Group Information from
UserDirectory” on page 85) and create additional groups if needed.
4 Associate users or groups with roles using permissions. See “Managing Roles and Permissions with
AuthorizationManager” on page 86.
At runtime, use SessionManager to log in to the server. vCenter Servers support single sign-on sessions. To establish a single sign-on session, use the SessionManager.LoginByToken method. To establish a session with a standalone ESXi host, use the SessionManager.Login method.

Obtaining User and Group Information from UserDirectory

The UserDirectory managed object allows a client application to obtain information about users and groups on a VMware vSphere server. Properties and results vary, depending on whether the server is a vCenter Server or an ESXi system.
vCenter Server system. Domain controller, Active Directory, or local Windows account repository.
ESXi host. Linux password file in /etc/passwd on the host.
For example, vCenter Server user accounts can be managed in a Windows Active Directory server or domain controller from which the domainList property of UserDirectory is derived. For ESXi systems, the domainList property is empty.
Figure 6-2. UserDirectory Managed Object
UserDirectory allows you to obtain information about users and groups using the RetrieveUserGroups method. The method can obtain a list of all user accounts from the host, and can search for specific users or groups based on specific criteria to filter the results. You can search by user name, by group name, for an exact match, or for a partial string (substring).
ESXi does not support local user groups, so this method will not return group information for a host. This
method will return information about Active Directory groups.
For ESXi systems, search returns all users from the passwd file. If this file contains Network Information
System (NIS) or NIS+ users, RetrieveUserGroups returns these accounts as well.
For vCenter Server, search is limited to the specified Windows domain. If the domain is omitted, the
search is performed on local users and groups.
IMPORTANT Do not configure an ESXi system to use NIS or NIS+, unless it is acceptable to have NIS (or NIS+) user information available through the UserDirectory.RetrieveUserGroups API.
VMware, Inc. 85
vSphere Web Services SDK Programming Guide

Managing ESXi Users with HostLocalAccountManager

The HostLocalAccountManager managed object supports user administration tasks. HostLocalAccountManager is available only on ESXi system.
I
MPORTANT vCenter Server systems use the Microsoft Windows user management facilities. See “vCenter
Server User Model” on page 83.
Figure 6-3. HostLocalAccountManager Managed Object
HostLocalAccountManager provides the following methods for local user account management:
CreateUser
RemoveUser
UpdateUser
These methods accept a HostAccountSpec data object. Specify the object properties according to the requirements on the target system. Examples of user account requirements are password length requirements and restricted use of dictionary words.
To create a user account on an ESXi system
1 Obtain a managed object reference to the HostLocalAccountManager of the target system.
2 Create a HostAccountSpec data object that defines the properties of the user account, including
description and password.
Define account names and passwords according to the configuration required by your ESXi system for user account naming conventions and password requirements, such as minimum length, character set, and other requirements.
3Call the HostLocalAccountManager.CreateUserAccount method, passing in the managed object
reference (from step 1) and the HostAccountSpec data object (step 2).
After creating user accounts on the ESXi system, you can grant these users access to virtual components by using AuthorizationManager methods. See “Managing Roles and Permissions with
AuthorizationManager” on page 86.

Managing Roles and Permissions with AuthorizationManager

AuthorizationManager is the service interface for handling permissions and roles assigned to the users and groups you define with HostLocalAccountManager. AuthorizationManager methods allow you to create, modify, and manage roles and permissions, and to obtain information about the roles and permissions defined in the system. If a predefined role does not meet your needs, define a new one that contains only the minimum set of required privileges.
The AuthorizationManager also allows access and prevents access to specific server objects based on the permissions associated with the object.
AuthorizationManager includes methods for managing roles and for managing permissions:
Roles Management. AddAuthorizationRole, RemoveAuthorizationRole, and
UpdateAuthorizationRole. See “Using Roles to Consolidate Sets of Privileges” on page 88 and
“Modifying Sample Roles to Create New Roles” on page 89.
86 VMware, Inc.
Permissions Management. MergePermissions, RemoveEntityPermission,
ResetEntityPermissions, RetrieveAllPermissions, RetrieveEntityPermissions, RetrieveRolePermissions, and SetEntityPermissions. See “Granting Privileges Through
Permissions” on page 89.
Figure 6-4 shows these methods in a UML diagram for AuthorizationManager and some of its associated
data objects.
Figure 6-4. AuthorizationManager Managed Object
Chapter 6 Authentication and Authorization
VMware, Inc. 87
vSphere Web Services SDK Programming Guide
AuthorizationManager properties allow access to information. For example:
The privilegeList property returns a list of all privileges defined on the system, as an array of
AuthorizationPrivilege data objects. Privileges are defined by VMware, on the objects and properties
contained in the system. These privileges are fixed and cannot be changed by client applications. See
Appendix D, “Privileges Reference,” on page 231 for lists of privileges.
The roleList property returns a list of all currently defined roles, including the system-defined roles, as
an array of AuthorizationRole data objects.

Using Roles to Consolidate Sets of Privileges

A role is a named set of one or more privileges. A role is normally defined for a group of people who have common responsibilities in the system, for example, administrators. Each role can have zero to multiple privileges. ESXi defines system roles and user roles.
System roles. Cannot be modified or deleted.
User roles. Apply to different user communities or restrict access for add-on tools. Several predefined
user roles are included with vCenter Server and with ESXi systems. You can create new roles using these predefined user roles as a starting point.
Tab le 6 -2 describes these two types of roles in more detail and lists currently available roles as examples.
Tabl e 6-2 . System and Sample Roles
Type Role name Role ID Description
System Roles
Sample Roles
Administrator -1 Superuser access. Encompasses the set of all defined privileges. See
Table D-3, “Privileges Granted to the Administrator Role,” on page 240
for an example list from a vCenter Server system. This role cannot be deleted. By default, the Administrator role is granted to the user or group that owns the root node.
Anonymous -4 Cannot be granted. Default access role associated with any user account
that has logged in.
No Access -5 No access. Explicitly denies access to the user or group with this role.
Read-Only -2 Read-only access. Encompasses the set of all nonmutable privileges.
View -3 Visibility access consisting of System.Anonymous and System.View
Virtual Machine Administrator
Datacenter Administrator
Virtual Machine Provider
Virtual Machine Power User
Virtual Machine User 5 Set of privileges necessary to use virtual machines only. Cannot
ResourcePool Administrator
VMware Consolidated Backup Utility
Assigning this role to a user account prevents the user from seeing any objects. Use the No Access role to mask subobjects under a higher-level object that has propagated permissions defined.
(System.Anonymous, System.Read, and System.View). Equivalent to a user role with no permissions. Users with this role can read data or properties and call query methods, but cannot make changes to the system.
privileges. Cannot be granted.
1 Set of privileges necessary to manage virtual machines and hosts within
the system.
2 Set of privileges necessary to manage resources, but not interact with
virtual machines.
3 Set of privileges necessary to provision resources.
4 Set of privileges for a virtual machine user that can also make
configuration changes and create new virtual machines.
reconfigure virtual machines.
6 Available on vCenter Server systems only.
7 Available on vCenter Server systems only. Set of privileges necessary to
run the Consolidated Backup Utility.
88 VMware, Inc.
Chapter 6 Authentication and Authorization

Modifying Sample Roles to Create New Roles

The system roles listed in Tab le 6 -2 cannot be modified or deleted. However, you can create new roles, or modify the sample roles.
To create new roles using the API
1 Starting with the ServiceContent object in ServiceInstance.content, obtain a managed object
reference to the AuthorizationManager for the server.
2Invoke the AddAuthorizationRole method. Parameters are a reference to AuthorizationManager, a
name for the role (as a string), and an array of privileges (array of strings) that should be assigned to the role.
AddAuthorizationRole returns an integer (xsd:int) value for the roleId that the system assigns to the newly defined role.
3 In subsequent code, use the roleID to assign the role to specific users or groups.

Granting Privileges Through Permissions

When you use one of the AuthorizationManager objects to assign or modify permissions, you use a Permission data object. Permission associates a principal with a set of privileges. A permission identifies:
The user or group (principal) to which the permission applies.
The role containing the privileges that should be granted to the user or group.
The managed object reference to the entity to which the permission applies.
Every managed entity has at least one Permission object associated with it. A managed entity can have more than one Permission assigned to it, effectively granting different privileges to different users or groups. Permissions are defined for managed entities either explicitly or through inheritance.
Obtaining Information About Permissions
Users with the Administrator role can obtain information about Permission objects at different levels of detail.
For an array of Permission objects, call the AuthorizationManager.RetrieveAllPermissions
method.
For specific inventory objects, such as managed entities, folders, datacenters, or virtual services, call the
AuthorizationManager.RetrieveEntityPermissions method.
For a role defined in the system, call the AuthorizationManager.RetrieveRolePermissions method.
See the vSphere API Reference.
Setting, Changing, or Deleting Permissions
The Permission data object associates the privileges required to perform an action on an object with the principals (user, group). Principals have privileges through their role. To set or update permissions on an object, use the AuthorizationManager.SetEntityPermissions method.
To set permissions on an entity
1 Obtain a reference to the AuthorizationManager for the server from the ServiceContent object
associated with the ServiceInstance. For example:
ManagedObjectReference hostAuthorizationManager = service.getAuthorizationManager();
2 Create a Permission data object that identifies the user (or group) name, the role, the entity to which the
permission should apply, and whether the permission should be applied to the entity’s children.
VMware, Inc. 89
vSphere Web Services SDK Programming Guide
For example, the following code fragment creates a permission on the root folder of the inventory granting a user Administrator role to the root folder and all its children.
Permission per = new Permission(); per.setGroup(false); per.setPrincipal(“new_user_name”); per.setRoleId(-1); per.setPropagate(true); per.setEntity(rootFolder);
Permissions cannot be set directly on children in a complex entity. For complex entities, set permissions on the parent entity and set the propagate flag to true to apply permissions to the child entities.
To replace existing permissions with a new set of permissions, use the AuthorizationManager.ResetEntityPermissions method.
Impact of Group Membership on Permissions
Users can be members of multiple groups. The system handles multigroup membership as follows:
Permissions are applied to inventory objects from the containing object to each of its child entities.
If a user has no explicit user-level permissions, group-level permissions apply as if granted to the user
directly.
Membership in multiple groups with permissions on the same object results in a union of permissions.
User-level permissions always take precedence over group-level permissions.
Applying Permission to a Managed Entity
Example 6-1 shows some of the code required to create a user account and apply a permission to an entity that
grants access to the user account based on a role. The role with role ID 4, assigned in this example, is defined as a “Virtual Machine Power User.” The sample uses AuthorizationManager to grant permissions to the user and to associate the permission with the managed entity in the inventory—in this example, the rootFolder. The example uses the apputil helper classes to access the objects.
Example 6-1. Creating a User Account
... ManagedObjectReference _authManRef = _sic.getAuthorizationManager(); public class CreateUser { private static AppUtil appUtil= null; private void createUser() throws Exception { ManagedObjectReference hostLocalAccountManager =
ManagedObjectReference hostAuthorizationManager =
appUtil.getConnection().getServiceContent().getAuthorizationManager();
// Create a user HostAccountSpec hostAccountSpec = new HostAccountSpec(); hostAccountSpec.setId(userName); hostAccountSpec.setPassword(password); hostAccountSpec.setDescription("my delegated admin auto-agent software"); appUtil.getConnection().getService().createUser(hostLocalAccountManager, hostAccountSpec); ManagedObjectReference rootFolder = appUtil.getConnection().getServiceContent().getRootFolder(); Permission permission = new Permission(); permission.setGroup(false); permission.setPrincipal(userName);
appUtil.getConnection().getServiceContent().getAccountManager();
// Assign the Virtual Machine Power User role permission.setRoleId(4); permission.setPropagate(true); permission.setEntity(rootFolder); appUtil.getConnection().getService().setEntityPermissions(hostAuthorizationManager, rootFolder,
new Permission [] {permission});
...
90 VMware, Inc.

Authenticating Users Through SessionManager

The SessionManager managed object controls user access to the server. SessionManager includes methods for logging in to the server, obtaining a session, and logging out. The SessionManager defines the lifetime and visibility of many objects. Session-specific objects are not visible outside the session in which they are created.
I
MPORTANT Each user session uses system resources and creates locks on the server side. Too many
concurrent sessions can slow down the server. By default, vCenter Server terminates a session after 30 minutes.
Upon successful authentication of a user account, SessionManager returns a UserSession data object to the client application. The session is associated with that user account for the duration of the session. The client application can save the session locally, to a secure file, and reuse the session later to reconnect to the server. You can also configure an ESXi or vCenter Server system to support local sessions, which enable users with credentials on the host to log in based on those privileges.
The SessionManager provides these capabilities:
Log in and log out. Basic operations to log in to ESXi or vCenter Server system, obtain a session, and log
out. When a session terminates, all session-specific objects are destroyed.
Impersonation. One user session adopts the authorization level of another user session. Impersonation is
common in Web based scenarios in which a middle-tier application functions as a central account that interacts with other back-end servers or processes. Windows services impersonate a client when accessing resources on behalf of the client. SesssionManager supports impersonation through its ImpersonateUser method.
Chapter 6 Authentication and Authorization
Delegation. A client application that is running on behalf of a local user can call the
SessionManager.AcquireLocalTicket method to obtain a one-time user name and password for logging in. Delegation is useful for host-based utilities that run in the local console.
If the user account associated with the session does not have the permissions required to perform an action, the AuthorizationManager returns a NoPermission fault to the client application.

Using VMware Single Sign On for vCenter Server Sessions

vSphere supports single sign on for a single point of authentication for vCenter Server clients. To use VMware Single Sign On, your vSphere Web Services SDK client connects to the VMware SSO Server to obtain an SSO token. Your client includes the token in the SessionManager.LoginByToken request to start a vSphere session. See “Establishing a Single Sign On Session with a vCenter Server” on page 28.

Using the Credential Store for Automated Login

To facilitate automated login for unattended applications, the vSphere Web Services SDK includes client-side credential store libraries and tools for automating the login process in a more secure manner. The libraries eliminate the need for system administrators to keep passwords in local scripts.
IMPORTANT These libraries are built on top of the vSphere Web Services SDK.
The credential store has the following components:
A persistence file (credential store backing file) that stores authentication credentials. Currently, only
passwords are supported. The persistence file maps a remote user account from an ESXi host to the password for that user on the server.
C#, Java, and Perl libraries for managing the credential store programmatically. See Tabl e 6 -4 for available
methods.
Java and Microsoft PowerShell-based command-line utilities for managing the credential store.
In addition to the libraries listed in Ta bl e 6 -3 , the vSphere Web Services SDK includes the CredentialStoreAdmin tool for creating, examining, and managing the credential store. You can use the tool to examine the contents of the credential store, for example, the generated user accounts and passwords.
VMware, Inc. 91
vSphere Web Services SDK Programming Guide
If you use the credential store client libraries, shown in Table 6 -3 in an application, you must set up the credential store on all client machines that run your application.
Tabl e 6-3 . Credential Store Client Libraries
Package com.vmware.security.credstore (Java) Namespace VMware.Security.CredentialStore(C#)
CredentialStore.java CredentialStoreFactory.cs
CredentialStoreFactory.java CredentialStore.cs
Several of the helper classes provided with the sample applications use the credential store mechanism.

Credential Store Methods

Tabl e 6-4 . Credential Store Client Methods
Java C# Description
addPassword(hostname, username, password)
removePassword(hostname, username)
clearPasswords() ClearPasswords() Deletes all passwords from the credential
getPassword(hostname, username)
getHosts() GetHosts() Returns the set of hosts contained in the
getUsernames(hostname) GetUsernames(hostname) Returns the collection of all user names
close() Close() Closes the credential store, preventing
AddPassword(hostname, username, password)
RemovePassword(hostname, username)
GetPassword(hostname, username)
Stores the password for the specified host and user. Overwrites any existing password for that user in the credential store. Creates the default credential store backing file in the default location (if it does not exist).
Deletes the password for the specified user from the credential store.
store.
Returns the password for the specified host and user from the credential store.
credential store.
that have passwords stored for the specified hostname.
further method invocations. Releases associated resources.

Credential Store Backing File

The credential store backing file is an XML file that is saved locally on the client machine for access at runtime. Unless otherwise specified, the backing file is located in the following location:
Linux. $HOME/.vmware/credstore/vicredentials.xml
Windows Vista.
Windows XP and Windows 2000.
C:\Documents and Settin
The credential store persists locally on a per-user basis—each user has his or her own credential store backing file.
CAUTION The credential store backing files use filesystem-level permissions to ensure that passwords remain confidential. Protect the credential store backing file with appropriate file permissions.
92 VMware, Inc.
C:\Users\[user_name]\AppData\Roaming\VMware\credstore\vicredentials.xml
gs\[user_name]\Application Data\VMware\credstore\vicredentials.xml
Chapter 6 Authentication and Authorization
Example 6-2 shows the XML elements that are read and written to the file.
Example 6-2. Credential Store File Format
<?xml version="1.0" encoding="UTF-8"?>
<viCredentials>
<version>1.0</version>
<passwordEntry>
<host>mi6.vmware.com</host> <username>agent007</username>
<password>IhWS1saIhtsw2FbIh0w2F2...</password> </passwordEntry> <passwordEntry>
... </passwordEntry> ...
</viCredentials>

Credential Store Samples

The CreateUser and SimpleAgent sample applications demonstrate how to use the credential store client libraries.
The CreateUser sample creates a user account and password for the server based on
random-number-generation scheme. The sample populates the local credential store backing file with this information. If the backing file does not exist, it is created in the default location.
When you run CreateUser, specify the name of an ESXi system, and an administrator user name and password. A user account name and password are created on the server. Specify --ignorecert unless your system has a secure connection to the target. Do not use --ignorecert in a production environment.
java com.vmware.samples.simpleagent.CreateUser --server <servername> --url https://<servername>/sdk --username <adminuser> --password <pwd> --ignorecert ignorecert
CAUTION The CreateUser sample application is for demonstration purposes only and should not be used as a model for production code. The sample breaks the principle of least privilege by granting the user account the Administrator role (-1). Never do this in a production environment.
The SimpleAgent sample application demonstrates how to use credential store libraries to extract the user account and password at runtime to authenticate a user noninteractively.
java com.vmware.samples.simpleagent.SimpleAgent <servername>

Specifying Roles and Users with the Credential Store

VMware recommends that you apply the principle of least privilege to any agent-like software or automated application that uses the credential store in a production environment. Give user accounts the minimal number of privileges on the system that they require to do their jobs.
Specify roles and users as follows:
1 For each SDK-based application, use one specific role, newly created or predefined, that has appropriate
privileges.
For example, if you are developing an agent-like application to automatically start the VMware Consolidated Backup utility, you might use the “VMware Consolidated Backup Utility” role (roleID 7).
If no predefined user role that meets the needs of your application exists, create a role with only those privileges needed for the application. See Table 6-2, “System and Sample Roles,” on page 88 for more information about roles.
2 Create a user account for use with the agent or application.
VMware, Inc. 93
vSphere Web Services SDK Programming Guide
3 Apply the role created in Step 1 to the user account created in Step 2.
4 Store the user account and password in the credential store, using the
CredentialStoreAdministration tool.
Never grant administrator privileges to a user account associated with an automated script or software agent, especially one that uses the credential store.

Managing Licenses with LicenseManager

When you want perform tasks in the vSphere environment, you must have licenses to do so. Licensing applies to ESXi hosts, vCenter Server, and special features such as VMware HA or VMware vMotion.
The vSphere Datacenter Administration Guide explains how to manage ESXi and vCenter Server licenses using the vSphere Client, and gives background information about license keys, license inventory, and related topics.
You can also manage licenses using the LicenseManager and LicenseAssignmentManager managed objects. You use LicenseManager to explicitly manage the pool of available licenses on ESXi systems released before vSphere 4.0. You use LicenseAssignmentManager, available through the LicenseManager.licenseAssignmentManager property, to manage assignment of licenses to entities in the vCenter Server inventory. You can retrieve information, add licenses, and remove licenses.
Retrieve Information
Retrieve the LicenseManager.evaluation and LicenseManager.licenses properties to obtain
information on evaluation licenses and full licenses.
Call LicenseManager.DecodeLicense to decode license information. The call returns a
LicenseManagerLicenseInfo data object, which encapsulates information about the license.
Call LicenseAssignmentManager.QueryAssignedLicenses for information about assigned licenses.
Add Licenses
Call LicenseManager.AddLicense, passing in a license key, to add a license to the inventory of available
licenses.
Call LicenseAssignmentManager.UpdateAssignedLicense, passing in a license key, to update the
licenses for an entity, for example, a host system.
Remove Licenses
Call LicenseAssignmentManager.RemoveAssignedLicense to remove all licenses from an entity,
passing in an entity to remove licenses from. You can then assign those licenses to other entities.
Call LicenseManager.RemoveLicense, passing in a license key, to remove a license from the inventory
of available licenses.
94 VMware, Inc.
7

Hosts

Many of the operations in your vSphere environment involve setting up the ESX/ESXi hosts on which the virtualization layer runs. You can set up storage (see Chapter 8, “Storage,” on page 99) and networking (see
Chapter 9, “vSphere Networks,” on page 113), and those settings directly affect the virtual machine. You must
also manage other aspects of the host, as discussed in this chapter.
The chapter includes the following topics:
“Host Management Objects” on page 95
“Retrieving Host Information” on page 95
“Configuring and Reconfiguring Hosts” on page 96
“Managing the Host Lifecycle” on page 97
“Querying and Changing the Host Time” on page 98
“Querying Virtual Machine Memory Overhead” on page 98
IMPORTANT See the ESX Configuration Guide and the ESXi Configuration Guide for important information on security considerations, not included here.
7

Host Management Objects

The vSphere Web Services SDK includes several objects for host management.
The central object is HostSystem. Each property of HostSystem is a data object that encapsulates some information about the host. For example, the capability property is a HostCapability object, the runtime property is a HostRuntimeInfo object. See the API Reference for a list of the properties and the corresponding data objects.
HostSystem methods allow you to perform certain tasks on ESX/ESXi hosts. However, many tasks are not performed through HostSystem methods, but through methods in managed objects related to HostSystem. For example, you manage the host time using the HostDateTimeSystem and you manage kernel modules using HostKernelModuleSystem.

Retrieving Host Information

You retrieve information about the host by accessing data objects defined for the HostSystem.
HostSystem.capability is a HostCapability object. The HostCapability properties indicate the
features that are supported by the host, for example, maintenanceModeSupported or recursiveResourcePoolsSupported.
HostSystem.runtimeInfo is a HostRuntimeInfo object that contains several data objects with detailed
information about the current state of the host. You can, for example, extract the health status as a HealthSystemRuntime object or the power state as a HostPowerState object.
VMware, Inc. 95
vSphere Web Services SDK Programming Guide
HostSystem.hardware is a HostHardwareInfo object that allows you to retrieve the host’s hardware
configuration including CPU and NUMA information and memory size.
HostSystem.config is a HostConfigInfo object. This data object type encapsulates a typical set of host
configuration information that is useful for displaying and configuring a host. You can access the
HostConfigInfo object only on managed hosts, and only if the host is connected.
HostSystem has several additional properties that allow you to directly access the virtual machines,
datastores, and networks associated with that system.
The QueryHostConnectionInfo, QueryMemoryOverhead, and QueryMemoryOverheadEx methods are available for information retrieval.
Figure 7-1. HostSystem and Information Properties

Configuring and Reconfiguring Hosts

When you configure or reconfigure an ESX/ESXi host, you usually do not use the methods in HostSystem directly, but work with managed objects available for configuration of that part of the system. For example, HostNetworkSystem allows you to configure the network, and HostAuthorizationManager is for managing users, groups, and permissions on a host. The objects and related methods are discussed in the corresponding chapters of this guide.
Some methods are defined locally in HostSystem. See the vSphere API Reference for details on each method.
CIM Management – AcquireCimServicesTicket. For additional information on using vSphere with
CIM, see the VMware CIM APIs documentation.
Host Lifecycle – RebootHost_Task, ShutdownHost_Task, PowerDownHostToStandBy_Task,
PowerUpHostFromStandBy_Task, DisconnectHost_Task, ReconnectHost_Task. See “Managing the
Host Lifecycle” on page 97.
Maintenance Mode – EnterMaintenanceMode_Task, ExitMaintenanceMode_Task.
Updates – UpdateFlags, UpdateIpmi, UpdateSystemResources.
96 VMware, Inc.

Managing the Host Lifecycle

A host’s lifecycle depends in part on whether the host is a standalone host or managed by a vCenter Server system.

Reboot and Shutdown

You can reboot and shut down managed and standalone hosts. The ShutdownHost_Task method is not supported on all hosts. Check the host capability shutdownSupported.
You can call both methods with a force parameter, which specifies whether to reboot hosts even when virtual machines are running or other operations are in progress on the host. If you set the parameter to false, hosts are rebooted only when they are in maintenance mode.
ShutdownHost_Task – Shuts down a host. If connected directly to the host, the client never receives an
indicator of success in the returned task, but temporarily loses connection to the host. If the method does not succeed, an error is returned.
RebootHost_Task – Reboots a host. If the command is successful, then the host has been rebooted. Clients
connected directly to the host do not receive an indication of success in the returned task, but temporarily lose connection to the host. If the method does not succeed, an error is returned.

Using Standby Mode

Chapter 7 Hosts
Standby is a power state in which the host does not support provisioning or power on of virtual machines. VMware power management module might evacuate and put a host in standby mode to save power. The host can be powered up remotely by using PowerUpHostFromStandBy_Task.
The following methods support standby mode. Both methods are cancelable.
PowerDownHostToStandBy_Task – Puts the host in standby mode, a mode in which the host is in a
standby state from which it can be powered up remotely. The command is only supported on hosts on which the host capability standbySupported is true.
While this task is running, no virtual machines can be powered on and no provisioning operations can be performed on the host.
Calling this method does not directly initiate any operations to evacuate or power down powered-on virtual machines. However, if VMware DRS is enabled, the vCenter Server migrates powered-off virtual machines or recommends migration to a different host, depending on the automation level. If the host is part of a cluster and the task is issued with a vCenter Server target with the method’s evacuatePoweredOffVms parameter set to true, the task does not succeed unless all the powered-off virtual machines are reregistered to other hosts.
PowerUpHostFromStandBy_Task – Takes the host out of standby mode. If the command is successful, the
host wakes up and starts sending heartbeats. This method might be called automatically by VMware DRS to add capacity to a cluster, if the host is not in maintenance mode.

Disconnecting and Reconnecting Hosts

You can make a host a managed host by adding it to the vCenter Server system. You can later disconnect and reconnect the host, for example, to refresh the agents.
You can use the following methods, which are only supported if you access the host through a vCenter Server system.
QueryHostConnectionInfo – Returns a HostConnectInfo object, which is the same object that the
Datacenter.QueryConnectionInfo returns. The information in this object can be used by a connection wizard, like the wizard used in the vSphere Client.
DisconnectHost_Task – Disconnects from a host and instructs the vCenter Server system to stop
sending heartbeats to the host.
VMware, Inc. 97
vSphere Web Services SDK Programming Guide
ReconnectHost_Task – Reconnects a host to the vCenter Server system. This process reinstalls agents
and reconfigures the host, if it has gotten out of sync with the server. The reconnection process checks for the correct set of licenses and for the number of CPUs on the host, ensures the correct set of agents is installed, and ensures that networks and datastores are discovered and registered with the vCenter Server system.
Client applications can change the IP address and port of the host when doing a reconnect operation. This can be useful if the client wants to preserve existing metadata, such as statistics, alarms, and privileges, even though the host is changing its IP address.

Querying and Changing the Host Time

The HostDateTimeSystem supports date and time related configuration on a host and supports NTP configuration. See also “Adding an NTP Service” on page 122.
The HostDateTimeSystem.dateTimeInfo property allows you to retrieve and set date and time information. The HostDateTimeInfo data object’s properties contain two data object for date time management:
HostNTPConfig contains a list of NTP servers for use by the host.
HostDateTimeSystemTimeZone specifies the time zone including the GMT offset, identifier for the time
zone, and name.
You can also query the host’s time information by calling one of the HostDateTimeSystem methods.
QueryAvailableTimeZones – Retrieves the list of available timezones on the host. The method uses the
public domain tz timezone database. The method returns an array of HostDateTimeSystemTimeZone objects.
QueryDateTime – Returns the current date and time on the host.
You can modify the host’s date time information by calling one of the following HostDateTimeSystem methods:
RefreshDateTimeSystem – Refreshes the date and time related settings to pick up any changes that
might have occurred.
UpdateDateTime – Updates the date and time on the host using the date and time passed into the method.
Use with caution. Network delays or execution delays can result in time skews.
UpdateDateTimeConfig – Updates the date and time configuration of the host. You call this method with
a HostDateTimeConfig parameter, which allows you to specify both the NTP configuration and the time zone.

Querying Virtual Machine Memory Overhead

Each virtual machine you power on requires a certain amount of memory for its use. In addition, the host must have some memory overhead available for each virtual machine. To find out about memory overheat, call the HostSystem.QueryMemoryOverheadEx method. The method takes a virtualMachineConfigInfo data object as an argument, and determines the amount of overhead necessary to power on a virtual machine with those characteristics.
The methods returns the amount of memory required, in bytes.
98 VMware, Inc.
8

Storage

A virtual machine uses a virtual disk to store its operating system, program files, and other data. A virtual disk is a large physical file, or a set of files, that can be copied, moved, archived, and backed up like other files. To store and manipulate virtual disk files, a host requires dedicated storage space. ESX/ESXi supports storage in multiple ways. Hosts that are managed by a vCenter Server system can share storage.
The chapter includes the following topics:
“Storage Management Objects” on page 99
“Introduction to Storage” on page 100
“Choosing the Storage API to Use” on page 102
“Configuring Disk Partitions” on page 103
“Creating and Managing Datastores” on page 106
“Managing VMFS Volume Copies (Resignaturing)” on page 109
“Managing Diagnostic Partitions” on page 110
“Sample Code Reference” on page 111
Any type of network-attached storage requires complete configuration of networking in the VMkernel to support network-based access to the storage media. The VMkernel requires its own IP address. See Chapter 9,
“vSphere Networks,” on page 113.
8

Storage Management Objects

You can access the objects that support storage management through the HostSystem managed object.
HostStorageSystem – The HostSystem.storageSystem property is a managed object reference to the
HostStorageSystem of the ESX/ESXi system. HostStorageSystem is a low-level interface that is used mainly for configuring the physical storage. See “Configuring Disk Partitions” on page 103.
HostDatastoreSystem – The HostSystem.datastoreSystem property is a managed object reference to
a HostDatastoreSystem managed object. HostDatastoreSystem methods allow you to create, configure, extend, and remove datastores. While HostStorageSystem supports access and configuration of physical storage, HostDatastoreSystem supports access and configuration of logical storage through the volumes (Datastore managed objects) the host can use for virtual machines. See “Creating and
Managing Datastores” on page 106.
HostDatastoreBrowser – Provides access to the contents of one or more datastores. The items in a
datastore are files that contain configuration, virtual disk, and other data associated with a virtual machine.
VMware, Inc. 99
vSphere Web Services SDK Programming Guide
Datastore – The Datastore managed entity provides methods for mounting datastores, browsing
datastores, and obtaining information about the datastores associated with a virtual machine. See
“Creating and Managing Datastores” on page 106.
HostDiagnosticPartition – Supports creating and querying diagnostic partitions for your ESX/ESXi
host. See “Managing Diagnostic Partitions” on page 110.

Introduction to Storage

The VMware vSphere storage architecture consists of layers of abstraction that hide and manage the complexity and differences of physical storage subsystems, shown in Figure 8-1.
Figure 8-1. Storage Architecture

How Virtual Machines Access Storage

Virtual machines use virtual disks for their operating system, application software, and other data files. A virtual disk is stored as a VMDK file on a datastore. The virtual disk hides the physical storage layer from the virtual machine’s operating system. Regardless of the type of storage device that your host uses, the virtual disk always appears to the virtual machine as a local SCSI device. As a result, you can run operating systems that are not certified for specific storage equipment, such as SAN, in the virtual machine.
When a virtual machine communicates with its virtual disk stored on a datastore, it issues SCSI commands. Because datastores can exist on different types of physical storage, these commands are encapsulated into other forms, depending on the protocol that the ESX/ESXi host uses to connect to the physical storage device.
To the applications and guest operating systems running on each virtual machine, the storage subsystem appears as a virtual SCSI controller connected to one or more virtual SCSI disks as shown in the top half of
Figure 8-1. These controllers are the only types of SCSI controllers that a virtual machine can see and access,
and include the objects that extend VirtualSCSIController:
ParaVirtualSCSIController
VirtualBusLogicController
VirtualLsiLogicController
VirtualLsiLogicSASController
100 VMware, Inc.
Loading...