Programming Guide: Vmware Infrastructure Perl Toolkit 1.6
Programming Guide: Vmware Infrastructure Perl Toolkit 1.6
Programming Guide
Revision: 20080725
Item: EN-000052-00
You can find the most up-to-date technical documentation on our Web site at:
http://www.vmware.com/support/
The VMware Web site also provides the latest product updates.
If you have comments about this documentation, submit your feedback to:
docfeedback@vmware.com
© 2007, 2008 VMware, Inc. All rights reserved. Protected by one or more U.S. Patent Nos. 6,397,242, 6,496,847, 6,704,925,
6,711,672, 6,725,289, 6,735,601, 6,785,886, 6,789,156, 6,795,966, 6,880,022, 6,944,699, 6,961,806, 6,961,941, 7,069,413,
7,082,598, 7,089,377, 7,111,086, 7,111,145, 7,117,481, 7,149,843, 7,155,558, 7,222,221, 7,260,815, 7,260,820, 7,269,683,
7,275,136, 7,277,998, 7,277,999, 7,278,030, 7,281,102, 7,290,253, and 7,356,679; patents pending.
VMware, the VMware “boxes” logo and design, Virtual SMP and VMotion are registered trademarks or trademarks of VMware,
Inc. in the United States and/or other jurisdictions. All other marks and names mentioned herein may be trademarks of their
respective companies.
VMware, Inc.
3401 Hillview Ave.
Palo Alto, CA 94304
www.vmware.com
2 VMware, Inc.
Contents
About This Book 7
Revision History 7
Intended Audience 7
Document Feedback 7
Technical Support and Education Resources 8
1 Getting Started with VI Perl Toolkit 9
VI Perl Toolkit Architecture 9
Example Scenarios 10
VI Perl Toolkit Components 10
Common VI Perl Toolkit Tasks 11
VI Perl Toolkit Programming Conventions 11
VI Perl Toolkit Common Options 12
Specifying Options 12
Using a Session File 12
Setting Environment Variables 13
Using a Configuration File 13
Passing Parameters at the Command Line 13
Using Microsoft Windows Security Support Provider Interface (SSPI) 14
Common Options Reference 14
Examples for Specifying Connection Options 15
Example for Using a Session File 15
Example for Using a Configuration File 16
Example for Using the Command Line 16
Example for Using the SSPI Protocol 16
Hello Host: Running Your First Script 16
2 Writing VI Perl Toolkit Scripts 17
Basic VI Perl Toolkit Script Pattern 17
Understanding Server‐Side Objects 22
Using the Managed Object Browser to Explore Server‐Side Objects 22
Types of Managed Objects and the Managed Object Hierarchy 23
Managed Object Hierarchy 24
Managed Entities in the Inventory 24
Accessing Server‐Side Inventory Objects 25
Understanding Perl View Objects 26
Working with View Object Property Values 27
Accessing Property Values 27
Accessing Simple Property Values 27
Accessing Enumeration Property Values 27
Modifying Property Values 28
Creating Data Objects with Properties 28
VMware, Inc. 3
Programming Guide
Understanding Operations and Methods 29
Non‐Blocking and Blocking Methods 29
Examples of Operations 29
Calling Methods 29
Omitting Optional Arguments in Method Calls 30
Updating View Objects 30
3 Refining VI Perl Toolkit Scripts 33
Creating and Using Filters 33
Using Filters with Vim::find_entity_view() or Vim::find_entity_views() 33
Using Filters on the Utility Application Command Line 35
Retrieving the ServiceInstance Object on a VMware Infrastructure Host 35
Saving and Using Sessions 35
Saving Sessions 35
Loading Sessions 36
Using Multiple Sessions 36
Learning About Object Structure Using Data::Dumper 37
Specifying Untyped Arguments in Scheduled Tasks and Callbacks 39
Using Advanced Subroutines 39
Opts::get_config() 39
4 VI Perl Toolkit Subroutine Reference 41
Subroutines in the Opts Package 42
add_options 42
get_option 42
option_is_set 43
parse 43
validate 43
usage 43
Subroutines in the Util Package 43
connect 43
disconnect 44
get_inventory_path 44
trace 44
Subroutines in the Vim Package 44
clear_session 45
find_entity_view 45
find_entity_views 45
get_service_instance 46
get_service_content 46
get_session_id 46
get_view 46
get_views 46
load_session 47
login 47
logout 47
save_session 48
update_view_data 48
4 VMware, Inc.
Contents
Appendix: Web Services for Management Perl Library 49
Understanding Web Services for Management 49
Required Perl Modules 50
Sample Scripts 51
API Reference for Perl Modules 51
Constructing SOAP Messages with WSMan::WSBasic 51
Performing Generic CIM Operations with WSMan::GenericOps 55
Using the StubOps.pm Object‐Oriented Wrapper for Generic Operations 58
Using the Stubs Classes 61
Glossary 63
Index 65
VMware, Inc. 5
Programming Guide
6 VMware, Inc.
About This Book
This book, the Programming Guide, provides information about writing and running VMware® Infrastructure
(VI) Perl Toolkit scripts on ESX Server or VirtualCenter Server systems. Because toolkit subroutines allow you
to manage VI hosts using VMware Infrastructure API (VI API) calls, a brief description of the server‐side VI
object model is included. This guide focuses on explaining how to access and modify server‐side objects using
the VI Perl Toolkit and on discussing some programming techniques.
Revision History
This guide is revised with each release of the product or when necessary. A revised version can contain minor
or major changes. Table 1 summarizes the significant changes in each version of this guide.
20070105 First version of the documentation for the VI Perl Toolkit 1.0.
20080110 Update for VI Perl Toolkit 1.5. Documentation bug fixes and some clarifications and additions.
To view the most current version of this guide, go to http://www.vmware.com/support/pubs/sdk_pubs.html.
Intended Audience
This book is intended for administrators with different levels of Perl scripting experience:
All administrators can use the utility applications and sample scripts included with the VI Perl Toolkit to
manage and monitor the hosts in the VMware Infrastructure environment.
Experienced Perl programmers can examine the source code for the available scripts. They can then
modify those scripts or write new scripts using the VI Perl Toolkit subroutines to access the objects on the
VMware Infrastructure host and manipulate those objects using Perl. This document includes a
discussion of the VMware Infrastructure object model and explains how you can preview and retrieve
those objects and their attributes and methods.
Document Feedback
VMware welcomes your suggestions for improving our documentation. Send your feedback to:
docfeedback@vmware.com
VMware, Inc. 7
Programming Guide
http://www.vmware.com/support/pubs
Online Support
You can submit questions or post comments to the Developer Community: SDKs and APIs forum, which is
monitored by VMware technical support and product teams. To access the forum, go to:
http://communities.vmware.com/community/developer
Support Offerings
Find out how VMware support offerings can help meet your business needs. Go to:
http://www.vmware.com/support/services
http://mylearn1.vmware.com/mgrreg/index.cfm
8 VMware, Inc.
1
The chapter includes the following topics:
“VI Perl Toolkit Architecture” on page 9
“Common VI Perl Toolkit Tasks” on page 11
“VI Perl Toolkit Common Options” on page 12
“Hello Host: Running Your First Script” on page 16
The VI Perl subroutines they perform variations of these basic tasks:
Connect to remote host using user‐supplied connection parameters, and disconnect.
Find objects on the VMware Infrastructure host (server‐side objects). For example, find all virtual
machines on a host.
Retrieve or modify server‐side objects, for example, manage the virtual machine life cycle (start, stop,
suspend, and so on).
Collect information from server‐side objects.
Manage sessions.
Most routines retrieve a VI API object and make it available as a Perl object (called a view object) that you can
then manipulate with your script.
VMware, Inc. 9
Programming Guide
Example Scenarios
This section looks at two example scenarios.
Assume you want to use the toolkit to retrieve performance information for a host. You might perform the
following tasks:
Check the VI Perl Toolkit Utility Applications Reference or the /usr/lib/vmware-viperl/apps directory
(Linux) or Program Files\VMware\VMware VI Perl Toolkit\Perl\apps folder (Windows) for a
script that retrieves performance information.
NOTE All utility applications are fully supported. If you can’t find a utility application, you can also use
the scripts in the ./usr/share/doc/vmware-viperl/samples or Program Files\VMware\VMware
VI Perl Toolkit\Perl\samples folder. The samples scripts are not fully supported but meant as
starting points for your own scripts.
You find the viperformance.pl script, which retrieves performance counters from the host.
Call the script with the --help option or without any options to see its online documentation. For more
detailed information than that provided by --help, see the Utility Applications Reference available from
the VI Perl Toolkit documentation link at http://www.vmware.com/support//pubs/sdk_pubs.html.
To retrieve the information, call the viperformance.pl script with the name of the host, user name and
password for log in, an output filename, and the counters you want to retrieve:
viperformance.pl --url https://<host>:<port>/sdk/vimService --username nemo --password fi\$h
--host Aquarium --countertype net --interval 30 --samples 3
You must escape special characters in passwords on Linux. See Table 1‐2, “Options Available for all Perl
Toolkit Scripts,” on page 14 for a complete list of connection parameters.
Assume you want to use the toolkit for a task that you cannot perform using one of the utility applications.
Check the /samples folder for a sample script that performs a similar task. The scripts in the samples
folder are available for you to customize.
You can modify existing scripts or write your script using the Perl Toolkit subroutines.
For an in‐depth discussion of scripts that includes an example see “Writing VI Perl Toolkit Scripts”
on page 17.
To execute a VI Perl Toolkit subroutine, use the parameter name followed by its value, as follows:
Vim::subroutine(<parameter_name>=><value>, <parameter_name>=><value> );
Util::subroutine(<parameter_name>=><value>, <parameter_name>=><value> );
Opts::subroutine(<parameter_name>=><value>, <parameter_name>=><value> );
Any script you write can be called with the options listed in Table 1‐2, “Options Available for all Perl
Toolkit Scripts,” on page 14. If you want to specify additional options, you can use the mechanism
discussed in “(Optional) Define Script‐Specific Command‐Line Options” on page 18.
A complete Perl binding of the VI API, which makes all server‐side operations and data structures
available. The toolkit handles the data type mapping between server‐side and client‐side objects
transparently.
VMware Perl modules (VIRuntime.pl, VILib.pl) that provide subroutines for basic functionality.
10 VMware, Inc.
Chapter 1 Getting Started with VI Perl Toolkit
VI Perl Toolkit Utility Applications – Management applications that you can run, as is, in your virtual
data center. You execute each application with connection parameters and other, application‐specific
parameters. See the VI Perl Toolkit Utility Applications Reference.
Sample Scripts – Scripts that you can quickly adapt to your own needs, and use to learn more about the
VI Perl Toolkit’s functionality. Unlike the utility applications, the sample scripts are not supported by
VMware. You typically cannot use the sample scripts as is. You must know Perl to customize the samples.
Boolean data types – You send and receive Boolean values as follows:
Input, that is, sending from the client application:
false: Use 0, ʹ0ʹ, or ʹfalseʹ (capitalization ignored)
true: Use 1, ʹ1ʹ, or ʹtrueʹ (capitalization ignored)
Output, that is, receiving from the server:
false: Return value is 0
true: Return value is 1
To match Boolean values in a filter, use the strings true and false. See “Creating and Using Filters” on
page 33
Date/Time – The server returns a SOAP dateTime value. You can use the Date::Parse Perl module to
process these objects.
The VI Perl Toolkit accepts only native SOAP dateTime values using standard date time format with or
without fractional seconds, and with or without GMT (Z) time zone:
YYYY-MM-DDThh:mm:ssTZD, for example 1997-07-16T19:20:30+01:00
YYYY-MM-DDThh:mm:ss.sTZD, for example 1997-07-16T19:20:30.45+01:00
The Perl Toolkit always returns dateTime values in this format.
SOAP error message – When you see a SOAP error as a result of a call, there is most likely an error on the
server, not an error with the communication to the server.
VMware, Inc. 11
Programming Guide
For example, to power on a virtual machine using the vmcontrol.pl utility application, you must specify the
name of the virtual machine to power on, as follows:
perl vmcontrol.pl --server <myserver> --username <admin> --password <mypassword> --operation
poweron --vmname <virtual_machine_name>
Invoke any application or sample without any options or with --help to see its parameters and execution
examples. Information about common and script‐specific option is included.
Specifying Options
You can specify the common options in several different ways.
“Using a Session File” on page 12
“Using a Configuration File” on page 13
“Setting Environment Variables” on page 13
“Passing Parameters at the Command Line” on page 13
CAUTION Limit read access to a configuration file, especially if it contains user credentials.
The VI Perl Toolkit first processes any options that are set in the configuration file, next any environment
variables, and finally command‐line entries. This order of precedence always applies. That means, for
example, that you cannot override an environment variable setting by using a configuration file.
1 Connect to the directory where the script is located, for example, on Windows:
cd C:\Program Files\VMware\VMware VI Perl Toolkit\Perl\apps\session
2 Call save_session.pl. You must supply connection parameters and the name of a session file in which
the script can save an authentication cookie.
perl save_session.pl --savesessionfile <location> --server <server>
For example:
perl save_session.pl --savesessionfile C:\Temp\my_session --server my_server
If you specify a server but no user name or password, the script prompts you.
3 You can now call scripts in the \apps or \samples directory or your own scripts and pass in the session
file using the --sessionfile parameter as follows:
<command> --sessionfile <sessionfile_location> <command_options>
For example:
perl hostinfo.pl --sessionfile C:\Temp\my_session
NOTE If you use a session file, any other connection parameters are ignored.
12 VMware, Inc.
Chapter 1 Getting Started with VI Perl Toolkit
If a call to the server throws an exception, your application should terminate the session to avoid session leaks.
You could do this with an error handler that calls disconnect() or logout(), for example:
eval {
# ... insert program here ...
};
if (@$) {
print "Fatal error: $@";
Util::disconnect();
exit(1);
}
You can also use the _END_ pseudo‐signal handler to perform a disconnect, as follows:
$SIG{__END__} = sub { Util::disconnect(); }
For example:
set VI_SERVER=<your_server_name>
The following example shows the contents of a /root/.visdkrc configuration file:
VI_SERVER = <server>
VI_USERNAME = root
VI_PASSWORD = <root_password>
VI_PROTOCOL = https
VI_PORTNUMBER = 443
Do not escape special characters in the file that specifies environment variables.
Using a configuration file helps you repeatedly enter connection details. If you have multiple VirtualCenter
Server or ESX Server systems and you administer each system individually, you can create multiple
configuration files with different names. When you want to execute a command or a set of commands on a
server, you pass in the --config option with the appropriate filename at the command line.
Use --config if the configuration information is saved in a different file than ./visdkrc. If you specify
--config, the system ignores the ./visdkrc settings.
For example, you can run connect.pl as follows:
connect.pl --server <server> --username <privileged_user> --password <password>
Enclose passwords and other text with special characters in quotation marks. Special characters are characters
that have special meaning to the shell, such as ʹ$ʹ in Linux environments.
On Linux, use single quotes (ʹ ʹ), on Windows, use double quotes (ʺ ʺ).
On Linux, you can also use \ to escape special characters.
VMware, Inc. 13
Programming Guide
If toolkit commands and the VirtualCenter Server run on the same machine, a local account for the executing
user works. If they run on different machines, then the executing user must be an account in a domain trusted
by both machines.
SSPI supports a number of protocols. By default, it chooses the Negotiate protocol, which indicates that client
and server attempt to resolve a mutually supported protocol. Alternatively, you can use
--passthroughauthpackage to specify another protocol supported by SSPI. Kerberos, the Windows
standard for domain‐level authentication, is commonly chosen. If the VirtualCenter Server is configured to
accept only a specific protocol, specifying the protocol to VI Perl Toolkit commands with
--passthroughauthpackage might be required for successful authentication to the server.
If you use --passthroughauth, you don’t need to specify authentication information in any other way. For
example, to run connect.pl on the server, you can use the following command at the command line.
<command> <login_params> --passthroughauth
See the Microsoft Web site for a detailed discussion of SSPI.
--help Print a brief usage message. The message lists first each command‐specific option
and then the common options.
--passthroughauth When the VI Perl Toolkit runs, the system uses the Microsoft Windows Security
VI_PASSTHROUGHAUTH Support Provider Interface (SSPI) for authentication. You are not prompted for a
user name and password. See the Microsoft Web site for a detailed discussion of
SSPI.
This option is supported only if you are running Perl Toolkit on a Windows system
and connecting to a VirtualCenter Server.
--passthroughauthpackage Use this parameter in conjunction with --passthroughauth to specify a
<package> domain‐level authentication protocol to be used by Windows. By default, SSPI uses
VI_PASSTHROUGHAUTHPACKAGE= the Negotiate protocol, which means that client and server attempt to negotiate a
<package> mutually supported protocol.
If the VirtualCenter Server to which you are connecting is configured to use a
specific protocol, you can specify that protocol using this parameter.
This option is supported only if you are running Perl Toolkit on a Windows system
and connecting to a VirtualCenter Server.
14 VMware, Inc.
Chapter 1 Getting Started with VI Perl Toolkit
Table 1-2. Options Available for all Perl Toolkit Scripts (Continued)
Parameter and Environment
Variable Description
--password <passwd> Use the specified password (used in conjunction with --username) to log in to the
VI_PASSWORD=<passwd> server.
If ‐‐server specifies a VirtualCenter Server, the user name and password apply
to that server. No passwords are then needed to execute on the ESX Server hosts
that server manages.
If ‐‐server specifies an ESX Server host, the user name and password apply to
that server.
NOTE: Use the empty string (' ' on Linux and “ “ on Windows) to indicate no
password.
If you do not specify a user name and password on the command line, you are
prompted.
--version Display version information.
You can use the save_session.pl and load_session.pl scripts as examples for use of session files from
scripts.
VMware, Inc. 15
Programming Guide
If you have set up your system to run this file, you can execute scripts on the specified server afterwards.
NOTE The password is in plain text, so you must limit access to this file.
Linux
vminfo.pl --server <server> --user snow\-white --password dwarf\$ --vmname <name>
vminfo.pl --server <server> --user ‘snow-white’ --password ‘dwarf$’ --vmname <name>
Windows
vminfo.pl --server <server> --user “snow-white” --password “dwarf$” --vmname <name>
See “Using Microsoft Windows Security Support Provider Interface (SSPI)” on page 14.
Successful VI Perl Toolkit installation. See the VI Perl Toolkit Installation Guide for information.
Access to one of the supported VMware Infrastructure hosts. Perform a connection check using the
process described in “Using the Managed Object Browser to Explore Server‐Side Objects” on page 22.
1 At a command prompt, change to the /apps/general directory.
2 Execute connect.pl as follows:
connect.pl --url https://<host>:<port>/sdk/vimService --username myuser --password mypassword
The script returns an information message and the host time.
You are now ready to run other scripts, or create new scripts
NOTE You can invoke any utility application with ‐‐help to see information about its parameters.
16 VMware, Inc.
2
NOTE This chapter does not discuss Perl basics. You are expected to know Perl and understand its
programming conventions. For example, when you develop a VI Perl Toolkit script, you should follow Perl
standards for filenames, imports, and general processing flow. Use the appropriate filename extension for the
type of script or application you are creating (.pl on Windows and .pl or no suffix on Unix‐like systems).
The chapter includes these sections:
“Basic VI Perl Toolkit Script Pattern” on page 17
“Understanding Server‐Side Objects” on page 22
“Understanding Perl View Objects” on page 26
“Working with View Object Property Values” on page 27
“Understanding Operations and Methods” on page 29
“Updating View Objects” on page 30
Opts::add_options(%opts);
Opts::parse();
Opts::validate();
VMware, Inc. 17
Programming Guide
This module handles all client‐side infrastructure details. For example, it transparently maps data types and
provides local Perl interfaces to server‐side objects. The module also loads subroutines you can use to connect
to a VirtualCenter Server or ESX Server host, and to retrieve views. Views are the client‐side Perl objects that
encapsulate the properties and operations of server‐side managed objects. The subroutines are organized into
three different packages:
The Opts package includes subroutines for handling built‐in options and creating custom options.
The Util package includes subroutines that facilitate routine tasks, such as setting up and closing
connections to the server.
The Vim package includes subroutines for accessing server‐side managed objects, instantiating local proxy
objects (views), updating properties, and running local methods that result in operations on remote
servers.
See “VI Perl Toolkit Subroutine Reference” on page 41.
A number of common command‐line options, most of them connection options, are already defined for all
utility applications (see Table 1‐2, “Options Available for all Perl Toolkit Scripts,” on page 14). In addition,
most applications have application‐specific options you pass to the script at execution time.
The VI Perl Toolkit has defined all common options using attributes and subroutines specified in the Opts
package. You can similarly use the VILib::Opts package to create custom options for your own applications
and scripts, to simplify use of your script or to allow users to specify other information.
18 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
Example 2‐1 defines an entity option that must be made available to the script at runtime. The option
specifies which of the available entity types is passed as a parameter to the Vim::find_entity_views()
subroutine for further processing. Any direct or indirect subclasses of ManagedEntity are legal options (for
example HostSystem, ResourcePool, or VirtualMachine). The example creates new command‐line
options in two steps.
First the example declares the option as a hash, where the key is the option name, and the value is a
hashref containing Getopt::Long‐style option attributes (See Table 2‐1 for attribute details.)
Example 2‐1 creates a required command‐line option that accepts a string value, as follows:
my %opts = (
entity => {
type => "=s",
variable => "VI_ENTITY",
help => "ManagedEntity type: HostSystem, etc",
required => 1,
},
);
Then the example adds the option to the default options using the Opts::add_options() subroutine:
Opts::add_options(%opts);
Table 2‐1 lists all attributes you can use to define command‐line options. The code fragment in Step 1
above uses only type, variable, help, and required. For related information, see the documentation
for the Getopt::Long module.
func Enables creating derived options. Set func to an external code reference to execute the code when the
toolkit queries the value of the option.
help Descriptive text explaining the option, displayed in the script’s help message.
required If this attribute is set to 1, users must provide a value for this option or the script exits and display
the help message. Set to 1 to require a value. Set to 0 if value is optional.
variable Allows you to specify the option in an environment variable or a configuration file. See “Specifying
Options” on page 12.
type Uses Perl Getopt‐style syntax to specify option type and whether the option is required or optional.
Use double quotes to indicate that option doesn’t accept a value. The default numeric value is 0. The
default string value is ʺ ʺ (empty string). You can use one of the following:
Equal sign (=) — mandatory
Colon (:) — optional
s — string
i — integer
f — float
Finally, the example parses and validates the options before connecting to the server, as follows:
Opts::parse();
Opts::validate();
In Example 2‐1, the entity option is required, so the script cannot run unless the user passes in the option
name and value (see “Specifying Options” on page 12). The Vim::find_entity_views() subroutine uses the
value the user passes in later in the script. The value must be one of the managed‐entity types listed as
view_type parameter supported by Vim::find_entity_views().
NOTE Your script must call Opts::parse() and Opts::validate() to process the options available for all
scripts, even if you do not define script‐specific command‐line options.
VMware, Inc. 19
Programming Guide
When you attempt to run a script and do not supply all necessary options, the VI Perl Toolkit displays usage
help for the script, as in the following example:
C:\viperltoolkit>perl simpleclient.pl
Required command option 'entity' not specified
Common VI options:
. . .
Command-specific options:
--entity (required)
ManagedEntity type: ClusterComputeResource, ComputeResource, Datacenter,
Folder, HostSystem, ResourcePool, or VirtualMachine
To connect to the server, call Util::connect().
When a script reaches the call to Util::connect(), the VI Perl Toolkit runtime checks the environment
variables, configuration file contents, and command‐line entries (in this order) for connection options. If the
options are not defined, the runtime uses the defaults (localhost and no user name and password) to set up
the connection.
Example 2‐1 uses the Opts::get_option() subroutine to assign to $entity_type the string value of the
parameter that the user passes in when executing the script. Example 2‐1 then uses $entity_type as the
view_type parameter in the subsequent call to Vim::find_entity_views().
# get all inventory objects of the specified type
my $entity_type = Opts::get_option('entity');
my $entity_views = Vim::find_entity_views(view_type => $entity_type);
The Vim::find_entity_views() subroutine creates a local Perl object (an array of references) from the
server‐side managed object of the specified entity type.
NOTE This object is static and must be explicitly updated when the corresponding server‐side object changes.
Because views are Perl objects, you use Perl object‐oriented syntax to process the views. Example 2‐1 loops
through the array of entities returned (@$entity_views) and accesses the name property of each entity by
calling $entity_view->name. The example then prints the name of each entity to the console.
foreach my $entity_view (@$entity_views) {
my $entity_name = $entity_view->name;
Util::trace(0, "Found $entity_type: $entity_name\n");
}
See “Understanding Server‐Side Objects” on page 22.
20 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
use strict;
use warnings;
use VMware::VIRuntime;
# Parse all connection options (both built-in and custom), and then
# connect to the server
Opts::parse();
Opts::validate();
Util::connect();
1 Open a command prompt or console.
2 Change to the directory that contains the simpleclient.pl script.
3 Execute the script using the following syntax:
perl simpleclient.pl <conn_params> --entity <EntityType>
For example:
C:\viperltoolkit>perl simpleclient.pl --server aquarium.mycompany.com --username abalone
--password tank --entity HostSystem
Found HostSystem: lgto-1s-dhcp214.eng.vmware.com
VMware, Inc. 21
Programming Guide
The VI API Reference Guide gives reference documentation for all VI API objects. Some users might also find
the VMware Infrastructure SDK Programmer’s Guide helpful for understanding how the VI API objects interact.
The Guide is available from http://www.vmware.com/support/pubs/sdk_pubs.html.
This section first introduces the Managed Object Browser (MOB), which allows you to browse all objects on a
remote host. The rest of the section discusses how to work with these server‐side objects. You learn how to find
the objects, access and modify properties, and how to invoke a method on the server.
NOTE If the ESX Server host or VirtualCenter Server system uses HTTPS (the default), you need a user name
and password to log in to the MOB.
1 Start a Web browser.
2 Connect to the MOB using the fully‐qualified domain name (or the IP address) of the ESX Server host or
VirtualCenter Server, as follows:
https://<hostname.yourcompany.com>/mob
The browser prompts you for a user name and password for the host.
3 Enter the user name and password.
After you enter the user name and password, the host might display warning messages regarding the SSL
certificate authority, such as Website Certified by an Unknown Authority. If VMware is the
certificate authority, you can disregard such warnings and continue to log in to the MOB.
When you are successfully connected to the MOB, the browser displays the managed object reference for the
service (ManagedObjectReference:ServiceInstance), available properties (with values), and methods, as
shown in Figure 2‐1.
22 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
VMware, Inc. 23
Programming Guide
The different managed objects define the entities in the inventory as well as common administrative and
management services such as managing performance (PerformanceManager), finding entities that exist in the
inventory (SearchIndex), disseminating and controlling licenses (LicenseManager), and configuring alarms
to respond to certain events (AlarmManager). For a detailed discussion of managed objects, see the VI API
Reference.
A managed object reference (represented by a ManagedObjectReference) identifies a specific managed
object on the server, encapsulates the state and methods of that server‐side objects, and makes the state and
methods available to client applications. Clients invoke methods (operations) on the server by passing the
appropriate managed object reference to the server as part of the method invocation.
NOTE The VI API Reference Guide contains definitions of all server‐side objects and their properties and
methods. You can therefore use the VI API Reference Guide to identify the list of parameters and operations that
you can use with specific VI Perl Toolkit views that you create and manipulate in your code.
1 Find the VI API Reference Guide, which is included with the VI Perl Toolkit documentation.
2 Click All Types to see a list of all managed object types.
3 Find the ServiceContent object.
ServiceContent provides access services such as PerformanceManager and also contains references to
inventory objects, which allow you to access the entities such as hosts (HostSystem) and virtual machines
(VirtualMachine) in the virtual datacenter. ServiceContent properties allow you access to other
managed objects, for example:
The rootFolder property is a ManagedObjectReference to a Folder managed object type.
The perfManager property is a ManagedObjectReference to a specific instance of a
PerformanceManager managed object type, and so on.
NOTE The VI Client displays the hierarchy of inventory objects. The VI Client uses the information about the
objects (the properties and the relationships among them) for the display. For information about the VI Client
display, see the VMware Infrastructure 3 online library.
Datacenter – Contains other managed entities, including folders, virtual machines, and host systems. A
VirtualCenter Server instance can support multiple datacenters, but an ESX Server host supports only one
datacenter.
Folder – Contains references to other entities, for example, other folders (Folder) or hosts (HostSystem).
HostSystem – Provides access to a virtualization host platform.
VirtualMachine – Represents a single virtual machine.
ResourcePool – Allows you to combine CPU and memory resources from multiple hosts and establish
rules for dividing those resources among all virtual machines associated with these hosts.
24 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
ClusterComputeResource – Represents a cluster of HostSystem objects. Administrators create clusters
to combine the CPU and memory resources of hosts and to set up VMware HA or VMware DRS for those
clusters. See the Resource Management Guide, which is part of the VMware Infrastructure documentation
set, for more information.
ComputeResource –Abstracts a host system’s physical resources and allows you to associate those
resources with the virtual machines that run on the host.
Managed entities offer specific operations that vary depending on the entity type. For example, a
VirtualMachine managed entity provides operations for creating, monitoring, and controlling virtual
machines. You can power a virtual machine on or off (PowerOnVM, PowerOffVM) and you can capture state
(Snapshot). A HostSystem entity provides operations for entering and exiting maintenance mode
(EnterMaintenanceMode_Task, ExitMaintenanceMode_Task) and for rebooting the server
(RebootHost_Task).
The ManagedEntity base class includes several properties that are inherited by each subclass, such as a name
property, whose data type is a string. ManagedEntity also includes a few operations that are inherited by each
subclass (Destroy_Task, and Reload, for example). VirtualMachine and HostSystem extend the
ManagedEntity class, so each has a name property that it inherits from ManagedEntity.
Example 2‐1 obtains all entities of a specific type from the inventory. The entity type is passed as a parameter
to the Vim::find_entity_views() subroutine, which returns an array of references to view objects that map
to the corresponding server‐side entities.
Example 2‐3 starts at the level of the entire service and uses the Vim::get_service_content() subroutine
to obtain an instance of the ServiceContent object:
my $content = Vim::get_service_content();
You can use the ServiceContent object to retrieve a local view of the services provided by the server, as in
this example:
my $diagMgr = Vim::get_view(mo_ref => $content->diagnosticManager);
Example 2‐3 shows how these two calls form the basis of a script that follows changes in the log file, which can
be accessed as the logfile property of the diagnosticManager.
use VMware::VIRuntime;
# get ServiceContent
my $content = Vim::get_service_content();
my $diagMgr = Vim::get_view(mo_ref => $content->diagnosticManager);
VMware, Inc. 25
Programming Guide
# Get the last 5 lines of the log first, and then check every 2 seconds
# to see if the log size has increased.
my $start = $lineEnd - 5;
while (1) {
$log = $diagMgr->BrowseDiagnosticLog(
key => "hostd",
start => $start);
if ($log->lineStart != 0) {
foreach my $line (@{$log->lineText}) {
# next if ($line =~ /verbose\]/);
print "$line\n";
}
}
$start = $log->lineEnd + 1;
sleep 2;
}
Is a Perl object.
Includes properties and methods that correspond to the properties and operations of the server‐side
managed object.
Is a static copy of a server‐side managed object.
Must be explicitly updated when the object on the server changes. See “Updating View Objects” on
page 30.
Includes these additional methods (beyond the operations offered in the server‐side managed object):
An accessor method for each managed object property. The VI Perl Toolkit provides accessors for any
property, regardless of its depth inside a composite object structure.
A blocking and a non‐blocking method for each (non‐blocking) operation provided by the server‐side
managed object. See “Non‐Blocking and Blocking Methods” on page 29.
A method that updates the state of any client‐side view object with current data from the server. See
“Updating View Objects” on page 30.
View object properties correspond to properties of server‐side managed objects as follows:
Simple property types (strings, booleans, numeric datatypes, such as integers, floats, and so on)
become view object properties of the same name.
Arrays of properties become arrays of properties of the same name.
For each simple property (string, boolean, numeric data type), including inherited simple properties, the
toolkit creates an accessor method. The accessor method name is the same as the property name.
26 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
The VI Perl Toolkit simplifies programming as follows:
Provides a _this parameter to reference the object on which a method is invoked, if needed.
Allows you to pass a view object as a parameter to methods that take managed object references as
required parameter. The toolkit converts the view object to the corresponding managed object.
This section explains how to work with properties in the following sections:
“Accessing Property Values” on page 27
“Modifying Property Values” on page 28
“Creating Data Objects with Properties” on page 28
Simple data type, such as a string, boolean, numeric, or The ManagedEntity managed object has a name property
dateTime. of type string.
Array of simple data types or data objects. A HostSystem managed object contains an array of virtual
machines that are hosted by the corresponding physical
machine.
Enumeration (enum) of predefined values. The values can A virtual machine’s power state can be one of only three
be a collection of simple data types or data objects. possible string values such as poweredOn, poweredOff, or
suspended.
Complex data types called data objects that are part of the AboutInfo, Action, and ServiceContent are all data
VMware Infrastructure object model. objects.
As shown in Example 2‐1, you can access the name property of entity_view calling its name method, as
follows:
my $entity_name = $entity_view->name;
For example, the power state of a virtual machine (powerState) is a member of the runtime data object.
To retrieve the value of powerState, you must dereference the two containing objects (the view object and the
runtime data object) and the value (val) itself, as follows:
$vm_view->runtime->powerState->val
VMware, Inc. 27
Programming Guide
Because powerState is an enumeration, you use runtime->powerState->val to retrieve its string value.
foreach my $vm (@$vm_views) {
if ($vm->runtime->powerState->val eq 'poweredOn') {
print "Virtual machine " . $vm->name . " is powered on.\n";
}
else {
print "Virtual machine " . $vm->name . " is not powered on.\n";
}
$data_object is a blessed reference to a Perl object or class name, and property is a method call on the object.
For example, you can change the force property to false, as follows:
$host_connect_spec->force ('false');
To create an enumeration data object, use a string value as the argument to the enumeration type’s constructor.
my $power_state = VirtualMachinePowerState->new('poweredOff');
Typically, enumerations are used as arguments to methods:
$vm->MigrateVM(
host => $target_host,
priority => VirtualMachineMovePriority->new('defaultPriority'),
state => VirtualMachinePowerState->new('poweredOff'),
);
For example, creating a virtual machine requires the creation of a data structure that includes a number of
nested data objects. One of those is a VirtualMachineFieldInfo data object, which can be constructed as
follows:
my $files = VirtualMachineFileInfo->new
(
logDirectory => undef,
snapshotDirectory => undef,
suspendDirectory => undef,
vmPathName => $ds_path
);
The VirtualMachineFileInfo object is then contained within a VirtualMachineConfigSpec object:
my $vm_config_spec = VirtualMachineConfigSpec->new(
name => $args{vmname},
memoryMB => $args{memory},
files => [ $files, ] # <-- here
numCPUs => $args{num_cpus},
guestId => $args{guestid},
deviceChange => \@vm_devices
);
This code is taken from the vm/vmcreate.pl utility application. See the scripts in the apps and samples
directories for examples of both simple and complex uses of data objects.
28 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
To set the value of a property that is defined as an enumeration, you must pass the new value to the data object
as follows:
$ref = new enum_type ('val');
For example, you can change the power state as follows:
$power_state = new VirtualMachinePowerState ('poweredOff');
The VI Perl Toolkit provides a corresponding non‐blocking method, and also provides a blocking
(synchronous) method (<opname>() method).
Non‐blocking methods – Asynchronous methods that return control to the client immediately after
invocation and also return a task object to the calling program.
Blocking methods – Synchronous methods that fully process the invoked operation before returning
control to the client script. Does not return a reference to a task object.
Using blocking methods and using non‐blocking methods each has advantages and disadvantages. If you use
a blocking methods, you don’t have to handle a task object with additional code. Non‐blocking methods allow
you to do the following:
Monitor progress (of the *_Task object) outside the main processing logic of the script, which can be
especially useful during potentially long‐running operations, such as creating virtual machines.
Interleave local (client‐side) processing and server‐side processing.
Examples of Operations
The following table lists some of the operations available for a VirtualMachine managed object.
PowerOnVM_Task() PowerOnVM()
CloneVM_Task() CloneVM()
SuspendVM_Task() SuspendVM()
See the VI API Reference Guide for lists of all methods for each managed object.
Calling Methods
After you have retrieved the view object that corresponds to a managed object, you can invoke methods on
that view to make use of the managed object’s services. You invoke a method by specifying the method name
parameter, for example:
$vm->MigrateVM (name => 'productionVM');
The type of parameter required by the method depends on the operation defined in the VI API. It might be a
simple type, data object, or managed object reference.
For information about specific parameters and data types, see the VI API Reference Guide.
VMware, Inc. 29
Programming Guide
Blocking operations are invoked as methods on a view object. For example, to suspend a virtual machine, call:
$vm_view->SuspendVM();
You can execute any operation that is defined for a managed object as a method on a corresponding view
object.
Because the VI Perl Toolkit creates an accessor and a mutator method (getter and setter method) for each
property defined in the managed object, you can reference the name of any property as a method call of the
view, for example:
my $network_name = $network_view->name
The VI Perl Toolkit allows you to pass a view object to a method that requires a ManagedObjectReference.
For example, if you have the view that represents a host ($host), you can pass the view to the powerOn()
method as follows:
my $host = Vim::find_entity_view (view_type => 'HostSystem',
name => 'my host');
my $vm = Vim::find_entity_view (view_type => 'VirtualMachine',
name => 'my virtual machine');
$vm->powerOn (host => $host)
NOTE “Specifying Untyped Arguments in Scheduled Tasks and Callbacks” on page 39 discusses using the
VI Perl Toolkit PrimType structure in some calls.
You can omit the argument:
$vm->PowerOnVM(host => $host); # with the optional host argument
$vm->PowerOnVM(); # without the optional host argument
You can supply undef as the value of the optional argument:
$vm->PowerOnVM(host => undef);
Supplying undef as the value of the optional argument is useful in cases where the value of an argument,
which might or might not be undef, is contained in a variable:
my $host = Vim::find_entity_view(
view_type => 'HostSystem',
filter => { name => 'preferredHost' }
);
$vm->PowerOnVM(host => $host);
You cannot use the empty string or the value 0 to represent undef or an unset parameter.
30 VMware, Inc.
Chapter 2 Writing VI Perl Toolkit Scripts
VMware, Inc. 31
Programming Guide
32 VMware, Inc.
3
“Creating and Using Filters” on page 33
“Retrieving the ServiceInstance Object on a VMware Infrastructure Host” on page 35
“Saving and Using Sessions” on page 35
“Using Multiple Sessions” on page 36
“Learning About Object Structure Using Data::Dumper” on page 37
“Specifying Untyped Arguments in Scheduled Tasks and Callbacks” on page 39
“Using Advanced Subroutines” on page 39
When you call Vim::find_entity_views(), the command might return more objects than you want to work
with, for example all virtual machines in a datacenter. When you call Vim::find_entity_views() the first
object found might not be the one you’re looking for. For example, you might want to retrieve only those
virtual machine objects whose names begin with a certain prefix. You can apply one or more filters to the
Vim::find_entity_view() and Vim::find_entity_views() subroutines to select a subset of objects based
on property values.
To apply a filter to the results of Vim::find_entity_view() or Vim::find_entity_views(), you supply an
optional filter parameter. The value of the parameter is an anonymous hash reference containing one or
more pairs of filter criteria. Each of the criteria is a property path and a match value. The match value can be
either a string or a regular expression object. If the match value is a string, the value of the property must match
it exactly (including case). To match Boolean values, use the strings true and false.
The following filter parameter matches a virtual machine power state of poweredOff:
filter => { 'runtime.powerState' => 'poweredOff' }
VMware, Inc. 33
Programming Guide
You can also match using a regular expression object, generally known as a qr// (quoted regular expression)
object. In this case, the value of the property must match the regular expression. The following filter
parameter that matches objects whose names begin with Test:
filter => { 'name' => qr/^Test/ }
filter => { 'name' => qr/^test/i } # make the match case-insensitive with the i option
For more about the qr// operator, see the perlre (perl regular expressions) and perlop man pages in the
standard Perl documentation.
The following example illustrates how you might use Vim::find_entity_views() in combination with a
filter. It prints a list of virtual machine objects whose guest operating system names contain the string
Windows.
Example 3-1. Filter that Creates Views of Windows-Based Virtual Machines Only
. . .
my $vm_views = Vim::find_entity_views(
view_type => 'VirtualMachine',
filter => {
# True if string 'Windows' appears anywhere in guestFullName
'config.guestFullName' => qr/Windows/
}
);
# Print VM names
foreach my $vm (@$vm_views) {
print "Name: " . $vm->name . "\n";
}
. . .
If you pass multiple filter criteria to Vim::find_entity_view() or Vim::find_entity_views(), the
method returns only the managed objects for which all criteria match. The filter parameter specified in
Example 3‐2 includes two criteria, so the example returns only virtual machines that fulfill both requirements:
Guest operating system is Windows — the config property’s guestFullName property includes the
string Windows.
Virtual machine is running — power state is poweredOn.
NOTE You can match only properties that have simple types like strings and numbers. Specifying a property
with a complex type as an argument to a filter results in a fatal runtime error. For example, you can’t specify
the runtime property of a VirtualMachine object, which is a complex object rather than a string.
34 VMware, Inc.
Chapter 3 Refining VI Perl Toolkit Scripts
Matches only the host santa.clara, not the hosts santa-clara or santa$clara.
When you invoke a utility application, you must escape the characters forward slash (/), backward slash (\),
and percent (%) as %2f, %5c, and %25 respectively when they appear in virtual machine names. Elsewhere,
you do not have to escape these characters. You should single‐quote percent (%) on Unix‐like command lines.
For example, to search for the virtual machine San-Jose/5, execute this command:
perl vminfo.pl --username Administrator --password 'secret' --server myserver --vmname
'San-Jose%2f5'
If you want to retrieve the current time, you must retrieve a ServiceInstance object and call its
CurrentTime() method. You can use the Vim::get_service_instance() subroutine to retrieve the object.
1 Connect to the VMware host:
Util::connect();
2 Retrieve the ServiceInstance object:
my $service_instance = Vim::get_service_instance();
3 Retrieve the current host time:
$service_instance->CurrentTime();
Saving Sessions
You can save a session using the usual subroutine call syntax as follows:
Vim::save_session():
...
# usual login procedure with connect()
Util::connect();
...
# save the global session in file .mysession
Vim::save_session(session_file => '.mysession');
VMware, Inc. 35
Programming Guide
Alternatively, you can use save_session() with the object‐oriented syntax (see “Using Multiple Sessions” on
page 36):
...
# object-oriented login
my $service_url = "https://$server/sdk/vimService";
my $vim = Vim->new(service_url => $service_url);
$vim->login(user_name => $username, password => $password); ...
# save session $vim in file .mysession
$vim->save_session(session_file => '.mysession');
The session remains active until either a log out or disconnect operation is invoked, or until it times out. Time
out is 30 minutes after the last operation was performed.
Loading Sessions
You use load_session() to load a saved session into the global session as follows:
Vim::load_session(session_file => '.visession');
Alternatively, you can load a session using the object‐oriented syntax as follows:
my $service_url = "https://$server/sdk/vimService";
my $vim = Vim->new(service_url => $service_url);
$vim = $vim->load_session(session_file => '.visession');
Each time an application connects to a server in the VMware Infrastructure environment, a session between
the application and the server is created. The VI Perl Toolkit represents the session as a Vim object, which is a
VI Perl Toolkit object. When you use single sessions, there is one global Vim object, which is implicit for single
sessions.
For multiple objects, you cannot use the implicit global Vim object. Instead, you must create and use Vim
objects explicitly, and use an object‐oriented syntax for calling Perl Toolkit methods.
You create an open session in two stages.
1 Create a Vim object using the new() constructor.
2 Log in by calling the object‐oriented login() method. The arguments to the object‐oriented login()
method are the same as for the procedural Vim::login() call.
Most procedural Vim:: methods have an object‐oriented counterpart. The procedural methods operate on an
implicitly specified global Vim object. The object‐oriented methods operate on the explicitly supplied Vim
object.
The following code fragment from /samples/sessions/multisession.pl illustrates how to use multiple
sessions, using the object‐ oriented programming style in VI Perl Toolkit.
use VMware::VIRuntime;
...
# create vim object for each host
my @vim_objs;
my $url;
$url = Opts::get_option('url');;
push @vim_objs, Vim->new(service_url => $url);
$url = Opts::get_option('url2');
push @vim_objs, Vim->new(service_url => $url);
36 VMware, Inc.
Chapter 3 Refining VI Perl Toolkit Scripts
if (Opts::option_is_set('username2')) {
$username = Opts::get_option('username2');
}
if (Opts::option_is_set('password2')) {
$password = Opts::get_option('password2');
}
$vim_objs[1]->login(user_name => $username, password => $password);
# logout
foreach my $vim_obj (@vim_objs) {
$vim_obj->logout();
}
Lines 12 through 14 set the following parameters of Data::Dumper to make it easier to understand the output:
Sortkeys orders the name‐value pairs alphabetically by name.
Deepcopy enables deep copying of structures. In general, deep copying ensures that the output is
straightforward and tree‐like.
Indent set to 2 causes Data::Dumper to take hash key length into account in the output. The indent
results in a more readable format.
08 Opts::parse();
09 Opts::validate();
10 Util::connect();
11
12 $Data::Dumper::Sortkeys = 1; #Sort the keys in the output
13 $Data::Dumper::Deepcopy = 1; #Enable deep copies of structures
14 $Data::Dumper::Indent = 2; #Output in a reasonable style (but no array indexes)
15
16
17
18 # Get the view for the target host
19 my $host_view = Vim::find_entity_view(view_type => 'HostSystem');
20
21 print "The name of this host is ", $host_view->name . "\n\n";
22
VMware, Inc. 37
Programming Guide
When you execute the entire program, it produces detailed output. The output from line 23 looks as follows:
$VAR1 = bless( {
'apiType' => 'HostAgent',
'apiVersion' => '2.0.0',
'build' => '31178',
'fullName' => 'VMware ESX Server 3.0.1 build-31178',
'localeBuild' => '000',
'localeVersion' => 'INTL',
'name' => 'VMware ESX Server',
'osType' => 'vmnix-x86',
'productLineId' => 'esx',
'vendor' => 'VMware, Inc.',
'version' => '3.0.1'
}, 'AboutInfo' );
The output above shows the content of the summary.config.product property of a HostSystem managed
object. The type (or more properly class) of summary.config.product property is AboutInfo. Perl’s
Data::Dumper module writes out the object in a form that can be used with eval to get back a copy of the
original structure. The bless keyword indicates the data is a Perl object, and the last argument to bless is the
class of the object, AboutInfo.
Line 19 (in Example 3‐3) retrieves the HostSystem view object and line 21 prints the name associated with the
corresponding host.
The config property has more values than those printed by line 23. Line 25 prints out the entire config object.
Inside the config object printed by line 25 (in Example 3‐3), the product property is an object. The bless
function returns a reference to the product object, which is itself nested inside the config object.
$VAR1 = bless( {
'name' => 'test-system.eng.vmware.com',
'port' => 'nnn',
'product' => bless( {
'apiType' => 'HostAgent',
'apiVersion' => '2.0.0',
'build' => '31178',
'fullName' => 'VMware ESX Server 3.0.1 build-31178',
'localeBuild' => '000',
'localeVersion' => 'INTL',
'name' => 'VMware ESX Server',
'osType' => 'vmnix-x86',
'productLineId' => 'esx',
'vendor' => 'VMware, Inc.',
'version' => '3.0.1'
}, 'AboutInfo' ),
'vmotionEnabled' => 'false'
}, 'HostConfigSummary' );
The output from line 27 of Example 3‐3 prints the structure of the entire summary object of the host view. There
are a number of nested objects, including two objects that are nested two levels deep. The product object is
nested inside the config object, and the connectionState object is nested inside the runtime object.
38 VMware, Inc.
Chapter 3 Refining VI Perl Toolkit Scripts
In a limited number of circumstances, you might deal with parts of the VI API that use callback methods.
Because of the way Perl Toolkit maps the VI API into Perl, you have to specify arguments to callback methods
differently from the way you specify arguments to other methods.
You must specify the arguments positionally, in the order defined in the bindings for other languages like
Java
You must indicate the type of each argument using the PrimType constructor.
For example, consider a scheduled task that periodically creates a snapshot. The CreateSnapshot() method
takes four arguments, name, description, memory, and quiesce, which you must define before you use them
by creating four MethodActionArgument objects with PrimType values, as follows:
my $name = MethodActionArgument->new(
value => PrimType->new('Sample snapshot task', 'string')
);
my $description = MethodActionArgument->new(
value => PrimType->new('Created from a sample script', 'string')
);
my $memory = MethodActionArgument->new(
value => PrimType->new(0, 'boolean')
);
my $quiesce = MethodActionArgument->new(
value => PrimType->new(0, 'boolean')
);
You use the MethodActionArgument objects in the order defined in the positional API, not with the usual
name => $value syntax. You can then supply the four values defined above as arguments to
CreateSnapshot().
my $snapshot_action = MethodAction->new(
name => "CreateSnapshot",
argument => [
$name,
$description,
$memory,
$quiesce
]
);
The complete example is in doc/samples/schedule_task/vm_snapshot_schedule.pl (Linux) and in
VMware VI Remote CLI\Perl\samples\scheduled_task\vm_snapshot_schedule.pl (Windows).
Opts::get_config()
Allows you to determine whether a configuration file was read when VI Perl Toolkit executed
Opts::parse().
This subroutine has no parameters.
Returns
If a configuration file was successfully opened, Opts::get_config() returns the path to it. If no
configuration file was found, or if it could not be opened, Opts::get_config() returns undef.
VMware, Inc. 39
Programming Guide
40 VMware, Inc.
4
The Opts package includes subroutines for handling built‐in options and creating custom options. See
“Subroutines in the Opts Package” on page 42.
The Util package includes subroutines to facilitate routine tasks, such as setting up and closing
connections to the server. See “Subroutines in the Util Package” on page 43.
The Vim package includes subroutines for accessing server‐side managed objects, instantiating local view
objects, updating properties, and run local methods to invoke operations on remote servers.
add_options Enables custom options to be parsed and validated for execution in the context of the script to which the
options have been added.
get_option Retrieves the value of the specified built‐in or custom option.
option_is_set Checks whether an option has been explicitly set by a script or from the command line or whether the
option has a default or computed value (that is, the return value of a func).
parse Reads options from the command line, environment variable, or configuration file and transforms into
appropriate data structures for validation.
validate Ensures that input values are complete, consistent, and valid.
usage Displays a help text message associated with the option.
clear_session Terminates the current session loaded by the load_session() subroutine.
find_entity_view Searches the inventory tree for a managed object that matches the specified entity type.
find_entity_views Searches the inventory tree for managed objects that match the specified entity type.
get_service_instance Retrieves a ServiceInstance object, which can be used to query the server time or to retrieve the
ServiceContent object.
get_service_content Retrieves properties of the service instance enabling access to the service’s managed objects.
get_session_id Retrieves a session ID.
get_view Retrieves the properties of a single managed object.
get_views Retrieves the properties of a set of managed objects.
load_session Uses a saved session file for connecting to a server.
login Establishes a session with the Web service running on the VMware Infrastructure host.
VMware, Inc. 41
Programming Guide
logout Disconnects the client from the server and closes the connection to the Web service.
save_session Saves a session cookie, which is a text file.
update_view_data Refreshes the property values of a view object.
connect Establishes a session by using the token provided in a previously‐saved session file, or by using the user
name and password provided on the command line, in environment variables, or in a configuration file.
disconnect If used in conjunction with connect (and a session file), does nothing. If used in conjunction with a user
name and password, logs out and closes the session.
get_inventory_path Returns the inventory path for the specified managed entity.
trace General‐purpose logging function used in conjunction with the --verbose command‐line option.
“add_options” on page 42
“get_option” on page 42
“option_is_set” on page 43
“parse” on page 43
“validate” on page 43
“usage” on page 43
add_options
Enables custom options to be parsed and validated for execution in the context of the script to which the
options have been added.
Parameters
%opts – Name of the hash variable that comprises the option name and its attributes.
This subroutine returns nothing.
get_option
Retrieves the value of the specified built‐in or custom option.
Parameters
option_name – String value of the built‐in or custom option.
Returns
Returns one of the following, depending upon the attributes defined for the option:
Return value of func (after execution) if a function is associated with the option
Default value, if one is specified for the option
Value of the option as passed to the script
Undef, if none of the above are specified
42 VMware, Inc.
Chapter 4 VI Perl Toolkit Subroutine Reference
option_is_set
Checks whether an option has been explicitly set by a script or from the command line or whether the option
has a default or computed value (that is, the return value of a func).
Parameters
option_name – String value of the built‐in or custom option.
Returns
Boolean. Returns 1 (true) if the option value has been explicitly set. Returns 0 (false) if the option value is a
default value, is null, or has not been explicitly set. For a discussion of Boolean, see “VI Perl Toolkit
Programming Conventions” on page 11.
parse
Reads options from the command line, environment variable, or configuration file and transforms into
appropriate data structures for validation.
This subroutine takes no parameters.
This subroutine returns nothing. It displays an error message and quits if the parse operation is not successful.
If you attempt to use a configuration file, you can call Opts::get_config() to make sure it can be opened.
See “Opts::get_config()” on page 39.
validate
Ensures that input values (from the command line, environment variable, or configuration file) are complete,
consistent, and valid.
This subroutine takes no parameters.
This subroutine returns nothing. It displays an error message and quits if the parse operation is not successful.
usage
Displays a help text message associated with the option.
This subroutine takes no parameters and returns nothing.
“connect” on page 43
“disconnect” on page 44
“get_inventory_path” on page 44
“trace” on page 44
connect
Establishes a session with the VirtualCenter Server or ESX Server Web service by using the token provided in
a previously saved session file, or by using the user name and password provided using the command line,
environment variables, or a configuration file.
This subroutine returns nothing.
VMware, Inc. 43
Programming Guide
Parameters
user_name – User account on the ESX Server or VirtualCenter Server system.
password – Password for the user account.
session_file – Full path and filename for the token saved from a previous successful connection. Use
session_file (instead of user_name and password) to reestablish a session to the same server, or to
establish a new connection to a different server.
disconnect
If used in conjunction with connect (and a session file), does nothing. If used in conjunction with a user name
and password, logs out and closes the session.
This subroutine has no parameters and returns nothing.
get_inventory_path
Returns the inventory path for the specified managed entity, for example, Folder, Datacenter, HostSystem,
VirtualMachine, ComputeResource, ClusterComputeResource, or ResourcePool. The resulting
inventory path can later be passed to the SOAP operation FindByInventory path to retrieve the
ManagedObjectReference for a managed entity (from which a view can be created).
Parameter
view – Managed entity view.
Returns
String that identifies the inventory path of the managed entity.
trace
General‐purpose logging function used in conjunction with the --verbose command‐line option. If not
specified, the default log level is 0. Passing the --verbose flag without a value sets the level to 1.
This subroutine returns nothing.
loglevel – Numeric value. If not specified, default is 0.
message – A string that will be printed for the associated loglevel value.
“clear_session” on page 45
“find_entity_view” on page 45
“find_entity_views” on page 45
“get_service_instance” on page 46
“get_service_content” on page 46
“get_session_id” on page 46
“get_view” on page 46
“get_views” on page 46
“load_session” on page 47
“login” on page 47
“logout” on page 47
“save_session” on page 48
“update_view_data” on page 48
44 VMware, Inc.
Chapter 4 VI Perl Toolkit Subroutine Reference
clear_session
Terminates the current session loaded by the load_session() subroutine.
This subroutine takes no parameters and returns nothing.
find_entity_view
Searches the inventory tree for a managed entity that matches the specified entity type. The search begins with
the root folder unless the begin_entity parameter is specified.
Parameters
view_type – Managed entity type specified as one of these strings:
“ClusterComputeResource”
“ComputeResource”
“Datacenter”
“Folder”
“HostSystem”
“ResourcePool”
“VirtualMachine”
begin_entity (optional) – Managed object reference that specifies the starting point for the search (in the
context of the inventory). This helps you narrow the scope.
filter (optional) – A hash of one or more name‐value pairs in which the name represents the property
value to test and the value represents a pattern the property must match. If more than one pair is present,
all the patterns must match.
Returns
Reference to a view object containing the same properties as the managed entity. If there is more than one
managed entity that matches the specified entity type, the subroutine returns only the first managed entity
found. If no matching managed entities are found, the subroutine returns undef.
find_entity_views
Searches the inventory tree for managed objects that match the specified entity type.
Parameters
view_type – Managed entity type specified as one of these strings:
“ClusterComputeResource”
“ComputeResource”
“Datacenter”
“Folder”
“HostSystem”
“ResourcePool”
“VirtualMachine”
begin_entity (optional) – Managed object reference that specifies starting point for search (in context of
inventory).
filter (optional) – A hash of one or more name‐value pairs, in which the name represents the property
value to test and the value represents a pattern the property must match. If more than one pair is present,
all the patterns must match.
VMware, Inc. 45
Programming Guide
Returns
A reference to an array of view objects containing static copies of property values for the matching inventory
objects. If there are no matching entities, the array is empty.
get_service_instance
Retrieves a ServiceInstance object, which can be used to query the server time or to retrieve the
ServiceContent object.
This subroutine takes no parameters.
Returns
Returns a ServiceInstance object.
get_service_content
Retrieves properties of the service instance enabling access to the service’s managed objects. Alternatively, you
can use get_views(), get_view(), and other subroutines to access the objects more directly. If you start with
the service content to work with the Web service, you can navigate to the object of interest.
This subroutine has no parameters.
Returns
Reference to ServiceContent object, which contains managed object references to all inventory content,
including the root folder.
get_session_id
Allows you to retrieve the session ID corresponding to the current session.
This subroutine has no parameters.
Returns
Session ID cookie for use by load_session().
get_view
Retrieves the properties of a single managed object.
Parameters
mo_ref – A managed object reference, obtained from a property of another managed object or a view.
view_type (optional) – The type of view to construct from the managed object. If the parameter is absent,
the subroutine constructs a view with a type that matches the name of the managed object type.
Returns
A view object containing static copies of the property values for a managed object.
get_views
Retrieves the properties of a set of managed objects.
Parameters
mo_ref_array – A reference to an array of managed object references.
view_type (optional) – The type of view to construct from the managed object. If the parameter is absent,
the subroutine constructs a view with a type that matches the name of the managed object type.
46 VMware, Inc.
Chapter 4 VI Perl Toolkit Subroutine Reference
Returns
A reference to an array of view objects containing copies of property values for multiple managed objects.
Notes
The Vim::get_views() subroutine takes a reference to an array of managed object references and returns a
reference to an array of view objects. Although the array can contain multiple managed‐object types, objects
of only one type can be obtained at the same time.
load_session
Uses a saved session file or session cookie for connecting to a server. Use Util::connect() instead of
Vim::login() after loading the session.
You can use save_session() to get a session file or get_session_id() to get a session ID.
Returns
Returns the Vim object instance.
Parameters
service_url – URL of the server to which the client connects (optional if use session_file).
session_id – Session ID returned by get_session_id(). You must specify either session_file or
session_id.
Example
To load a session using a session file: load_session(session_file => $filename);
login
Establishes a session with the Web service running on the VirtualCenter Server or ESX Server host using the
credentials (user name, password) provided via command‐line, environment variables, or configuration file.
NOTE In most cases, you use Util::connect() to establish a connection.
Returns
Returns the Vim object instance.
Parameters
service_url – The URL of the server to which the client connects.
user_name – User account on the ESX Server or VirtualCenter Server system.
password – Password for the user account.
logout
Disconnects the client from the server and closes the connection to the Web service. Use this subroutine if you
connected using Vim::login(). Otherwise, use Util::disconnect().
This subroutine takes no parameters and returns nothing.
VMware, Inc. 47
Programming Guide
save_session
Allows you to save a session cookie, which is a text file. See “Using a Session File” on page 12 and “Example
for Using a Session File” on page 15.
This subroutine returns nothing.
Parameters
session_file – Full path and filename where the token should be saved. Times out after 30 minutes. You
pass in the filename as a hash.
Example
save_session (session_file => $filename);
update_view_data
Refreshes the property values of a view object.
This subroutines takes no parameters and returns nothing.
48 VMware, Inc.
Appendix: Web Services for
Management Perl Library
Web Services for Management (WS‐Management) provides a common way for systems to access and exchange
management information across the IT infrastructure.
ESX Server 3 supports WS‐Management by implementing over a dozen CIM (Common Information Model)
profiles. CIM profiles are a set of object‐oriented schemas defined by the DTMF (Distributed Management
Task Force). CIM defines how managed elements in a networked environment are represented as a common
set of objects and relationships that users can view, share, and control. For example, system management client
applications might be able to check the status of server components such as CPU, fans, power supplies, and
so on.
The WS‐Management Perl Library allows you to write scripts that retrieve CIM data from the ESX Server using
CIMOM, a service that provides standard CIM management functions over a WBEM (Web‐Based Enterprise
Management). WBEM is s standard protocol for passing CIM‐XML messages over HTTP.
Although you can use this library with other available WS‐Management‐enabled CIMOMs, this appendix
limits discussion to using the library with the CIMOM available on ESX Server 3i, ESX Server 3.5, and
VirtualCenter 2.5.
This appendix discusses these topics:
“Understanding Web Services for Management” on page 49
“Required Perl Modules” on page 50
“Sample Scripts” on page 51
“API Reference for Perl Modules” on page 51
Traditionally, clients uses the CIM‐XML protocol for CIMOM access, but more recently, the DMTF has been
promoting Web Services for Management (WS‐Management), a SOAP‐based protocol for accessing CIM data.
The Perl library discussed in this appendix is an implementation of WS‐Management client artifacts (stubs,
bindings) for connecting to a WS‐Management server and obtaining CIM data.
ESX Server 3i is compatible with version 2.17.1 of the CIM schema, and with version 1.0.0 of the SMASH
standard. For a list of specific profiles implemented, see the SMASH Programming Guide.
For more information about CIM, SMASH, and WS‐Management, visit the DMTF at http://www.dmtf.org.
VMware, Inc. 49
Programming Guide
SOAP::Lite – At least version 0.67.
UUID – At least version 0.02.
Data::Dump – At least version 1.07.
If the system you are using is behind a firewall, make sure that your http_proxy and ftp_proxy environment
variables are set properly before proceeding with the following instructions for Windows or Linux.
NOTE If you use one of the supported Linux distributions, the modules are included with the VI Perl Toolkit
and you do not have to install them.
1 Determine which version of Perl you are using by issuing the perl -v command.
For version 5.6, type the following at the command prompt:
C:\>ppm install http://theoryx5.uwinnipeg.ca/ppmpackages/SOAP-Lite.ppd
For version 5.8, type the following at the command prompt:
C:\>ppm install http://theoryx5.uwinnipeg.ca/ppms/SOAP-Lite.ppd
2 Issue the following command to install UUID:
C:>ppm install UUID
3 Issue the following command to install Data::Dump:
C:>ppm install Data-Dump
1 Open a terminal window and enter the following commands for remote access to CPAN (comprehensive
Perl archive network):
$ sudo -s
# perl -MCPAN -e shell
2 Issue the following command at the CPAN prompt to install SOAP::Lite:
cpan> install SOAP::Lite
Answer any questions and the module installs.
3 Go to http://search.cpan.org, search for UUID, and download the latest source. Untar the downloaded file,
open a terminal window, and go to the untarred directory. Issue the following commands to install UUID:
# make
# make test
# make install
If the make displays errors about missing items, install uuid-dev with apt-get on Debian‐based systems
or e2fsprogs-dev[el] on other systems.
4 Open a terminal window and issue the following commands to install Data::Dump:
# perl -MCPAN -e shell
cpan> install Data::Dump
After downloading, unzipping, and installing the VI Perl Toolkit, you’ll find the artifacts and samples listed in
Table A‐1 in the VI Perl Toolkit installation directory in the following location:
50 VMware, Inc.
Appendix: Web Services for Management Perl Library
Perl/samples/WSMan Sample Perl scripts that use the WS‐Management library to obtain information through the
CIMOM of an ESX Server 3.5, ESX Server 3i, or VirtualCenter Server system. Sample
programs let you check sensor health, obtain firmware revision levels, list field‐replaceable
units, and list power supply details. See Table A‐2, “Sample Scripts Located in the
/samples/WSMan Sub‐directory of the VI Perl Toolkit Installation,” on page 51.
Perl/lib/WSMan/Stubs Proxy code (stubs) that handle the mapping between server‐side and client‐side objects.
Sample Scripts
You can run the sample scripts as is. You can use the scripts as starting point for writing your own Perl scripts
to obtain CIM data from the server. If you accepted the defaults during VI Perl Toolkit installation, the samples
are in the following location on a Windows system:
C:\Program Files\VMware\VMware VI Perl Toolkit\Perl\samples\WSMan
You can run the samples like other VI Perl Toolkit samples or utility applications using this basic syntax:
perl <scriptname.pl> --server <servername> --username <username> --password <password>
For example:
perl firmwarerevisions.pl --server my.FQDN.esx35server.com --username root --password root_pass
If --server is not specified, it defaults to localhost. If you’re connecting to a remote host and do not specify
a user name and password, you are prompted.
The CIMOM service listens for requests on port 80.
Table A-2. Sample Scripts Located in the /samples/WSMan Sub-directory of the VI Perl Toolkit Installation
Script Description
checksensorhealth.pl Returns a list of sensors associated with all system devices.
firmwarerevisions.pl Obtains a list of firmware revisions on the system.
listfrus.pl Returns a list of all field‐replaceable units on the system.
listpowersupplies.pl Obtain status of discrete sensors associated with all power‐supplies. Demonstrates
traversing associations and using GetInstance.
Name
WSMan::WSBasic
Synopsis
$client = WSMan::WSBasic->new(%args);
$client->register_xml_ns(%args);
$client->register_class_ns(%args);
$client->_get_uuid();
$client->Identify();
$client->Enumerate(%args);
$client->PullRelease(%args);
$client->Get(%args);
VMware, Inc. 51
Programming Guide
Description
You can use the WSBasic class in this model to construct SOAP messages for communicating with the
WS‐Management server. All operations return deserialized SOAP::SOM objects from which you can extract the
fault code or the SOAP replies.
Under normal circumstances, you do not use this module directly. Instead, you use the GenericOps module
built on top of this WSBasic, which supports generic operations as defined by the DMTF standards. See
“Performing Generic CIM Operations with WSMan::GenericOps” on page 55. If you want to use the
SOAP::SOM library directly, see the CPAN documentation for SOAP::SOM.
Currently, the WSBasic class provides the following methods:
new
Constructor that takes a hash argument containing key‐value pairs. For example:
$client = WSMan::WSBasic->new( address => 'http://www.abc.com/',
port => '80',
path => 'wsman',
username => 'wsman',
password => 'secret',
namespace => 'root/cimv2', #optional
timeout => '60' #optional
);
The constructor takes the following arguments:
register_xml_ns
Registers extra XML namepaces that might be required for proprietary tags in the SOAP message. Under
normal circumstances, calling this method is not required. The argument to this method is a hash
containing prefixes to be used as keys, and relative URLs to be used as values. For example, this line
declares a prefix wsen with the URL http://www.dmtf.org/wsen in the global XML namespace:
$client->register_xml_ns((wsen => 'http://www.dmtf.org/wsen'));
register_class_ns
Registers extra CIM namepaces that the WS‐Management server might require. By default, the
constructor provides a set of namespaces for CIM classes. Review the server configuration files to see if
other CIM namespaces are required. The usage is the same as for register_xml_ns.
52 VMware, Inc.
Appendix: Web Services for Management Perl Library
Identify
Performs the wsmid:Identify operation, which causes the WS‐Management server to identify itself. The
method takes no arguments. The method returns a SOAP::SOM object, which you can use to parse the
results or do error correction.
Enumerate
Allows you to filter results differently depending on the optional arguments you pass in. Several
arguments perform generic operations that are implemented in another class, as described in “Performing
Generic CIM Operations with WSMan::GenericOps” on page 55. Other arguments implement
enumeration for non‐standard‐compliant servers. This section discusses the most common arguments. To
understand other arguments that can be passed to the Enumerate method, look at the Perl code. The
Enumerate method returns a SOAP::SOM object that can be used to either check for errors
($result->fault) or to parse the results ($result->result). The SOAP object includes header and
data in XML format. Enumerate accepts the following arguments:
PullRelease
An overloaded method that performs a Pull operation or a Release operation. PullRelease takes these
arguments:
Get
Retrieves an instance of a class. Takes the following named arguments:
VMware, Inc. 53
Programming Guide
Dependencies
The WSMan::WSBasic module requires the following Perl modules:
SOAP::Lite – Version 0.65 or later is required by the WSMan::WSBasic to form SOAP messages and to
parse XML replies that are received from the WS‐Management server.
UUID – Required to generate UUIDs for the SOAP messages.
Code Examples
You can use the WSMan::WSBasic module to do a simple Enumerate and Pull operation:
#!/usr/bin/perl -w
use strict;
use WSMan::WSBasic; #Import the module.
To use one of the enumeration modes like EnumerateEPR or EnumerateEPRandObject, call the Enumerate
operation with EnumerationMode enabled. You could also do this in the constructor call.
$result = $client->Enumerate(class_name => 'CIM_Processor',
#namespace => 'root/cimv2', #if needed.
enummode => 'EnumerateEPR'
);
To perform operations on vendor‐specific classes, you must register them first with the client. The actual URL
depends on your WS‐Management software.
$client->register_class_ns(Linux => 'http://www.dmtf.org/linux');
54 VMware, Inc.
Appendix: Web Services for Management Perl Library
Name
WSMan::GenericOps
Synopsis
$client = WSMan::GenericOps->new(%args)
$client->register_xml_ns(%)
$cleint->register_class_ns(%)
$client->Identify()
$client->EnumerateInstances(%args)
$client->EnumerateInstanceNames(%args)
$client->EnumerateAssociatedInstances(%args)
$client->EnumerateAssociatedInstanceNames(%args)
$client->EnumerateAssociationInstances(%args)
$client->EnumerateAssociationInstanceNames(%args)
$client->GetInstance(%args)
Description
The GenericOps module implements some of the generic operations specified in the WS‐Management CIM
bindings published by the DMTF. Not all generic operations are currently implemented.
The WSBasic module provides more primitive intrinsic WS‐Management operations. See “Constructing
SOAP Messages with WSMan::WSBasic” on page 51.
The following methods are defined by the GenericOps class:
new
Constructor that takes a hash argument containing key‐value pairs in the following form:
$client = WSMan::GenericOps->new(( address => 'http://www.abc.com/',
port => '80',
path => 'wsman',
username => 'wsman',
password => 'secret',
namespace => 'root/cimv2', #optional
timeout => ‘60’ #optional
));
The constructor has the following arguments:
VMware, Inc. 55
Programming Guide
register_xml_ns
Registers extra XML namepaces that might be required for proprietary tags in the SOAP message. Under
normal circumstances, calling register_xml_ns is not required, unless you are trying to extend the class
itself. The argument to this method is a hash containing prefixes to be used as keys, and relative URLs as
values. For example, this line declares a prefix wsen with the URL http://www.dmtf.org/wsen in the
global XML namespace:
$client->register_xml_ns((wsen => 'http://www.dmtf.org/wsen'));
register_class_ns
Registers extra CIM namepaces that the WS‐Management server might require. By default, the
constructor provides a set of namespaces for CIM classes. Review the server configuration files to see if
other CIM namespaces are required. The usage is the same as for register_xml_ns.
Identify
Performs the wsmid:Identify operation, which causes the WS‐Management server to identify itself. This
is particularly useful to check whether the server is up and running.
The method takes no arguments. The method prints a fault string if a fault occurs, or returns the reply sent
by the server. The reply is a hash reference containing the parsed reply in key‐value pairs.
EnumerateInstances
Enumerates the instances of a given class. The method returns a list of hashes containing the parsed reply
from the server, or prints a fault string from the server if an error occurs. The common way to use the
method is as follows:
$client->EnumerateInstances(
class_name => 'CIM_Processor',
namespace => 'root/cimv2' #optional
)
EnumerateInstanceNames
Enumerates only the key values of the instances of a given class. Like EnumerateInstances, this method
returns a list of hashes containing the parsed reply from the server, with keys only, or prints a fault string
if an error occurs. The call to this method is similar to EnumerateInstances.
EnumerateAssociatedInstances
Returns the instances related to the source object through an association. Results are filtered differently
depending on optional arguments. A typical way to use the method is as follows:
$client->EnumerateAssociatedInstances(
class_name => 'CIM_Foo',
selectors => \%hash;
associationclassname => 'CIM_Bar', #optional
role => 'CIM_Baz', #optional
resultclassname => 'CIM_Bat', #optional
resultrole => 'CIM_Quux', #optional
includeresult => \%hash, #optional
namespace => 'root/cimv2' #optional
)
This method has the following arguments:
56 VMware, Inc.
Appendix: Web Services for Management Perl Library
EnumerateAssociatedInstanceNames
Returns objects with only the key values of the associated instance populated. The usage is the same as
for EnumerateAssociatedInstances.
EnumerateAssociationInstances
Returns objects containing association instances of which the class is a part. The usage is the same as for
EnumerateAssociatedInstances.
EnumerateAssociationInstanceNames
Returns objects containing key values of the association instances of which the class is a part. The usage
is the same as for EnumerateAssociatedInstances.
GetInstance
This method gets a particular instance of a class. It prints a fault string or returns the result in a hash. The
method takes the following named arguments:
Dependencies
The WSMan::GenericOps module requires the WSMan::WSBasic module.
VMware, Inc. 57
Programming Guide
Name
WSMan::StubOps
Synopsis
$client = WSMan::StubOps->new(%args)
$client->register_xml_ns(%)
$client->register_class_ns(%)
$client->Identify()
$client->EnumerateInstances(%args)
$client->EnumerateInstanceNames(%args)
$client->EnumerateAssociatedInstances(%args)
$client->EnumerateAssociatedInstanceNames(%args)
$client->EnumerateAssociationInstances(%args)
$client->EnumerateAssocitionInstanceNames(%args)
$client->GetInstance(%args)
Description
The StubOps module provides a wrapper for generic operations so that replies to queries to the server can be
returned as Perl objects rather than as hashes. Each of these objects has accessor methods associated with each
object variable, and a set of common methods. These objects are Meta Object Format (MOF) files compiled into
Perl modules. MOF was developed by the Object Management Group (OMG). See “Required Perl Modules”
on page 50.
The following methods are defined by the StubOps class:
new
Constructor that takes a hash argument containing key‐value pairs in the following form:
$client = WSMan::StubOps->new(( address => 'http://www.abc.com/',
port => '80',
path => 'wsman',
username => 'wsman',
password => 'secret',
namespace => 'root/cimv2', #optional
timeout => '60' #optional
));
The constructor takes the following arguments:
58 VMware, Inc.
Appendix: Web Services for Management Perl Library
register_xml_ns
Registers extra XML namepaces that might be required for proprietary tags in the SOAP message. Under
normal circumstances, calling this method is not required, unless you are trying to extend the module
itself. The argument to this function is a hash containing prefixes to be used as keys, and relative URLs as
values. For example, this line declares a prefix wsen with the URL http://www.dmtf.org/wsen in the
global XML namespace:
$client->register_xml_ns((wsen => 'http://www.dmtf.org/wsen'));
register_class_ns
Registers extra CIM namepaces that the WS‐Management server might require. By default, the
constructor provides a set of namespaces for CIM classes. Review the server configuration files to see if
other CIM namespaces are required. The usage is the same as for register_xml_ns.
Identify
Performs the wsmid:Identify operation, which causes the WS‐Management server to identify itself. The
method is useful to check whether the server is up and running. The method takes no arguments. It either
prints a fault string, if a fault occurs, or returns the reply sent by the server. The reply is an object of the
type IdentifyResponse. You can get all the key‐value pairs from the reply either by using the object as
a normal hash, or if you know the names of the keys, using the get() method to obtain values by passing
in the key names, in string form, as an argument to the method. For convenience, the object also contains
the to_string() method to convert the whole object into a string.
EnumerateInstances
Enumerates the instances of a given class. The method yields a list of objects returned by the server, or
prints a fault string from the server if one occurs. A common way to use the method is as follows:
$client->EnumerateInstances(
class_name => 'CIM_Processor',
namespace => 'root/cimv2' #optional
)
That query returns all instances of the CIM_Processor object returned by the server. For an explanation
of methods that can be called on the returned objects, see descriptions under “Using the Stubs Classes”
on page 61.
EnumerateInstanceNames
Enumerates only the key values of instances of a given class. Like EnumerateInstances, this method
yields a list of objects returned from the server, or prints a fault string if an error occurs. The objects
returned have only the key values populated. The call to this method is similar to EnumerateInstances.
For an explanation of methods that can be called on returned objects, see “Using the Stubs Classes” on
page 61.
EnumerateAssociatedInstances
Returns the instances related to the source object through an association. Results are filtered differently
depending on optional arguments. A typical way to use the method is as follows:
$client->EnumerateAssociatedInstances(
objectpath => $some_objectpath_of_an_instance,
associationclassname => 'CIM_Bar', #optional
role => 'CIM_Baz', #optional
resultclassname => 'CIM_Bat', #optional
resultrole => 'CIM_Quux', #optional
includeresult => \%hash, #optional
namespace => 'root/cimv2' #optional
)
VMware, Inc. 59
Programming Guide
EnumerateAssociatedInstanceNames
Returns objects with only the key values of the associated instance populated. The usage is the same as
for EnumerateAssociatedInstances.
EnumerateAssociationInstances
Returns the object containing association instances of which the class is a part. The usage is the same as
for EnumerateAssociatedInstances.
EnumerateAssociationInstanceNames
Returns the object containing key values of the instances of which the class is a part. The usage is the same
as for EnumerateAssociatedInstances.
GetInstance
Gets a particular instance of a class. Returns the requested object, or prints the fault string, and takes the
following named arguments:
60 VMware, Inc.
Appendix: Web Services for Management Perl Library
Dependencies
The WSMan::StubOps module requires the following modules:
WSMan::WSBasic
WSMan::GenericOps::Data::Dump
Name
The Stubs directory in the VMware installation folder contains Perl modules that are object‐oriented Perl
representations of various MOF (Meta Object Format) models.
Description
The Stubs directory contains most of the classes supported by VMware. The stubs are compiled directly from
MOF files into Perl classes. There are over 600 Perl modules in the Stubs directory and each of them is a
meta‐object class translated into a Perl class. These modules are also called stubs in this document.
Under normal circumstances, you do not create instances of these stubs directly; they are used by methods in
the StubOps module. See “Using the StubOps.pm Object‐Oriented Wrapper for Generic Operations” on
page 58.
All the stubs inherit class objects from Initializable.pm, which contains methods for initializing the classes
as well as some common methods required by all classes.
new
Instantiates a class. When you invoke the method with no arguments, all the fields in the class are
initialized to undef. To set the fields to a particular value, pass in the fields with the desired values as a
hash containing the key value pairs.
clone
You can call this method on any of the instantiated objects and it returns an exact copy of the object. You
can use this method as a deep copy mechanism for the objects.
to_string
Serializes an object into a string. You can pass this string to the print function for display on standard
output, or it can be parsed by eval to produce a clone of the object.
get_selectorset
Returns the key values that define a unique instance of an object as a hash reference.
accessors
Every stub has a separate accessor method for each of the variables in the class. The accessor name is the
same as the variable name. If you call the accessor without arguments, it returns the present value of the
variable. If you call the accessor with an argument, the value of the variable is set to the passed‐in value
and the modified value is returned.
For example, consider Processor to be an instance of CIM_Processor. The CIM_Processor class has a
class variable called DeviceID. To access the value of DeviceID, call the accessor method on the
Processor instance as Processor->DeviceID, which returns the value of the DeviceID variable. To
change the value of this variable, call the accessor method as follows, which changes the present value to
4.0 and also returns this changed value:
Processor->DeviceID('4.0');
VMware, Inc. 61
Programming Guide
Instantiating Stubs
Under normal circumstances, you are not required to instantiate any of the stubs. However, if the need arises,
you can import stubs into your script with the following implied syntax: WSMan::Stubs::CIM_Processor.
After importing the module you must instantiate the new object as follows:
my $processor = CIM_Processor->new;
Note the lack of leading package identifier WSMan::Stubs:: in this instantiation statement (a shortcut).
62 VMware, Inc.
Glossary
A appliance
See virtual appliance.
D data object
Complex data type that consists of properties and values only (no operations or methods). Data objects
are used throughout the VI API to capture or reflect the state of various properties of managed objects. As
implemented in the VI API, data objects are analogous to structures (structs) in C, C++, and other
programming languages.
H hash
One or more key‐value pairs that define the attributes and their values.
I inventory
The collection of all managed entities on the server, that is, of all instances of HostSystem, Datacenter,
VirtualMachine, ResourcePool, ComputeResource, ClusterComputeResource, and Folder.
M managed entity
One of the managed object types that extends the ManagedEntity managed object.
The ManagedEntity managed object type is an abstract class that defines the base properties and methods
for VMware Infrastructure objects, the same kinds of manageable components found in a physical IT
infrastructure, such as datacenters and hosts.
managed object
A server‐side type that encapsulates properties and operations available on the server. Different managed
objects offer different services (operations, methods). From the highest level, the various managed object
types on the server define common administrative and management services one would expect to use in
a typical datacenter, services such as managing performance (PerformanceManager), finding entities
that exist in the inventory (SearchIndex), disseminating and controlling licenses (LicenseManager), and
configuring alarms to respond to certain events (AlarmManager).
managed object reference
A type of data object that enables distributed computing for the VMware Infrastructure environment. A
managed object reference identifies a specific managed object on the server, and encapsulates the state
and methods of server‐side objects, making them available to client applications. Clients invoke methods
(operations) on the server by passing the appropriate managed object reference (mo_ref) to the server, in
the method invocation.
MOB (Managed Object Browser)
A Web‐based application hosted on all VMware ESX Server hosts and VirtualCenter Server systems. The
MOB lets you explore the objects on the system and obtain information about each object’s properties and
methods.
VMware, Inc. 63
Programming Guide
V VI API
A set of Web services, hosted on ESX Server and VirtualCenter Server host systems, that provides
interfaces to VMware Infrastructure components such as hosts, virtual machines, and data centers and
operations on these components.
view
A client‐side Perl object that the VI Perl Toolkit has populated with the state of one or more server‐side
managed objects. Client applications and scripts work with view objects rather than with the managed
entities that exist on the server. To create a view, call the appropriate VI Perl Toolkit subroutine
(Vim::get_view, Vim::get_views, and so on) with the managed object reference for the entity of
interest.
virtual appliance
A virtual appliance is a virtual machine that is prepackaged with an operating system and a set of
applications.
virtualization
Separation of a resource‐ or service‐request from the underlying physical delivery of that service.
Virtualization provides an abstraction layer between computing resources, physical storage, networking
hardware and the applications that use these resources. Virtualization can greatly enhance the computing
environment, optimizing the use of available physical components. For example, virtual memory enables
computer software to use more memory than is physically installed, via the background swapping of data
to disk storage. Virtualization techniques can be applied to all layers of an IT infrastructure such as
networks, storage, laptop or server hardware, operating systems, and applications.
VI SDK
The package of components (WSDL, sample code, and other artifacts) required for developing Java, C#,
or other Web‐services‐enabled client applications that invoke operations on the Web‐services‐based
VI API.
64 VMware, Inc.
Index
A error messages 11
AlarmManager managed object 24 example scenarios 10
architecture 9 examples
configuration files 16
B SSPI protocol 16
blocking methods 26, 29 executing subroutines 10
Boolean data types 11
Boolean values F
filter 33 filters
command-line 35
C in script 33
CIM 49 multiple filter example 34
CIMON 49 Folder managed entity 24
ClusterComputeResource managed entity 25
command-line H
connection parameters 13 --help option 10
filters 35 HostSystem managed entity 24
parameters 13
command-line options I
importing modules 18
defining 18
inventory objects 24
Common Information Model 49
ISO-8859-1 encoding 14
common options, precedence 12
components 10
L
ComputeResource managed entity 25 LicenseManager managed object 24
configuration files 13, 16
connecting to server 20 M
cp936 encoding 14 Managed Object Browser 22
current time 35 managed objects
hierarchy 23
D retrieving 20
Data::Dumper 37
ManagedObjectReference 22
Datacenter managed entity 24
Meta Object Facility models 61
dateTime objects 11
methods
defining command-line options 18
blocking 29
Distributed Management Task Force 49
calling 29
DTMF 49
introduction 29
non-blocking 29
E
omitting optional arguments 29
encodings
MOB 22
cp936 14
modules
ISO-8859-1 14
importing 18
Shift_JIS 14
required 50
enumeration property values
VMware Perl modules 10
accessing 27
WS-Management Perl modules 51
environment variables 13
MOF models 61
setting 13
multiple sessions 36
VMware, Inc. 65
Programming Guide
N Shift_JIS 14
new options Shift_JIS encoding 14
attribute list 19 simple property values, accessing 27
type attribute 19 SOAP error messages 11
non-blocking methods 26, 29 SSL certificate authority warning 22
non-blocking operations 29 SSPI protocol 16
subroutines
O executing 10
operations 29 reference 41
optional method arguments 29
options T
parsing 19 technical support resources 8
validating 19 time 35
Opts package 18 type attribute 19
Opts::get_option() 20
Opts::parse() 19 U
undef method argument 30
Opts::validate() 19
update_view_data() 30
P Util package 18
parsing options 19 Util::connect() 20
Passing 13 utility application 11
PerformanceManager managed object 24
precedence for options 12 V
validating options 19
programming conventions 11
VI API 9
property values
VI Perl Toolkit
accessing 27
architecture 9
modifying 28
components 10
property values, accessing 27
runtime 10
R view objects 20
ResourcePool managed entity 24 accessor 26
runtime engine 10 blocking method 26
characteristics 26
S updating 30
samples 11 VIM package 18
save_session.pl 12 Vim::find_entity_view() 33
--savesessionfile 12 Vim::find_entity_views() 20, 25
SearchIndex managed object 24 Vim::get_service_content() 25
servers Vim::update_view_data 30
checking status 49 viperformance.pl 10
connecting 20 virtual machines
server-side objects 22 powering on 12
server-side operations 29 VirtualMachine managed entity 24
ServiceContent object 24 VMware 10
ServiceInstance object 35
session files 12 W
expiration 12 web services for management 49
using 12 WSMan Stubs classes 61
--sessionfile 12 WSMan::GenericOps 55
sessions WSMan::StubOps 58
expiration 36 WSMan::WSBasic 51
multiple 36 ws-management 49
saving 35
using 35
66 VMware, Inc.