
VMware Infrastructure (VI) Perl Toolkit Programming Guide
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:
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:
VMware provides numerous support and educational resources. See the support page at:
http://www.vmware.com/support/services
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 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
http://mylearn1.vmware.com/mgrreg/index.cfm
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 |
VMware welcomes your suggestions for improving technical publications. You can email your feedback to:
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. Youll 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 isyou dont need to learn anything about the VI Perl Toolkit or its underpinnings to use these Utility Applications.
The VI Perl Toolkit provides:
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.
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| Parameter | Variable | Description |
| config | VI_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). |
| password | VI_PASSWORD | Password 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. |
| portnumber | VI_PORTNUMBER | Port used for server connection. |
| protocol | VI_PROTOCOL | Protocol used to connect to server. Default is HTTPS. If the server has been configured for HTTP, set to HTTP. |
| server | VI_SERVER | ESX Server or VirtualCenter Management Server host to which you want the application or script to connect. Default is localhost if none specified. |
| servicepath | VI_SERVICEPATH | Service path for server connection. Default is /sdk/webService. |
| sessionfile | VI_SESSIONFILE | Name of file containing the token saved from successful login. Alternative to specifying username and password. Sessions time out after 30 minutes of inactivity. |
| url | VI_URL | Complete 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 |
| username | VI_USERNAME | User account that has privileges to connect to the server. |
| verbose | VI_VERBOSE | Increase 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. |
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:
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:
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. |
|
Any Perl script you write using the toolkit should include these these two modules:
These two modules, directly or indirectly, handle all client-side infrastructure detailsfor 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:
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.
| Attribute | Description | ||||||||||
| default | Default value used if the option isnt explicitly set; an unset option with no default returns undef. | ||||||||||
| func | Enables 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 scripts help message. | ||||||||||
| required | If 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. | ||||||||||
| variable | Enables 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 doesnt accept a value (identifies it as a flag). Default numeric value is 0. Default string value is " " (empty string).
|
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
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.
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.
Heres 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.
Youll use the VI API Reference Guide to determine the available properties and methods.
Remember that views are Perl objects, and so youll 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 its 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 .
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:
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
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 basicsit is this server-side object model that the VI Perl Toolkit abstracts.
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 datacenterservices 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 otherwiseservices 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 objectsobjects 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 infrastructurethe 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. Youll 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.
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 youve obtained a ServiceContent object, you can obtain a local view to the services provided by that specific server. Heres 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; } |
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.
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 Perls 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 objectsthe 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"; } |
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")
To create a new managed object with specific propertiesfor example, a virtual machine on a specific hostyou 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');
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) versionopnamethat 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 (youll 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. |
|
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 youll 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:
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 statepoweredOn or poweredOff, for examplethen 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 views 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(); |
This section includes these advanced topics:
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, ... }
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 definitionstatus must be poweredOnso only those virtual machines whose guest operating system is Windowsthe config propertys guestFullName property includes the string Windowsand 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"; } . . . |
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 subroutinesfind_entity_view, find_entity_views, get_view, get_views, for exampleis 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 wasnt 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.
Since the VI API is hosted as a Web service, your scripts should include handlers for any possible SOAP faults (youll find these in the VI API ReferenceGuide for the managed object), to avoid having your script terminate with a error message. If your script doesnt 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 Perls 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 } } |
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 scriptfor 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 isnt exposed or readable.
The session file is an object thats 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).
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:
|
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 objects 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. Perls 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.
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| data object | Complex 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.) |
| inventory | The collection of all managed entities on the serverinstances of HostSystem, Datacenter, VirtualMachine, ResourcePool, ComputeResource, ClusterComputeResource, and Folder. |
| managed entity | One 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 infrastructurethe same kinds of manageable components found in a physical IT infrastructure, such as datacenters and hosts. |
| managed object | A 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 datacenterservices 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 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 API | The set of Web services, hosted on ESX Server and VirtualCenter Server host systems, that provides interfaces to virtual infrastructure componentshosts, virtual machines, and datacenters, for exampleand operations on these components. |
| view | A 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. |
| 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 hardwareand 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 infrastructurenetworks, storage, laptop or server hardware, operating systems, and applications. |
| VI SDK | The package of componentsWSDL, sample code, and other artifactsrequired 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