Skip to content

Improve sample code #30

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 18, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 30 additions & 25 deletions sample_template/sample_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@
import atexit

from com.vmware.vcenter_client import VM
from samples.vsphere.common.sample_util import parse_cli_args
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.service_manager import ServiceManager


class Sample:
class Sample(object):
"""
TODO: Sample description and prerequisites.
e.g. Demonstrates getting list of VMs present in vCenter
Expand All @@ -33,40 +34,44 @@ class Sample:
"""

def __init__(self):
self.vm_service = None # Service used by the sample code.
self.stub_config = None
self.si = None
self.service_manager = None
self.vm_name = None
self.cleardata = None

def setup(self):
server, username, password, cleardata, skip_verification = \
parse_cli_args()
self.cleardata = cleardata
# Create argument parser for standard inputs:
# server, username, password, cleanup and skipverification
parser = sample_cli.build_arg_parser()

# Connect to both Vim and vAPI services
service_manager = ServiceManager(server,
username,
password,
skip_verification)
service_manager.connect()
atexit.register(service_manager.disconnect)
# Add your custom input arguments
parser.add_argument('-n', '--vm_name',
action='store',
default='Sample_Default_VM_for_Simple_Testbed',
help='Name of the testing vm')

# Get the vAPI stub
self.stub_config = service_manager.stub_config
self.vm_service = VM(self.stub_config)
args = sample_util.process_cli_args(parser.parse_args())
self.vm_name = args.vm_name
self.cleardata = args.cleardata

# Get VIM service instance (pyVmomi)
self.si = service_manager.si
# Connect to both Vim and vAPI services
self.service_manager = ServiceManager(args.server,
args.username,
args.password,
args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)

def run(self):
# TODO add steps to demo your API
# TODO add your sample code here

# Using vAPI services
vms = self.vm_service.list()
# Using REST API service
vm_service = VM(self.service_manager.stub_config)
filter_spec = VM.FilterSpec(names=set([self.vm_name]))
vms = vm_service.list(filter_spec)
print(vms)

# Using vim services
current_time = self.si.CurrentTime()
# Using Vim API service (pyVmomi)
current_time = self.service_manager.si.CurrentTime()
print(current_time)

def cleanup(self):
Expand Down
4 changes: 2 additions & 2 deletions samples/vsphere/common/sample_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def build_arg_parser():
-u username
-p password
-c cleanup
-v skip_verification
-v skipverification

"""
parser = argparse.ArgumentParser(
Expand All @@ -43,7 +43,7 @@ def build_arg_parser():
action='store',
help='Password to use when connecting to vc')

parser.add_argument('-c', '--cleanup',
parser.add_argument('-c', '--cleardata',
action='store_true',
help='Clean up after sample run. ')

Expand Down
59 changes: 18 additions & 41 deletions samples/vsphere/common/sample_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,6 @@ def pp(value):
return output.getvalue()


def parse_cli_args():
"""
Parse the server IP and credential used by samples.
Use values from command line arguments if present, otherwise use values
from testbed.py
"""
# parse command line
parser = sample_cli.build_arg_parser()
args = parser.parse_args()
return process_cli_args(args)


def parse_cli_args_vm(vm_name):
"""
Parse the server IP, credential and vm name used by vcenter vm samples.
Expand All @@ -51,10 +39,7 @@ def parse_cli_args_vm(vm_name):
parser.add_argument('-n', '--vm_name',
action='store',
help='Name of the testing vm')
args = parser.parse_args()

server, username, password, cleardata, skip_verification = \
process_cli_args(args)
args = process_cli_args(parser.parse_args())

if args.vm_name:
vm_name = args.vm_name
Expand All @@ -64,45 +49,37 @@ def parse_cli_args_vm(vm_name):
raise Exception("vm name is required")
print("vm name = {}".format(vm_name))

return server, username, password, cleardata, skip_verification, vm_name
return args.server, args.username, args.password, args.cleardata, \
args.skipverification, vm_name


def process_cli_args(args):
"""
Process server IP and credential args.
Verify if required inputs (server, username and password) are provided.
If they are not passed through cmd arguments, we will try to get them from
testbed.py. If they are not configured in testbed.py either, we will raise
an exception to remind the user to provide them.
"""

if args.server:
server = args.server
else:
if not args.server:
print("Using vcenter server specified in testbed.py")
server = testbed.config['SERVER']
if not server:
args.server = testbed.config['SERVER']
if not args.server:
raise Exception("vcenter server is required")
print("vcenter server = {}".format(server))
print("vcenter server = {}".format(args.server))

if args.username:
username = args.username
else:
if not args.username:
print("Using vc user specified in testbed.py")
username = testbed.config['USERNAME']
if not username:
args.username = testbed.config['USERNAME']
if not args.username:
raise Exception("vc username is required")
print("vc username = {}".format(username))
print("vc username = {}".format(args.username))

if args.password:
password = args.password
else:
if not args.password:
print("Using vc password specified in testbed.py")
password = testbed.config['PASSWORD']

cleardata = args.cleanup
print("sample cleanup = {}".format(cleardata))

skip_verification = args.skipverification
print("skip server cert verification = {}".format(skip_verification))
args.password = testbed.config['PASSWORD']

return server, username, password, cleardata, skip_verification
return args


class Context(object):
Expand Down
59 changes: 36 additions & 23 deletions samples/vsphere/contentlibrary/ovfdeploy/deploy_ovf_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,27 +22,30 @@
except ImportError:
import urllib.request as urllib2

import atexit

from com.vmware.content.library_client import Item
from com.vmware.vcenter.ovf_client import LibraryItem
from pyVmomi import vim

from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.common.vim.helpers.vim_utils import (
get_obj, get_obj_by_moId, poweron_vm, poweroff_vm, delete_object)
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper


class DeployOvfTemplate(SampleBase):
class DeployOvfTemplate:
"""
Demonstrates the workflow to deploy an OVF library item to a resource pool.
Note: the sample needs an existing library item with an OVF template
and an existing cluster with resources for deploying the VM.
"""

def __init__(self):
SampleBase.__init__(self, self.__doc__)
self.servicemanager = None
self.client = None
self.helper = None
Expand All @@ -51,29 +54,37 @@ def __init__(self):
self.vm_obj = None
self.vm_name = None

def _options(self):
self.argparser.add_argument('-clustername',
'--clustername',
help='The name of the cluster to be used.')
self.argparser.add_argument('-libitemname',
'--libitemname',
help='The name of the library item to deploy.'
'The library item should contain an OVF package.')

def _setup(self):
self.cluster_name = self.args.clustername
assert self.cluster_name is not None
def setup(self):
parser = sample_cli.build_arg_parser()
parser.add_argument('-n', '--vm_name',
action='store',
help='Name of the testing vm')
parser.add_argument('-clustername',
'--clustername',
help='The name of the cluster to be used.')
parser.add_argument('-libitemname',
'--libitemname',
help='The name of the library item to deploy.'
'The library item should contain an OVF package.')
args = sample_util.process_cli_args(parser.parse_args())
self.lib_item_name = args.libitemname
self.cluster_name = args.clustername
self.vm_name = args.vm_name

self.servicemanager = ServiceManager(args.server,
args.username,
args.password,
args.skipverification)
self.servicemanager.connect()
atexit.register(self.servicemanager.disconnect)

self.lib_item_name = self.args.libitemname
assert self.lib_item_name is not None

self.servicemanager = self.get_service_manager()
self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification)
self.helper = ClsApiHelper(self.client, args.skipverification)

# Default VM name
self.vm_name = 'vm-' + str(generate_random_uuid())

def _execute(self):
def execute(self):

# Find the cluster's resource pool moid
cluster_obj = get_obj(self.servicemanager.content,
Expand Down Expand Up @@ -141,7 +152,7 @@ def deploy_ovf_template(self, lib_item_id, ovf_summary, deployment_target):
for error in result.error.errors:
print('OVF error: {}'.format(error.message))

def _cleanup(self):
def cleanup(self):
if self.vm_obj is not None:
# Power off the VM and wait for the power off operation to complete
poweroff_vm(self.servicemanager.content, self.vm_obj)
Expand All @@ -151,7 +162,9 @@ def _cleanup(self):

def main():
deploy_ovf_sample = DeployOvfTemplate()
deploy_ovf_sample.main()
deploy_ovf_sample.setup()
deploy_ovf_sample.execute()
deploy_ovf_sample.cleanup()


if __name__ == '__main__':
Expand Down
30 changes: 13 additions & 17 deletions samples/vsphere/sso/embedded_psc_sso_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,19 @@
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+'

from pprint import pprint
import requests

from com.vmware.cis.tagging_client import (Category, CategoryModel)
from com.vmware.cis_client import Session
from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.session import create_session_security_context
from vmware.vapi.security.sso import create_saml_bearer_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from com.vmware.cis.tagging_client import (Category, CategoryModel)

from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common import sso
from samples.vsphere.common.ssl_helper import get_unverified_context
from samples.vsphere.common.vapiconnect import create_unverified_session
from samples.vsphere.common.sample_util import parse_cli_args
from samples.vsphere.common import sso


class EmbeddedPscSsoWorkflow(object):
Expand All @@ -40,37 +39,34 @@ class EmbeddedPscSsoWorkflow(object):
"""

def __init__(self):
self.server = None
self.username = None
self.password = None
self.args = None
self.session = None
self.session_id = None
self.skip_verification = False
self.category_svc = None
self.category_id = None

def setup(self):
self.server, self.username, self.password, _, self.skip_verification = \
parse_cli_args()
parser = sample_cli.build_arg_parser()
self.args = sample_util.process_cli_args(parser.parse_args())

def run(self):
print('\n\n#### Example: Login to vCenter server with '
'embedded Platform Services Controller')

# Since the platform services controller is embedded, the sso server
# is the same as the vCenter server.
ssoUrl = 'https://{}/sts/STSService'.format(self.server)
ssoUrl = 'https://{}/sts/STSService'.format(self.args.server)

print('\nStep 1: Connect to the Single Sign-On URL and '
'retrieve the SAML bearer token.')

authenticator = sso.SsoAuthenticator(ssoUrl)
context = None
if self.skip_verification:
if self.args.skipverification:
context = get_unverified_context()
bearer_token = authenticator.get_bearer_saml_assertion(
self.username,
self.password,
self.args.username,
self.args.password,
delegatable=True,
ssl_context=context)

Expand All @@ -81,12 +77,12 @@ def run(self):

# The URL for the stub requests are made against the /api HTTP endpoint
# of the vCenter system.
vapi_url = 'https://{}/api'.format(self.server)
vapi_url = 'https://{}/api'.format(self.args.server)

# Create an authenticated stub configuration object that can be used to
# issue requests against vCenter.
session = requests.Session()
if self.skip_verification:
if self.args.skipverification:
session = create_unverified_session(session)
connector = get_requests_connector(session=session, url=vapi_url)
connector.set_security_context(sec_ctx)
Expand Down
Loading