VMware logo

VMware Infrastructure (VI) Perl Toolkit Programming Guide

PRINT

The VMware Infrastructure (VI) Perl Toolkit provides an easy-to-use Perl scripting interface to the VMware Infrastructure (VI) API. Administrators and developers who may be more comfortable with Perl (rather than with Java, C#, or other programming languages) can easily leverage the power of the VI API for managing their virtual infrastructure. Better still, the VI Perl Toolkit includes numerous ready-to-run Utility Applications that can be put to use immediately.

The VI Perl Toolkit is a client-side framework from VMware that simplifies the programming effort associated with the VI API and server-side object model. For developers who have previously worked with the Scripting API (specifically, the VmPerl API), the VI Perl Toolkit is the tool of choice.

For information about installing the VI Perl Toolkit, see the VI Perl Toolkit Installation Guide.

This Programming Guide includes these topics:

  1. Preface
  2. Introduction to the VI Perl Toolkit
  3. Developing VI Perl Toolkit Scripts
  4. Advanced Topics
  5. VI Perl Toolkit Subroutine Reference Table
  6. Glossary

1. Preface

The VI Perl Toolkit simplifies access to the VMware Infrastructure API (VI API)—the Web-services-based API for programmatically managing virtual infrastructure components. This Programming Guide:

Using any of the Utility Applications requires only minimal understanding of the server-side object model and the VI API. However, writing your own scripts requires some basic knowledge of Perl. For more information about Perl, see:

Technical Support and Education Resources

VMware provides numerous support and educational resources. See the support page at:

Online Support

You can submit questions or post comments to the VMware Management APIs (VI SDK, VI Perl, CIM SDK) discussion forum, which is monitored by VMware technical support and product teams.

VMware Education Services

VMware education services offers technical training that includes extensive hands-on labs, case study examples, and course materials designed to be used as on-the-job reference tools. For more information about VMware Education Services, go to

Resources for Developers

Here are some links to various resources, including developer forums, user groups, and product pages.

Developer Resources http://www.vmware.com/support/developer
Discussion forums http://www.vmware.com/community
Product information http://www.vmware.com/products/
User groups http://www.vmware.com/vcommunity/usergroups.html
VMTN Knowledge Base http://www.vmware.com/support/kb
VMware Infrastructure technical publications http://www.vmware.com/support/pubs/vi_pubs.html
VMware Technology Network http://www.vmtn.net

Contacting VMware

VMware welcomes your suggestions for improving technical publications. You can email your feedback to:

docfeedback@vmware.com

2. Introduction to the VI Perl Toolkit

The VI Perl Toolkit lets you automate a wide variety of virtual-infrastructure administrative, provisioning, and monitoring tasks. For example, you can quickly obtain a list of all virtual machines in your virtual data center and obtain performance statistics. If a host system is over-burdened, you can migrate virtual machines as needed, to better distribute the load.

As a Perl interface, the VI Perl Toolkit brings the power of VMware Infrastructure API to anyone familiar with the scripting capabilities of Perl. You’ll have full access to the VI API and object model, albeit through an easy-to-use Perl interface. In addition, for handling some of the most common management and automation tasks, the VI Perl Toolkit includes several Utility Applications that can be integrated into your management environment, as is—you don’t need to learn anything about the VI Perl Toolkit or its underpinnings to use these Utility Applications.

What’s in the VI Perl Toolkit?

The VI Perl Toolkit provides:

Requirements

To use the VI Perl Toolkit, you need access to an ESX Server (3.x) or VirtualCenter Management Server (2.x) system. ESX Server 2.5.x is also supported as long as it is being managed by a VirtualCenter Management Server 2.x system.

See the VI Perl Toolkit Installation Guide for complete requirements.

Subroutine Libraries

The VI Perl Toolkit includes several subroutine libraries, one of which includes built-in options to simplify passing command-line syntax. The Utility Applications all use this VILib::Opts library.

perl app_name.pl --optionname optionvalue

You will need to know the server name, username, and password to run the applications. Depending on the nature of the application, you may also need to pass other parameters to the command line. For example, powering-on virtual machines using the vmcontrol Utility Application requires you to provide the name of the virtual machine whose power status you want to change:

perl vmcontrol.pl --server myserver --username admin --password password --operation poweron --vmname myvmname

You can provide the required parameters to VI Perl Toolkit utility applications in several different ways:

The VI Perl Toolkit runtime processes options set in the config file first, environment variables next, and command-line entries last. As shown in the example above, you can use a combination of these three approaches.

For example, assuming that most of your administrative chores take place through a central VirtualCenter Management Server, you can create a configuration file for executing applications and avoid repeatedly entering connection details. If you have multiple VirtualCenter Management Server or ESX Server systems and you need to administer them individually, you can create multiple configuration files using different names for each and then simply pass the --config option with the appropriate filename when you run the applications.

Furthermore, each option can be set in multiple ways. Since command-line flags take precedence over environment variables, and environment variables take precedence over settings in the configuration file, you can easily over-ride any parameter when necessary.

Table 1: Built-in Parameters and Variables
ParameterVariableDescription
configVI_CONFIG Specify non-default name or location for the VI Perl Toolkit configuration file. Default name and location for Linux is ~/.visdkrc and for Windows is %HOME%\visdk.rc.
help~ Displays usage information about a script or application to standard output (command console).
passwordVI_PASSWORDPassword for the specified username. Sucessful authentication with username and password returns a session object that can be saved and used for subsequent connections using the same or different script. See sessionfile.
portnumberVI_PORTNUMBERPort used for server connection.
protocolVI_PROTOCOLProtocol used to connect to server. Default is HTTPS. If the server has been configured for HTTP, set to HTTP.
serverVI_SERVERESX Server or VirtualCenter Management Server host to which you want the application or script to connect. Default is localhost if none specified.
servicepathVI_SERVICEPATHService path for server connection. Default is /sdk/webService.
sessionfileVI_SESSIONFILEName of file containing the token saved from successful login. Alternative to specifying username and password. Sessions time out after 30 minutes of inactivity.
urlVI_URLComplete URL for SDK connection. An alternative to specifying protocol, server, and servicepath as individual connection parameters. For example, perl app_name.pl --url https://myserver.mycompany.com/sdk --username root --password mypassword
usernameVI_USERNAMEUser account that has privileges to connect to the server.
verboseVI_VERBOSEIncrease loglevel. Use in conjunction with Util::trace subroutine to display additional debugging information. By default, value of --verbose (loglevel) is 0.
version~Displays script version information, if available.

3. Developing VI Perl Toolkit Scripts

To develop VI Perl Toolkit scripts, you must have basic familiarity with Perl scripting techniques. You will also need some basic understanding of the VI API and the server-side object model: It is this object model that is abstracted by the VI Perl Toolkit runtime. Some of the basics are covered in this section.

Topics in this section include:

Basic VI Perl Toolkit Script Pattern

Generally, you should follow common Perl approaches for filename, imports, and general processing flow. Use the appropriate filename extension for the type of script or application you are creating (.pl for Perl library, .pm for Perl module, for example), with the proper declarations.

The basic pattern for any VI Perl Toolkit is:

  • Step 1:  Import the VI Perl Toolkit runtime Perl modules.

  • Step 2:  Create custom options, if needed, and then parse and validate both built-in and custom options before connecting to the server.

  • Step 3:  Connect to the server.

  • Step 4:  Obtain client-side Perl view objects that contain static copies of server-side managed objects of interest, that you want to manipulate or monitor.

  • Step 5:  Process the view objects in your client script using common Perl scripting techniques, invoking methods on the views (local Perl objects) to effect changes on the server-side managed objects and reporting results, as appropriate.

  • Step 6:  Close the connection.

More detailed information about each step in this basic pattern as demonstrated in Listing 1, simpleclient.pl, is provided in the next several sub-sections.

 

Step 1: Import the VI Perl Toolkit Modules

Any Perl script you write using the toolkit should include these these two modules:

use VMware::VIRuntime;
use VMware::VILib;

These two modules, directly or indirectly, handle all client-side infrastructure details—for example, transparently mapping data types and providing local Perl interfaces to objects on the remote service. They also provide subroutines for connecting to ESX Server and VirtualCenter Management Server systems, and for obtaining views, the client-side Perl objects that encapsulate the properties and operations of server-side managed objects and entities. These subroutines are organized into three different packages:

See VI Perl Toolkit Subroutines Reference for complete details.

The basic syntax for invoking any of the subroutines from these packages is to use the parameter name followed by its value:

Step 2: Create Custom Options [Optional]

All the options specified in the Utility Applications have been defined using attributes and subroutines specified in the VILib::Opts package. You can use this same library to create your own custom options for your applications and scripts, to simplify use of your script, or to provide more flexibility beyond that provided with the built-in options listed in Table 1: Built-in Parameters and Variables.

For example, as shown in Listing 1, the ’entity’ option requires script users to specify at runtime which of the 7 entity types will be passed as a parameter to the get_entity_views() subroutine for further processing.

  1. Define the option as a hash—a series of key-value pairs that define the option attributes and specifications. (In other programming languages, a hash is called an associative array, so the key name is used to reference and access associated value (order is not important). See Table 2 for attribute details.) Listing 1 creates a required command-line option that will accept a string value for entity name:
    my %opts = (
        entity => {
        type => "=s",
        variable => "VI_ENTITY",
        help => "Enter one of the 7 managed entity types: HostSystem, VirtualCenter, etc.",
        required => 1,
      },
    );
  2. Add the hash to the script using the Opts::add_options subroutine:
    Opts::add_options(%opts);

    Table 2: Attributes for Defining New Options
    Attribute Description
    default Default value used if the option isn’t explicitly set; an unset option with no default returns undef.
    funcEnables creating “derived options.” Set func to an external code reference to execute the code when the value of the option is queried.
    help Descriptive text explaining the meaning of the option, displayed in the script’s help message.
    requiredIf this attribute is set to 1, a value must be provided for this option or the script will exit and display the help message. Set to 1 to require a value. Set to 0 if value is optional.
    variableEnables an option to be read from an environment variable or the configuration file.
    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 (identifies it as a flag). Default numeric value is 0. Default string value is " " (empty string).

    Mandatory Optional String Integer Float
    = : s i f

  3. Parse and validate the options, prior to connecting to the server:
    Opts::parse();
    Opts::validate();

The entity option defined above is required, so the script will not be able to run unless the user passes in a string value. The string value passed as a parameter will be used in the Vim::find_entity_views() subroutine later in the script, and must be one of the 7 managed-entity types listed as view_type parameter supported by Vim::find_entity_views().

Attempting to run the script without all the necessary options displays usage help for the script, as shown in this 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

Step 3: Connect to the Server

The VI API is hosted as a secure web service on VirtualCenter Server and ESX Server systems: by default, the web service is available over HTTPS, so clients must provide valid credentials to connect to the service. (If your server has been re-configured for HTTP, you do not have to provide logon credentials.) Depending on the specifics of the server you are using for your script development, you may need to enter a username and password only. Or, if the built-in parameter defaults (see Table 1: Built-in Parameters and Variables) are not correct for your specific configuration, you may need to enter servername and other details.

Note that, as shown in the subroutine reference, the VI Perl Toolkit provides two different subroutines for establishing a connection:

Using Util::connect() in your code is a simple one-line entry, after parsing and validating:

Util::connect();

When the script is run, the VI Perl Toolkit runtime checks the environment variables, configuration file contents, and command-line entries (in this order) for the necessary connection-setup details. If none of these overrides are available, the runtime uses the defaults (see Table 1 ) to setup the connection.

Both subroutines return a session token that you can save to a file and then use in subsequent connections to the same or to different servers. See Saving and Using Sessions for details.

Step 4: Obtain Views of Server-Side Managed Objects

The subroutines in the Vim package let you create Perl objects and references for working with server-side objects of interest. In the simpleclient.pl shown in Listing 1, the Opts::get_option subroutine is used to obtain the string value of the parameter that is passed with the script when it is executed. This string value is then used 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 find_entity_views subroutine creates the Perl object (an array of references) from the server-side managed object of the specified entity type.

Step 5: Process Views and Report Results

Here’s where the true purpose of the script becomes clear, in the actual processing of the views. Knowledge of server-side objects is useful here because in order to invoke methods, obtain information about objects (is a virtual machine on or off, for example), you must have some understanding of where in the returned objects the properties and methods reside.

You’ll use the VI API Reference Guide to determine the available properties and methods.

Remember that views are Perl objects, and so you’ll use Perl object-oriented syntax to process the views. In this example, the “processing” involves looping through the array of entities returned (@$entity_views) and accessing the name property of the entity (using the method call, $entity_view->name), and then printing out to the console the name of each entity as it’s found.

foreach my $entity_view (@$entity_views) {
      my $entity_name = $entity_view->name;
      Util::trace(0, "Found $entity_type: $entity_name\n");
}

Additional background information about views is provided in Working with Views .

Step 6: Close the Server Connection

To logout and exit, use the Vim::logout() subroutine.

Util::disconnect();

Listing 2: Sample script (simpleclient.pl) that uses basic pattern [commented version]
#!/usr/bin/perl -w

# The simpleclient.pl script outputs a list of all the entities of the
# specified managed-entity type (ClusterComputeResource, ComputeResource,
# Datacenter, Folder, HostSystem, ResourcePool, or VirtualMachine) found
# on the target VirtualCenter Server or ESX Server system.
# Script users must provide logon credentials and the managed entity type.
# The simpleclient.pl script leverages the Util::trace() subroutine to
# display the found entities of the specified type.


use strict;
use warnings;
use VMware::VIRuntime;
use VMware::VILib;

# Defining attributes for a required option named 'entity' that
# accepts a string.
#
my %opts = (
        entity => {
        type => "=s",
        help => "ManagedEntity type: HostSystem, Datacenter, etc",
        required => 1,
    },
);
Opts::add_options(%opts);

# Parse all connection options (both built-in and custom), and then
# connect to the server
Opts::parse();
Opts::validate();
Util::connect();

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

# Process the findings and output to the console

foreach my $entity_view (@$entity_views) {
      my $entity_name = $entity_view->name;
      Util::trace(0, "Found $entity_type: $entity_name\n");
}

# Disconnect from the server
Util::disconnect();

To run the simpleclient.pl script:

  1. Open command-prompt or console
  2. Navigate to a directory that has path set to VI Perl Toolkit installation
  3. Enter as follows:

    perl simpleclient.pl --server myServerFQDN --username my_username --password password --entity HostSystem

For example:

C:\viperltoolkit>perl simpleclient.pl --server myserver.vmware.com --username Administrator --password password --entity HostSystem

Found HostSystem: lgto-1s-dhcp214.eng.vmware.com

Working with Views

A VI Perl Toolkit view is a client-side Perl object that comprises a static copy of the properties and operations of one or more managed objects on the server. Before delving into VI Perl Toolkit views in more detail, you should understand some of the server-side object model basics—it is this server-side object model that the VI Perl Toolkit abstracts.

VI Object Model Basics (Server-side Object Model)

A managed object is the primary type of object provided in the virtual infrastructure object model. A managed object is a data type that comprises properties and operations available on the server. Each managed object type provides various services (operations, or methods) and properties. Basically, the various managed object types define common administrative and management services that 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).

Another important construct of the server-side object model is the managed object reference ( ManagedObjectReference ), which is essentially the mechanism that enables distributed computing for VMware virtual infrastructure. A managed object reference identifies a specific managed object on the server, and encapsulates the state and methods of specific server-side objects and makes these properties 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.

Managed objects comprise both operations and properties. Each property is defined as a specific data type. Data types include:

ServiceContent is the “largest grained” object on the server, providing access to everything the server offers, through well over a dozen properties that comprise references to specific managed objects.

For example, the rootFolder property is a ManagedObjectReference to a Folder managed object type; the perfManager is a ManagedObjectReference to a specific instance of a PerformanceManager managed object type, and so on. These managed object types define the typical administrative and management services one would expect to use in any datacenter, virtual or otherwise—services such as managing performance (PerformanceManager), finding entities that exist in the inventory (SearchIndex), disseminating and controlling licenses (LicenseManager), and configuring alarms to respond to certain events (AlarmManager), for example.

In addition to providing services to the server as a whole, the ServiceContent object also contains references to so-called inventory objects—objects that are specific instances of entities, such as hosts and the virtual machines that run on them, that effectively comprise an “inventory” of manageable virtual-datacenter components.

Note:  For a hierarchical, graphically-oriented rendering of inventory objects, use the VI Client. The VI Client uses the information about the objects (the properties, and the relationships among them) to materialize a hierarchy in the left-hand pane of its display. See the VMware Infrastructure 3 online library ( Managing the VI Client Inventory:: Understanding VI Client Objects) for additional information about the VI Client and how it represents server-side objects graphically.

The inventory comprises the collection of all managed entities on the server. A managed entity is simply a managed object that extends the ManagedEntity managed object type: ManagedEntity is an abstract class that defines the base properties and operations for the managed objects that comprise the virtual infrastructure—the same type of manageable components found in a physical world, such as datacenters and hosts. The current virtual infrastructure has 7 managed object types that extend the ManagedEntity superclass:

Managed entities offer specific operations that vary, depending on the entity type. For example, a virtual machine managed entity (VirtualMachine) provides operations for creating, monitoring, and controlling virtual machines, including power operations (PowerOnVM, PowerOffVM) and capturing state (Snapshot). On the other hand, a host system managed entity ( HostSystem) provides different operations for entering and exiting maintenance mode (EnterMaintenanceMode_Task, ExitMaintenanceMode_Task), or rebooting the server (RebootHost_Task).

The ManagedEntity base class includes several properties (such as a name property, whose data type is a string) that are inherited by each subclass. ManagedEntity also includes only a few operations that are inherited by each sub-class (Destroy_Task, Reload, for example). So since both VirtualMachine and HostSystem extend the ManagedEntity base class, each has a name property that it inherits from the superclass.

The VI API Reference Guide contains the definition of all server-side objects, their properties and methods. You’ll 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.

An Example

The VI Perl Toolkit provides subroutines for accessing server-side objects from the inventory (managed entities) and other managed objects that provide functionality to the server as a whole. The example in Listing 1 obtains all entities of a specific type from the inventory. The entity type is passed as a parameter to the find_entity_views subroutine, which returns an array of references to view objetcs that map to the specific server-side entity. Listing 3 is a bit different in that it starts from a higher level, that of the entire service; it uses the get_service_content() subroutine to obtain an instance of the ServiceContent object:

my $content = Vim::get_service_content();

Once you’ve obtained a ServiceContent object, you can obtain a local view to the services provided by that specific server. Here’s and example of obtaining reference to a managed object:

my $diagMgr = Vim::get_view(mo_ref => $content->diagnosticManager);

Listing 3 shows how these two calls form the basis of a script that “tails” (follows changes) in the logfile, which is a property of the diagnosticManager.

Listing 3: Obtaining a ServiceContent object
#!/usr/bin/perl -w
#
# Copyright 2007 VMware, Inc. All rights reserved.
#
# This script creates a Perl object reference to the ServiceContent data
# object, and then creates a reference to the diagnosticManager. The script
# follows ('tails') the log as it changes.

use strict;
use warnings;

use VMware::VIRuntime;
use VMware::VILib;

# read/validate options and connect to the server
Opts::parse();
Opts::validate();
Util::connect();

# get ServiceContent
my $content = Vim::get_service_content();
my $diagMgr = Vim::get_view(mo_ref => $content->diagnosticManager);
# Obtain the last line of the logfile by setting an arbitrarily large
# line number as the starting point
my $log = $diagMgr->BrowseDiagnosticLog(
    key => "hostd",
    start => "999999999");
my $lineEnd = $log->lineEnd;

# First, get the last 5 lines of the log, and then check every 2 seconds
# to see if the log size has increased.
my $start = $lineEnd - 5;

# Disconnect on receipt of an interrupt signal while in the infinite
# loop below.
$SIG{INT} = sub {
    Util::disconnect();
    exit;
 };
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 3;
}

View Basics

VI Perl Toolkit views have several characteristics that you should keep in mind as you write your own scripts. Specifically, a view:

The VI Perl Toolkit maps properties from managed objects into client-side view objects as follows:

The VI Perl Toolkit simplifies many programming chores. For example, the VI Perl Toolkit automatically:

The VI Perl Toolkit provides subroutines to access all properties, regardless of their “depth” inside a composite object structure, and provides a subroutine that updates the state of any client-side view objects with current data, from the server.

Accessing Property Values

VI Perl Toolkit view objects are Perl objects. When you obtain a view and manipulate its properties or invoke its methods in a script, you do so using Perl’s object-oriented syntax. To access a simple property from a view, invoke the method name (same as the property name) on the Perl object, as follows:

$view_name->property_name

As shown in Listing 1, the name property of the entity view is accessed by invoking the name method.

my $entity_name = $entity_view->name;

To retrieve the value of a property defined as an enumeration, you must dereference its val from within the containing object, by qualifying the property with ->val.

So, for example, since the power state of a virtual machine (powerState) is “nested” inside (“is a a member of”) the runtime data object, you must dereference the two containing objects—the view object and the runtime data object and the value (val) itself, in order to retrieve the value of powerState,as in:

$vm_view->runtime->powerState->val

Runtime.powerState is an enumeration (enum) and so you need to qualify it as runtime.powerState->val to retrieve is property.

foreach my $vm (@$vm_views) {
   if ($vm->runtime->powerState->val eq 'poweredOn') {
      print "Virtual machine " . $vm->name . " is running.\n";
   } else {
      print "Virtual machine " . $vm->name . " is not running.\n";
}

Modifying Property Values

To modify an existing data object, change its property values by passing the new value:

$data_object->property (new value);

where $data_object is a blessed reference to a Perl object or class name, and property is a method call on the object.

For example, to change the force property,

$host_connect_spec->force ('false');

To change the value of a property that has been defined as an enumeration (enum), you must pass the new value to the method defined for the property in the Perl object, as in:

$data_object->property->val (new value)

$vm_view->runtime->powerState->val ("poweredOff")

Creating Data Objects

To create a new managed object with specific properties—for example, a virtual machine on a specific host—you must create the appropriate data objects that define the managed object and then construct the managed object using the data objects, simple types, and enumeration values, as defined in the VI API Reference Guide for the object.

The client-side object (or objects) that you build-up in this way can then be passed, along with the appropriate managed object reference, to create new server-side managed objects on the server.

The one thing you will need is a managed object reference (mo_ref) for the managed object on the server.

To create a data object:

$var = new DataobjectType (param1 => value, param2 => value …)

For example, adding a host requires several parameters, including a HostConnectSpec data object. Start by creating a HostConnectSpec data object:

$host_connect_spec = new HostConnectSpec (
            force => 'true',
            hostName => 'my host',
            userName => 'user',
            password => 'pwd');

To set the value of a property that has been defined as an enumeration, you must pass the new value to the data object as follows:

$ref = new enum_type (val => value);

For example, to change the power state:

$power_state = new VirtualMachinePowerState (val => 'poweredOff');

Understanding Operations and Methods

One of the key functions of the VI Perl Toolkit runtime is to map server-side operations to client-side Perl view methods.

A VI Perl Toolkit view provides a method for each operation defined on the server managed object from which the view was created.

For each server-side operation, the VI Perl Toolkit creates a method (of the same name) in the client-side Perl object. By default, most all server-side operations available in the VI API are non-blocking operations listed in the VI API Reference Guide (opname_Task method), the VI Perl Toolkit provides a blocking (synchronous) version—opname—that provides the same functionality (as opname_Task) but without returning a reference to a task object.

In addition, the VI Perl Toolkit extends the capabilities of the VI API, by providing blocking methods in addition to the non-blocking operations available through the VI API.

You will see the non-blocking operations defined in the VI API Reference as opname_Task. For every managed object opname_Task available in the VI API (you’ll see these listed in the VI API ReferenceGuide), the VI Perl Toolkit also provides an opname method.

Thus, the VI Perl Toolkit provides both blocking and non-blocking methods, and if you see an opname_Task operation in the VI API ReferenceGuide, you can safely assume that the VI Perl Toolkit view provides an opname method that you can use in your script.

To invoke a method on the view, you must pass the appropriate parameters, as defined in the VI API Reference, for the managed object.

 

Invoking Methods

After obtaining a view of a managed object, you can invoke methods on that view to effectively make use of the services provided by the managed object. Client-side view objects are Perl objects; to invoke methods, you specify the parameter for the object method by name:

$vm->MigrateVM (name => 'productionVM');

The type of parameter (simple type, data object, or managed object reference) that you’ll need to pass to the method depends on the operation as defined in the VI API.

See the VI API Reference Guide for information about specific parameters and data types.

Blocking operations are invoked as methods on a view object. For example, to suspend a virtual machine:

$vm_view->SuspendVM();

Any operation that is defined for a managed object can be invoked as a method on a corresponding view object.

Since the VI Perl Toolkit creates an accessor/mutator method for each property defined in the managed object, you can reference the name of any property as a method call of the view (a Perl object):

my $network_name = $network_view->name

As mentioned in View Basics , one of the convenience features of the VI Perl Toolkit is that you can pass a view to a method that requires a ManagedObjectReference (rather than a managed object reference). For example, assuming you have view of a host ($host), you can pass the view ($host) to the powerOn method, in place of the managed object reference argument:

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)

Updating View Objects

The values of properties in any view represent the state of the server side objects at the time the view was created, and as mentioned previously, these property values are not updated automatically. However, in a production environment, the state of managed objects on the server is likely to be changing constantly. If your client script depends on the server-side view being in a particular state—poweredOn or poweredOff, for example—then you must either check the state prior to acting on the client view object, or you must refresh the state of the view object. The VI Perl Toolkit library provides the update_view_data subroutine to refresh the values of client-side views with server-side values.

To refresh a view’s data, use the update_view_data() subroutine.

Listing 4: Updating the state of view objects
#!/usr/bin/perl
use strict;
use warnings;
use VMware::VIRuntime;
use VMware::VILib;
. . .
# Get all VirtualMachine objects
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine');

# Power off virtual machines.
foreach my $vm (@$vm_views) {
    # Refresh the state of each view
    $vm->update_view_data();
    if ($vm->runtime->powerState->val eq 'poweredOn') {
        $vm->PowerOffVM();
        print " Stopped virtual machine: " . $vm->name . "\n";
    } else {
        print " Virtual machine " . $vm->name .
    " power state is: " . $vm->runtime->powerState->val . "\n";
    }
}

# logout
Vim::logout();

4. Advanced Topics

This section includes these advanced topics:

Creating and Using Filters

One of the more powerful features of the VI Perl Toolkit is the ability to define and use filters to select specific objects based on property values. For example, instead of obtaining all virtual machines from an ESX Server system, you can obtain only those virtual machines whose names begin with a certain prefix. Filters use regular expressions for pattern matching (see Filters and Regular Expressions for details). You can apply one or more filters to the find_entity_views (and find_entity_view) subroutines to quickly select a subset of objects based on property values.

To create a filter based on a simple property, such as a string, you must first find the property in the VI API Reference to find the property name, and set the filter for the specific possible value:

filter => { 'property_name' => property_value, ... }

Filters and Regular Expressions

The filter construct is a standard Perl programming pattern; it supports regular expressions, so the syntax model above means

Matching is based on regular expression matching.

^myspecificmachine$

Use dot notation to specify the property name in the filter definition, as shown in Listing 5.

For properties that are nested inside a data object, you must use dot notation. For example:

filter => {'object_name.method_name' => 'property_value', ... }

Listing 5: Example of a filter that creates views of Windows-based virtual machines only
. . .
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine',
          filter => {
              'config.guestFullName' => '.*Windows.*'
              });


Print VM names
foreach my $vm (@$vm_views) {
          print "Name: " . $vm->name . "\n";
}
. . .

If you pass multiple filters to find_entity_views (or find_entity_view), only those managed objects matching all criteria are returned.

For example, the filter parameter specfied in Listing 6 includes a second filter definition—status must be poweredOn—so only those virtual machines whose guest operating system is Windows—the config property’s guestFullName property includes the string “Windows”—and that are actually running will be returned.

Listing 6: Example of multiple filter specification
. . .
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine',
          filter => {
              'config.guestFullName' => '.*Windows.*'
              'runtime.powerState' => 'poweredOn'

              });br>
Print VM names
foreach my $vm(@$vm_views) {
          print "Name: " . $vm->name . "\n";
}
. . .

Handling Errors

Be sure to embed your calls to the VI Perl Toolkit subroutines inside appropriate conditional logic, to handle possible empty or non-existent return values and other issues. Using conditional logic around any of the access subroutines—find_entity_view, find_entity_views, get_view, get_views, for example—is generally a good practice.

For example, as shown in Listing 7 (excerpted from the \scripts\discovery\datacenterlisting.pl sample script), you can use simple conditional logic to handle null or empty results, by gracefully exiting the script and notifying the user (via console display) that the requested datacenter wasn’t found (lines 28 and 29):

Listing 7: Use conditional logic
01 #!/usr/bin/perl -w
02 use strict;
03 use warnings;
04
05 use VMware::VIRuntime;
06 use VMware::VILib;
07
...
22
23 # Find the datacenter that matches the name entered as a parameter
24 my $datacenter = Opts::get_option('datacenter');
25 my $datacenter_view = Vim::find_entity_view(view_type => 'Datacenter',
26 filter => { name => $datacenter });
27
28 if (!$datacenter_view) {
29   die "Datacenter '" . $datacenter . "' not found\n";
30 }
31
32 # get all hosts under this datacenter
33 my $host_views = Vim::find_entity_views(view_type => 'HostSystem',
34         begin_entity => $datacenter_view);
. . .

As standard practice, you should include error-handling code in your scripts. Errors fall into one of these three basic categories:

However, regardless of the root cause, the VI Perl Toolkit runtime is designed to stop processing scripts whenever errors such as these occur.

SOAP Faults

Since the VI API is hosted as a Web service, your scripts should include handlers for any possible SOAP faults (you’ll find these in the VI API ReferenceGuide for the managed object), to avoid having your script terminate with a error message. If your script doesn’t include fault handling code and a fault is received during script execution, the script terminates with an error message.

The VI Perl Toolkit translates all server-generated faults (including non-SOAP-specific faults) into a Perl object named SoapFault that contains information about the server-side fault.

You can trap both server-generated faults and client-errors using Perl’s eval function, which uses a special variable, $@, to hold the value of any exception raised. The name of the fault is located in the detail property of the Perl error object:

$@->detail

Listing 8 shows a basic approach to error handling.

Listing 8: Basic Pattern for Error Handling
eval {
# call operations    };
if ($@) {
    if ($@ is SoapFault) {
        # server fault
        my $server_fault = $@->detail;
        if ($server_fault is 'InvalidLogin') {
              # handle or exit
    }
    } else {
    # user code error
    # print and exit
  }
}

Saving and Using Sessions

The VI Perl Toolkit library includes several subroutines that let you save and re-use sessions, enabling you to maintain sessions across scripts and use multiple sessions within the same script—for example, to copy information from one server to another.

Using sessions can also enhance security: Instead of storing passwords in scripts, you can instead invoke the connect() subroutine in your script using the name of the session file. The session file contains a token so the password information isn’t exposed or readable.

The session file is an object that’s returned by the login subroutine. Save the object to a sessionfile and then use the session file in another script.

$session1 = Vim->new(service_url => 'https://<hostname1>/sdk');
$session1->login(
        user_name => 'user',
        password => 'secret');


$session2 = Vim->new(service_url => 'https://<hostname2>/sdk');
$session2->login(
        user_name => 'user',
        password => 'secret');

You can then use the session object to reference all functions.

$session1->find_entity_views

To use sessions, you must first login to the server using Vim::login or Util::connect subroutines. Then you can use the vim::save_session and vim::load_session to maintain this connection across multiple scripts. The session remains active until either a logout or disconnect operation is invoked, or until it times out (after 30 minutes, by default).

if (!Opts::option_is_set('sessionfile')) {
    print "Must specify sessionfile for this sample\n";
    Opts::usage();
} elsif (!Opts::option_is_set('username') || !Opts::option_is_set('password')) {
    print "Must specify username and password for this sample\n";
    Opts::usage();
}

Learning About Object Structure Using Data::Dumper

The VI Perl Toolkit transparently uses the Data::Dumper Perl module (a standard library) to create the client-side proxy (stub) components known as view objects (views). If you want to learn more about these Perl objects (and how they relate to the VI object model), you can use Data::Dumper as demonstrated in Listing 9.

Lines 12 through 14 set parameters of Data::Dumper that make its output more easily understood:

Listing 9: Using Data::Dumper to output Perl object structures
01 use strict;
02 use warnings;
03
04 use VMware::VIRuntime;
05 use VMware::VILib;
06
07 # Parse connection options and connect to the server

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
23 print Dumper ($host_view->summary->config->product) . "\n\n\n";
24
25 print Dumper ($host_view->summary->config) . "\n\n\n";
26
27 print Dumper ($host_view->summary) . "\n\n\n";
28
29 # logout
30 Vim::logout();

The sample output produced by line 23 [Listing 9] shows the AboutInfo object’s properties

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

This shows the content of the properties of object referred to by the product property of the config property of the summary property of the HostSystem managed object of this server. Perl’s 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 that the values between parentheses comprise a Perl object.

Line 19 [Listing 9] gets the HostSystem view and line 21 prints the name associated with that host.

The config property has more values than just those printed by line 23. Line 25 prints out the entire config object. The config object printed by line 25 [Listing 9], 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' );

Not shown is the output from line 27 of Listing 9, which 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.

5. VI Perl Toolkit Subroutine Reference

Table 6 lists subroutines available through the various VI Perl Toolkit runtime modules and libraries. Unless otherwise noted, parameters listed below are required.

Table 6: VI Perl Toolkit Subroutines
Subroutine Description Parameters Returns
Opts
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. %opts:  Name of the hash variable that comprises the option name and its attributes. Nothing.
option_getObtains the value of the specified built-in or custom option. option_name: String value of the built-in or custom option.Returns one of the following, depending upon the attributes defined for the option:
  • Return value of func (after execution) if a func has been associated with the option; or
  • Default value, if one has been specified for the option; or
  • Value of the option as passed to the script; or
  • Undef, if none of the above have been specified.
option_is_setDenotes that an option has been explicitly set via the script, as a command-line or other parameter, rather than being a default or computed value (that is, the return value of a func). option_name: String value that represents the built-in or custom option name. Boolean. Returns 1 (true) if option value has been explicitly set. Returns 0 (false) if option value is a default value, is null, or has not been explicitly set.
parseReads options from the command-line, environment variable, or configuration file, transforming into appropriate data structures for validation. None.Nothing. Displays error message and quits if parse not successful.
validateEnsures that input values (from command-line, environment variable, or configuration file) are complete, consistent, and valid. None. Nothing. Displays error message and quits if validation not successful.
usage Outputs help text message associated with the option. None. String of text message.
Util
connectEstablishes a session with the VirtualCenter Management Server or ESX Server Web service using the token provided in a previously saved session file, or by using the user name and password provided via command-line, environment variables, or configuration file. user_name: User account on the ESX Server or VirtualCenter Server host system.
password: Password for the user account.
filename: Full path and filename comprising the token saved from a previous successful connection. Use filename (instead of user_name and password) to re-establish session to the same server, or to establish new connection to a different server.
Returns a session object (token) that can be saved to a file and used in subsequent connections.
disconnectIf used in conjunction with connect (and session file), does nothing. If used in conjunction with username and password, logs out and closes the session. None.Nothing.
get_inventory_pathFunction that returns the inventory path for the specified managed entity (Folder, Datacenter, HostSystem, VirtualMachine, ComputeResource, ResourcePool). The resulting inventory path can later be passed to the SOAP operation FindByInventory path to retrieve the ManagedObjectReference for managed entity (from which a view can be created). view: Managed entity view. String that identifies the inventory path of the managed entity.
traceGeneral-purpose logging function used in conjunction with --verbose command-line option. If not specified, default loglevel is 0. Passing --verbose flag without a value sets the level to 1. loglevel: Numeric value. If not specified, default is 0.
message: A string value that will be printed for the associated loglevel value.
Nothing.
Vim
find_entity_viewSearches the inventory tree for a managed entity that matches the specified entity type. Search begins with root folder unless the begin_entity parameter is specified. 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.
A 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 the first managed entity found only. If there are no matching managed entities, the subroutine returns undef.
find_entity_viewsSearches the inventory tree for managed objects that match the specified entity type. 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.
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_content Retrieves properties of the service instance enabling access to all managed objects that comprise the service. Alternatively, you can use get_views, get_view, and other subroutines to access more directly the objects of interest. If you start with the service content to work with the Web service, you will need to navigate to the object of interest. None. A reference to a data object that contains managed object references to all inventory content, including root folder.
get_viewRetrieves the properties of a single managed object. 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.
A view object containing static copies of the property values for a managed object.
get_viewsRetrieves the properties of a set of managed objects. mo_ref_array: A reference to an array of managed object references.
view_type (optional): Same as for the get_view subroutine.
A reference to an array of view objects containing copies of property values for multiple managed objects.
load_sessionUses a saved session file for connection to a server. Use Util::connect instead of Vim::login. filename: Full path and filename where the token should be saved. Times out after 30 minutes. Nothing.
login Establishes a session with the VirtualCenter Management Server or ESX Server Web service using the provided credentials (user name, password) provided via command-line, environment variables, or configuration file. service_url: The URL of the server to which the client connects.
user_name: User account on the ESX Server or VirtualCenter Server host system.
password: Password for the user account.
Session object that can be saved to a file for future use. See save_session for details.
logoutDisconnects the client from the server. None. Closes the connection to the Web service.Nothing.
save_sessionSaves a token comprising current session information (username and password) to the specified filename, overwriting content if filename already exists. filename: Full path and filename where the token should be saved. Times out after 30 minutes. Nothing.
update_view_dataRefreshes the property values of a view object. NoneNothing.

6. Glossary

data objectComplex data type that comprises 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 analagous to structures (struct) in C, C++, and several other programming languages; Java has no distinguished notion of struct, but uses class declarations for abstract data types.)
inventoryThe collection of all managed entities on the server—instances of HostSystem, Datacenter, VirtualMachine, ResourcePool, ComputeResource, ClusterComputeResource, and Folder.
managed entityOne of the seven managed object types that extends the ManagedEntity managed object, specifically: The ManagedEntity managed object type is an abstract class that defines the base properties and methods for the objects that comprise the virtual infrastructure—the same kinds of manageable components found in a physical IT infrastructure, such as datacenters and hosts.
managed objectA server-side type that comprises 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 referenceA type of data object that enables distributed computing for VMware virtual infrastructure. 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.
VI APIThe set of Web services, hosted on ESX Server and VirtualCenter Server host systems, that provides interfaces to virtual infrastructure components—hosts, virtual machines, and datacenters, for example—and operations on these components.
viewA client-side Perl object that is populated with the state of one or more 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.
virtualizationSeparation 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—networks, storage, laptop or server hardware, operating systems, and applications.
VI SDKThe 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.

Copyright © 2007 VMware, Inc. All rights reserved.

VI Perl Toolkit 1.0 | Released 30-Aug-2007 | Last updated 11-October-2007 5:45 pm