VMware vCloud Suite Python SDK: client samples README

VMware logo

Additionally, some of the samples demonstrate the combined use of the vCloud Suite and vSphere APIs. To support this combined use, the vCloud Suite Python SDK samples require the vSphere Management SDK packages (pyVmomi) to be installed on the client. The examples have been developed to work with the python 2.7, 3.3 and 3.4.

The following sections provide information about using the samples..

Python SDK and 3rd party Dependencies

Please see the instructions for installing the SDK and 3rd party libraries.

Feature Samples

The vCloud Suite Python SDK samples are located in the client sample directory:
samples

The following table shows the sample sub-directories and their contents.

DirectoryDescription
com.vmware.vcloud.suite.samples.commonSamples common classes and abstractions; This package does NOT contain any sample
com.vmware.vcloud.suite.samples.vim.helpersSamples and utilities for accessing and manipulating VC objects using pyVmomi
com.vmware.vcloud.suite.samples.lookupserviceService discovery sample using lookup service APIs
com.vmware.vcloud.suite.samples.workflowVarious vAPI work flow samples
com.vmware.vcloud.suite.samples.inventorySamples for inventory APIs for retrieving information about vCenter datastore and network objects.

Sample Program Structure

The vCloud Suite Python SDK samples use a framework to facilitate different aspects of using the samples. Some of the framework capabilities are:

  • Command line argument parsing.
  • Specifying mandatory and optional arguments for a sample.
  • Sample setup, execution and post-execution cleanup.
  • Information about samples.

To work with the VMWare-supported deployment configurations of Platform Services Controllers (Single Sign-On) and vCenter Servers, applications need to dynamically discover service URLs to make service requests. Before making service requests, applications need to authenticate with the Single Sign-On service.
Most of the vCloud Suite client application performs the following basic tasks to connect to the vAPI and vim service endpoint (on a management node) and accomplish Platform Services initialization.

  • Step 1: Connect to the lookup service endpoint on the Platform Service Controller Node.
  • Step 2: Discover the Single Sign-On service URL from lookup service.
  • Step 3: Connect to the Single Sign-On URL and retrieve the SAML token.
  • Step 4: Discover the vim, vAPI service URL's of the respective Management Node.
  • Step 5: Login to vAPI and vim service endpoints.
  • Step 6: Discover other services through lookup service.
  • Step 7: Perform certain tasks using the vAPI and vim services.

The call sequence shown above is implemented in the samples framework through the following modules:

  • src/com/vmware/vcloud/suite/sample/common/lookup_service_helper provides methods for discovering management nodes and service endpoint URLs on management nodes from lookup service.
  • src/com/vmware/vcloud/suite/sample/common/platform_service_controller uses lookup_service_helper to discover the Single Sign-On URL (on any of the Platform Service Controller node) and then retrieves the SAML token from the Single Sign-On server by authenticating the given user.
  • src/com/vmware/vcloud/suite/sample/common/service_manager login to the vAPI and vim service endpoints (on a management node).
Note: Depending on the vCenter Server deployment model, it is possible to have more than one management node. The samples framework uses src/com/vmware/vcloud/suite/sample/common/service_manager_factory to manage connections/sessions to multiple management nodes.

Each sample extends the class samples_base. This class uses platform_service_controller and service_manager_factory to create and manage the vAPI service endpoint and vSphere service port. Every sample implements the following methods from the class samples_base:

  • _options() - Called by samples_base during parse_args phase. This occurs during initialization.
  • _setup() - Called by samples_base during before phase. This occurs after authentication and vAPI and vSphere service initialization.
  • _execute() - Called by samples_base during run phase. At this point all the connections and services are initialized.
  • _cleanup() - Called by samples_base during after phase. This occurs before disconnecting the services.

The following code snippet from src/com/vmware/vcloud/suite/samples/common/samples_base.py illustrates the order in which _options(), _setup(), _execute() and _cleanup() methods are called in the samples:

    def __init__(self, description, servicemanager=None):
        if description is None:
            raise Exception("Sample description cannot be empty")
        self.description = description
        # setup the argument parser
        self.argparser = argparse.ArgumentParser(description=description)
        self.argparser.add_argument('-lswsdlurl', '--lswsdlurl', help='Lookup service WSDL URL')
        self.argparser.add_argument('-lssoapurl', '--lssoapurl', help='Lookup service SOAP URL')
        self.argparser.add_argument('-ssousername', '--ssousername', help='SSO user name')
        self.argparser.add_argument('-ssopassword', '--ssopassword', help='SSO user password')
        self.argparser.add_argument('-cleardata', '--cleardata', help='Clears the sample data on server after running')
        ....
        ....
        ....
        self.servicemanager = servicemanager

    def parse_args(self):
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and name == '_options':
                attr()  # calling the method
        self.args = self.argparser.parse_args()  # parse all the sample arguments when they are all set

        if self.args.lswsdlurl is None:
            self.lswsdlurl = SampleConfig.get_ls_wsdl_url()  # look for lookup service WSDL in the sample config
        else:
            self.lswsdlurl = self.args.lswsdlurl
        assert self.lswsdlurl is not None
        logger.info('lswsdlurl: %s' % self.lswsdlurl)

        ....
        ....
        
        if self.args.cleardata is not None:
            if self.args.cleardata.lower() == 'true':
                self.cleardata = True

    def before(self):
        if self.servicemanager is None:
            self.servicemanager = ServiceManager(lswsdlurl=self.lswsdlurl,
                                                 lssoapurl=self.lssoapurl,
                                                 ssousername=self.ssousername,
                                                 ssopassword=self.ssopassword)
            self.servicemanager.connect()
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and name == '_setup':
                attr()  # calling the method

    def run(self):
        for name in dir(self):
            attr = getattr(self, name)
            if callable(attr) and name == '_execute':
                try:
                    attr()  # calling the method
                except Exception as e:
                    # print the exception and move on to the cleanup stage if cleardata is set to True.
                    logger.exception(e)
                    traceback.print_exc()
                    if bool(self.cleardata) is not True:
                        # re-throw the exception
                        raise Exception(e)

    def after(self):
        if bool(self.cleardata) is True:
            for name in dir(self):
                attr = getattr(self, name)
                if callable(attr) and name == '_cleanup':
                    attr()  # calling the method

Running the samples

The following parameters are needed for running most of the samples:

  • lswsdlurl -lookup service WSDL file URL. See Using WSDL
  • lssoapurl - Platform Service controller's/node's (any, since data is replicated) lookupservice soap URL. Ex: https://psc/lookupservice/sdk
  • ssousername - username for authentication with the SSO server
  • ssopassword - password for the SSO user
  • cleardata - Optional, if set to true all the sample data gets deleted on the server after the sample run

You can specify lswsdlur, lssoapurl, ssousername and ssopassword in a configuration file (sample.cfg). If you use a configuration file, you can run samples without specifying these options on the command line.

Samples configuration


sample.cfg configuration file specifies all the basic connection properties needed by most of the samples. When you run a sample, you can override the configuration file values by specifying command line options.

[connection]
lswsdlurl=file:///path/to/the/VMware-vCloud-Suite-SDK-Python-6.0.0/client/wsdl/lookupservice.wsdl
lssoapurl=https://myserver.mydomain.com/lookupservice/sdk
ssousername=admin
ssopassword=adminpassword
The sample.cfg file can be found under VMware-vCloud-Suite-SDK-Python-<version>/client/samples/src

Working with lookup service WSDL


The vCloud Suite SDK for Python samples use the vCloud Suite Lookup Service to obtain the URLs for other vCloud Suite services (SSO, vAPI, VIM, SPBM, etc.). The SDK contains the Lookup Service WSDL files. The samples use the python SUDS client for accessing the lookup service.
The Lookup Service WSDL files are located in the following SDK directory:
VMware-vCloud-Suite-SDK-Python-<version>/client/wsdl.
You must specify the WSDL file location in the client/samples/src/sample.cfg file and in the lookupservice.wsdl file (located in the WSDL directory).

  1. In sample.cfg, set 'lswsdlurl' to the lokkupservice WSDL file location. Use a local file URL specification: e.g. lswsdlurl=file:///path/to/the/VMware-vCloud-Suite-SDK-Python-6.0.0/client/wsdl/lookupservice.wsdl
    (Note: You can also specify the lookup service WSDL path to the sample as a command line option)
  2. In lookupservice.wsdl, set 'import location' to the local lookup WSDL file. Use a local file URL specification.
    <import location="file:///path/to/the/VMware-vCloud-Suite-SDK-Python-6.0.0/client/wsdl/lookup.wsdl" namespace="urn:lookup" />
       <service name="LsService">
          <port binding="interface:LsBinding" name="LsPort">
              <soap:address location="http://localhost:8080/lookupservice/sdk" />
          </port>
       </service>
    

Running the samples from command line


You can run the samples from command line using the scripts supplied in VMware-vCloud-Suite-SDK-Python-<version>/client/bin directory:
Before running the samples:

  1. You must set the PYTHON_HOME environment variable to the base directory for the python 2.7
  2. You must install all the dependencies required by the samples on client. See Sample Dependencies

Examples:
$cd /path/to/VMware-vCloud-Suite-SDK-Python-<version>/client/bin
$run_sample.sh ../samples/src/com/vmware/vcloud/suite/sample/workflow/connection_workflow.py \
    -vapiurl https://203.0.113.0/api \
    -stsurl https://203.0.113.0:443/sts/STSService/vsphere.local \
    -ssousername [email protected] \
    -ssopassword AdminPassword

Use the -h option to print information about a sample. The following example shows the help for the Virtual Datacenter work flow sample.
$ ./run_sample.sh  ../samples/src/com/vmware/vcloud/suite/sample/workflow/tagging_workflow.py -h
usage: tagging_workflow.py [-h] [-lswsdlurl LSWSDLURL] [-lssoapurl LSSOAPURL]
                           [-ssousername SSOUSERNAME]
                           [-ssopassword SSOPASSWORD]
                           [-mgmtinstancename MGMTINSTANCENAME]
                           [-cleardata CLEARDATA] [-clustername CLUSTERNAME]
                           [-categoryname CATEGORYNAME]
                           [-categorydesc CATEGORYDESC] [-tagname TAGNAME]
                           [-tagdesc TAGDESC]

Demonstrates tagging CRUD operations 
Step 1: Create a Tag category.
Step 2: Create a Tag under the category.
Step 3: Retrieve the managed object id of an existing cluster from its name.
Step 4: Assign the tag to the cluster.
Additional steps when clearData flag is set to TRUE:
Step 5: Detach the tag from the cluster.
Step 6: Delete the tag. Step 7: Delete the tag category.
Note: the sample needs an existing cluster

optional arguments:
  -h, --help            show this help message and exit
  -lswsdlurl LSWSDLURL, --lswsdlurl LSWSDLURL
                        Lookup service WSDL URL
  -lssoapurl LSSOAPURL, --lssoapurl LSSOAPURL
                        Lookup service SOAP URL
  -ssousername SSOUSERNAME, --ssousername SSOUSERNAME
                        SSO user name
  -ssopassword SSOPASSWORD, --ssopassword SSOPASSWORD
                        SSO user password
  -mgmtinstancename MGMTINSTANCENAME, --mgmtinstancename MGMTINSTANCENAME
                        Instance name of the vCenter Server management node.
                        When only one node is registered, it is selected by
                        default; otherwise, omit the parameter to get a list
                        of available nodes.
  -cleardata CLEARDATA, --cleardata CLEARDATA
                        Clears the sample data on server after running
  -clustername CLUSTERNAME, --clustername CLUSTERNAME
                        Name of the cluster to be tagged
  -categoryname CATEGORYNAME, --categoryname CATEGORYNAME
                        Name of the Category to be created
  -categorydesc CATEGORYDESC, --categorydesc CATEGORYDESC
                        Description of the Category to be created
  -tagname TAGNAME, --tagname TAGNAME
                        Name of the tag to be created
  -tagdesc TAGDESC, --tagdesc TAGDESC
                        Description of the tag to be created
Note: If you choose to specify the connection properties in sample.cfg file; you can omit the following options in the command line:
  • lswsdlurl
  • lssoapurl
  • ssousername
  • ssopassword

Running a sample without sample.cfg (specifying all the connection options in the command line):
./run_sample.sh ../samples/src/com/vmware/vcloud/suite/sample/workflow/tagging_workflow.py \
    -lswsdlurl file:///Users/smukhopadhyay/Downloads/lookupservice.wsdl \
    -lssoapurl https://203.0.113.0/lookupservice/sdk \
    -ssousername [email protected] \
    -ssopassword AdminPassword \
    -categoryname test -categorydesc test-category -tagname sample -tagdesc sample-tag \
    -clustername vAPISDKCluster -cleardata True

Running a sample specifying connection properties in sample.cfg:
./run_sample.sh ../samples/src/com/vmware/vcloud/suite/sample/workflow/tagging_workflow.py \
    -categoryname test -categorydesc test-category -tagname sample -tagdesc sample-tag \
    -clustername vAPISDKCluster -cleardata True

Note: In the above example mgmtinstancename is optional and can be omitted if there's a single vCenter Server management node in the deployment. When there is more than one management node, the user MUST specify the management node instance name against which the sample needs to run, else the sample throws MultipleManagementNodeException. Example of a multiple management node exception:

raise MultipleManagementNodeException(MultipleManagementNodeException.format(result))
com.vmware.vcloud.suite.sample.common.lookup_service_helper.MultipleManagementNodeException: Multiple Management Node Found on server
Node name: vcenter-1.example.com uuid: de2afd86-790e-11e4-9c20-0200087f55c6
Node name: vcenter-2.example.com uuid: 545da868-7910-11e4-81e1-020008e89d83
Example exception when an invalid management instance name is specified by the user:
ValueError: abc is not a valid management node instance name
Available management nodes:
Node name: vcenter-2.example.com uuid: 545da868-7910-11e4-81e1-020008e89d83
Node name: vcenter-1.example.com uuid: de2afd86-790e-11e4-9c20-0200087f55c6


Copyright © 2015 VMware, Inc. All rights not expressly granted herein are reserved.

Last updated: 23rd January 2015 |  VMware vCloud Suite Python SDK