1
0
mirror of https://github.com/vmware/vsphere-automation-sdk-python.git synced 2024-11-23 01:49:59 -05:00

remove logging_context, use print() instead to simplify sample output control

This commit is contained in:
Tianhao He 2017-01-23 14:28:03 -08:00
parent 2a40af9dd2
commit 3d2f044934
22 changed files with 137 additions and 286 deletions

View File

@ -1,44 +0,0 @@
[loggers]
keys=root,suds
[logger_root]
level=NOTSET
handlers=console,file
[logger_suds]
level=INFO
handlers=console,file
qualname=suds
propagate=0
[formatters]
keys=simple,complex
[formatter_simple]
format=%(asctime)s %(levelname)-8s %(name)-15s %(message)s
[formatter_complex]
format=%(asctime)s %(levelname)-8s %(name)-15s [%(module)s, %(lineno)d] %(message)s
[handlers]
keys=file,console
[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('/tmp/vsphereautomationpythonsdksamples.log',)
[handler_console]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)
[vmware.vapi.protocol.client.msg.json_connector]
processors=vmware.vapi.dsig.jsonlib.JSONSSOSigner
[vmware.vapi.protocol.server.msg.json_handler]
processors=vmware.vapi.dsig.jsonlib.JSONSSOVerifier

View File

@ -1,37 +0,0 @@
"""
* *******************************************************
* Copyright (c) VMware, Inc. 2013. All Rights Reserved.
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware'
__copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.'
from os import path
import logging.config
class LoggingContext(object):
logging.config.fileConfig(path.join(path.dirname(path.realpath(__file__)), '../../../logging.conf'), disable_existing_loggers=False)
@classmethod
def get_logger(cls, name):
return logging.getLogger(name)
def main():
logger = LoggingContext.get_logger(__name__)
logger.critical('critical')
logger.info('info')
logger.debug('debug')
# Start program
# just for testing
if __name__ == "__main__":
main()

View File

@ -15,10 +15,6 @@ __copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.'
import os import os
from suds.client import Client from suds.client import Client
from samples.vsphere.common.logging_context import LoggingContext
logger = LoggingContext.get_logger('samples.vsphere.common.lookup_service_helper')
class LookupServiceHelper(object): class LookupServiceHelper(object):
def __init__(self, wsdl_url, soap_url, skip_verification): def __init__(self, wsdl_url, soap_url, skip_verification):
@ -52,19 +48,19 @@ class LookupServiceHelper(object):
self.client = Client(url=self.wsdl_url, location=self.soap_url) self.client = Client(url=self.wsdl_url, location=self.soap_url)
assert self.client is not None assert self.client is not None
logger.info(self.client) print(self.client)
self.client.set_options(service='LsService', port='LsPort') self.client.set_options(service='LsService', port='LsPort')
self.managedObjectReference = self.client.factory.create('ns0:ManagedObjectReference') self.managedObjectReference = self.client.factory.create('ns0:ManagedObjectReference')
self.managedObjectReference._type = 'LookupServiceInstance' self.managedObjectReference._type = 'LookupServiceInstance'
self.managedObjectReference.value = 'ServiceInstance' self.managedObjectReference.value = 'ServiceInstance'
logger.debug(self.managedObjectReference) print(self.managedObjectReference)
lookupServiceContent = self.client.service.RetrieveServiceContent(self.managedObjectReference) lookupServiceContent = self.client.service.RetrieveServiceContent(self.managedObjectReference)
logger.debug(lookupServiceContent) print(lookupServiceContent)
self.serviceRegistration = lookupServiceContent.serviceRegistration self.serviceRegistration = lookupServiceContent.serviceRegistration
logger.info(self.serviceRegistration) print(self.serviceRegistration)
def find_sso_urls(self): def find_sso_urls(self):
""" """
@ -193,10 +189,10 @@ class LookupServiceHelper(object):
assert self.serviceRegistration is not None assert self.serviceRegistration is not None
lookupServiceRegistrationFilter = self.__create_filter_spec(product, service, endpoint, protocol) lookupServiceRegistrationFilter = self.__create_filter_spec(product, service, endpoint, protocol)
logger.debug(lookupServiceRegistrationFilter) print(lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter) result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
logger.debug(result) print(result)
assert len(result) > 0 assert len(result) > 0
# Support for MxN # Support for MxN
# return the results in a dictionary where key is NodeId and Value is Service URL # return the results in a dictionary where key is NodeId and Value is Service URL
@ -216,10 +212,10 @@ class LookupServiceHelper(object):
assert self.serviceRegistration is not None assert self.serviceRegistration is not None
lookupServiceRegistrationFilter = self.__create_filter_spec(product, service, endpoint, protocol) lookupServiceRegistrationFilter = self.__create_filter_spec(product, service, endpoint, protocol)
logger.debug(lookupServiceRegistrationFilter) print(lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter) result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
logger.debug(result) print(result)
assert len(result) > 0 assert len(result) > 0
urls = [] urls = []
@ -258,20 +254,20 @@ class LookupServiceHelper(object):
lookupServiceRegistrationServiceType = self.client.factory.create('ns0:LookupServiceRegistrationServiceType') lookupServiceRegistrationServiceType = self.client.factory.create('ns0:LookupServiceRegistrationServiceType')
lookupServiceRegistrationServiceType.product = 'com.vmware.cis' lookupServiceRegistrationServiceType.product = 'com.vmware.cis'
lookupServiceRegistrationServiceType.type = 'vcenterserver' lookupServiceRegistrationServiceType.type = 'vcenterserver'
logger.debug(lookupServiceRegistrationServiceType) print(lookupServiceRegistrationServiceType)
lookupServiceRegistrationEndpointType = self.client.factory.create('ns0:LookupServiceRegistrationEndpointType') lookupServiceRegistrationEndpointType = self.client.factory.create('ns0:LookupServiceRegistrationEndpointType')
lookupServiceRegistrationEndpointType.type = 'com.vmware.vim' lookupServiceRegistrationEndpointType.type = 'com.vmware.vim'
lookupServiceRegistrationEndpointType.protocol = 'vmomi' lookupServiceRegistrationEndpointType.protocol = 'vmomi'
logger.debug(lookupServiceRegistrationEndpointType) print(lookupServiceRegistrationEndpointType)
lookupServiceRegistrationFilter = self.client.factory.create('ns0:LookupServiceRegistrationFilter') lookupServiceRegistrationFilter = self.client.factory.create('ns0:LookupServiceRegistrationFilter')
lookupServiceRegistrationFilter.serviceType = lookupServiceRegistrationServiceType lookupServiceRegistrationFilter.serviceType = lookupServiceRegistrationServiceType
lookupServiceRegistrationFilter.endpointType = lookupServiceRegistrationEndpointType lookupServiceRegistrationFilter.endpointType = lookupServiceRegistrationEndpointType
logger.debug(lookupServiceRegistrationFilter) print(lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter) result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
logger.debug(result) print(result)
assert len(result) > 0 assert len(result) > 0
results_dict = {} results_dict = {}

View File

@ -16,12 +16,10 @@ __copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
from vmware.vapi.security.sso import create_saml_bearer_security_context from vmware.vapi.security.sso import create_saml_bearer_security_context
from samples.vsphere.common import sso from samples.vsphere.common import sso
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.common.lookup_service_helper import LookupServiceHelper from samples.vsphere.common.lookup_service_helper import LookupServiceHelper
from samples.common.ssl_helper import get_unverified_context from samples.common.ssl_helper import get_unverified_context
logger = LoggingContext.get_logger('samples.vsphere.common.platform_service_controller')
class PlatformServiceController(object): class PlatformServiceController(object):
@ -43,7 +41,7 @@ class PlatformServiceController(object):
""" """
Finds the SSO URL from the lookup service and retrieves the SAML token from STS URL Finds the SSO URL from the lookup service and retrieves the SAML token from STS URL
""" """
logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl)) print('Connecting to lookup service url: {0}'.format(self.lssoapurl))
self.lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, self.lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl,
soap_url=self.lssoapurl, soap_url=self.lssoapurl,
skip_verification=self.skip_verification) skip_verification=self.skip_verification)
@ -52,7 +50,7 @@ class PlatformServiceController(object):
self.stsurl = self.lookupservicehelper.find_sso_url() self.stsurl = self.lookupservicehelper.find_sso_url()
assert self.stsurl is not None assert self.stsurl is not None
logger.info('Retrieving a SAML bearer token from STS url : {0}'.format(self.stsurl)) print('Retrieving a SAML bearer token from STS url : {0}'.format(self.stsurl))
au = sso.SsoAuthenticator(self.stsurl) au = sso.SsoAuthenticator(self.stsurl)
context = None context = None
if self.skip_verification: if self.skip_verification:

View File

@ -17,11 +17,8 @@ __copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
import argparse import argparse
import traceback import traceback
from samples.vsphere.common.service_manager_factory import ServiceManagerFactory from samples.vsphere.common.service_manager_factory import ServiceManagerFactory
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.common.sample_config import SampleConfig from samples.vsphere.common.sample_config import SampleConfig
logger = LoggingContext.get_logger(__name__)
class SampleBase(object): class SampleBase(object):
def __init__(self, description): def __init__(self, description):
@ -56,7 +53,7 @@ class SampleBase(object):
else: else:
self.server = self.args.server self.server = self.args.server
assert self.server is not None assert self.server is not None
logger.info('server: {0}'.format(self.server)) print('server: {0}'.format(self.server))
if self.args.username is None: if self.args.username is None:
self.username = SampleConfig.get_username() # look for username in the sample config self.username = SampleConfig.get_username() # look for username in the sample config
@ -88,7 +85,6 @@ class SampleBase(object):
attr() # calling the method attr() # calling the method
except Exception as e: except Exception as e:
# print the exception and move on to the cleanup stage if cleardata is set to True. # print the exception and move on to the cleanup stage if cleardata is set to True.
logger.exception(e)
traceback.print_exc() traceback.print_exc()
if bool(self.cleardata) is not True: if bool(self.cleardata) is not True:
# re-throw the exception # re-throw the exception

View File

@ -15,12 +15,9 @@ __copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
from pyVim.connect import SmartConnect, Disconnect from pyVim.connect import SmartConnect, Disconnect
from samples.vsphere.common import vapiconnect from samples.vsphere.common import vapiconnect
from samples.vsphere.common.logging_context import LoggingContext
from samples.common.ssl_helper import get_unverified_context from samples.common.ssl_helper import get_unverified_context
logger = LoggingContext.get_logger('samples.vsphere.common.service_manager')
class ServiceManager(object): class ServiceManager(object):
""" """
@ -64,7 +61,7 @@ class ServiceManager(object):
self.vim_uuid = self.content.about.instanceUuid self.vim_uuid = self.content.about.instanceUuid
def disconnect(self): def disconnect(self):
logger.info('disconnecting the session') print('disconnecting the session')
vapiconnect.logout(self.stub_config) vapiconnect.logout(self.stub_config)
Disconnect(self.si) Disconnect(self.si)

View File

@ -15,7 +15,6 @@ except ImportError:
from com.vmware.content.library.item_client import UpdateSessionModel from com.vmware.content.library.item_client import UpdateSessionModel
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
@ -23,8 +22,6 @@ from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.content_update')
class ContentUpdate(SampleBase): class ContentUpdate(SampleBase):
""" """
@ -84,14 +81,14 @@ class ContentUpdate(SampleBase):
item_name=self.ISO_ITEM_NAME, item_name=self.ISO_ITEM_NAME,
item_description='Sample iso file', item_description='Sample iso file',
item_type='iso') item_type='iso')
logger.info('ISO Library item version (on creation) {0}:'.format( print('ISO Library item version (on creation) {0}:'.format(
self.get_item_version(iso_item_id))) self.get_item_version(iso_item_id)))
iso_files_map = self.helper.get_iso_file_map(item_filename=self.ISO_FILE_1, iso_files_map = self.helper.get_iso_file_map(item_filename=self.ISO_FILE_1,
disk_filename=self.ISO_FILE_1) disk_filename=self.ISO_FILE_1)
self.helper.upload_files(library_item_id=iso_item_id, files_map=iso_files_map) self.helper.upload_files(library_item_id=iso_item_id, files_map=iso_files_map)
original_version = self.get_item_version(iso_item_id) original_version = self.get_item_version(iso_item_id)
logger.info('ISO Library item version (on original content upload) {0}:'.format( print('ISO Library item version (on original content upload) {0}:'.format(
original_version)) original_version))
session_id = self.client.upload_service.create( session_id = self.client.upload_service.create(
@ -105,7 +102,7 @@ class ContentUpdate(SampleBase):
self.client.upload_service.complete(session_id) self.client.upload_service.complete(session_id)
self.client.upload_service.delete(session_id) self.client.upload_service.delete(session_id)
updated_version = self.get_item_version(iso_item_id) updated_version = self.get_item_version(iso_item_id)
logger.info('ISO Library item version (after content update): {0}'.format( print('ISO Library item version (after content update): {0}'.format(
updated_version)) updated_version))
assert updated_version > original_version, 'content update should increase the version' assert updated_version > original_version, 'content update should increase the version'
@ -127,16 +124,16 @@ class ContentUpdate(SampleBase):
item_description='Sample simple VM template', item_description='Sample simple VM template',
item_type='ovf') item_type='ovf')
assert ovf_item_id is not None assert ovf_item_id is not None
logger.info('Library item created id: {0}'.format(ovf_item_id)) print('Library item created id: {0}'.format(ovf_item_id))
logger.info('OVF Library item version (at creation) {0}:'.format( print('OVF Library item version (at creation) {0}:'.format(
self.get_item_version(ovf_item_id))) self.get_item_version(ovf_item_id)))
# Upload a VM template to the CL # Upload a VM template to the CL
ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR) ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
self.helper.upload_files(library_item_id=ovf_item_id, files_map=ovf_files_map) self.helper.upload_files(library_item_id=ovf_item_id, files_map=ovf_files_map)
logger.info('Uploaded ovf and vmdk files to library item {0}'.format(ovf_item_id)) print('Uploaded ovf and vmdk files to library item {0}'.format(ovf_item_id))
original_version = self.get_item_version(ovf_item_id) original_version = self.get_item_version(ovf_item_id)
logger.info('OVF Library item version (on original content upload): {0}'.format( print('OVF Library item version (on original content upload): {0}'.format(
original_version)) original_version))
# Create a new session and perform content update # Create a new session and perform content update
@ -145,7 +142,7 @@ class ContentUpdate(SampleBase):
client_token=generate_random_uuid()) client_token=generate_random_uuid())
existing_files = self.client.upload_file_service.list(session_id) existing_files = self.client.upload_file_service.list(session_id)
for file in existing_files: for file in existing_files:
logger.info('deleting {0}'.format(file.name)) print('deleting {0}'.format(file.name))
self.client.upload_file_service.remove(session_id, file.name) self.client.upload_file_service.remove(session_id, file.name)
ovf_files_map = self.helper.get_ovf_files_map( ovf_files_map = self.helper.get_ovf_files_map(
ovf_location=ClsApiHelper.PLAIN_OVF_RELATIVE_DIR) ovf_location=ClsApiHelper.PLAIN_OVF_RELATIVE_DIR)
@ -153,7 +150,7 @@ class ContentUpdate(SampleBase):
self.client.upload_service.complete(session_id) self.client.upload_service.complete(session_id)
self.client.upload_service.delete(session_id) self.client.upload_service.delete(session_id)
updated_version = self.get_item_version(ovf_item_id) updated_version = self.get_item_version(ovf_item_id)
logger.info('OVF Library item version (after content update): {0}'.format( print('OVF Library item version (after content update): {0}'.format(
updated_version)) updated_version))
assert updated_version > original_version, 'content update should increase the version' assert updated_version > original_version, 'content update should increase the version'
@ -165,7 +162,7 @@ class ContentUpdate(SampleBase):
def _cleanup(self): def _cleanup(self):
if self.local_library: if self.local_library:
self.client.local_library_service.delete(library_id=self.local_library.id) self.client.local_library_service.delete(library_id=self.local_library.id)
logger.info('Deleted Library Id: {0}'.format(self.local_library.id)) print('Deleted Library Id: {0}'.format(self.local_library.id))
def main(): def main():

View File

@ -18,7 +18,6 @@ from com.vmware.content.library_client import StorageBacking
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id
@ -27,9 +26,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved. -- VMware Confidential' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved. -- VMware Confidential'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary')
class LibraryCrud(SampleBase): class LibraryCrud(SampleBase):
""" """
Demonstrates the basic operations of a content library. The sample also Demonstrates the basic operations of a content library. The sample also
@ -68,12 +64,12 @@ class LibraryCrud(SampleBase):
if len(visible_cls) > 0: if len(visible_cls) > 0:
for visible_cl in visible_cls: for visible_cl in visible_cls:
get_visible_cl = self.client.local_library_service.get(visible_cl) get_visible_cl = self.client.local_library_service.get(visible_cl)
logger.info('Visible content library: {0} with id: {1}'.format(get_visible_cl.name, visible_cl)) print('Visible content library: {0} with id: {1}'.format(get_visible_cl.name, visible_cl))
# Find the datastore by the given datastore name using property collector # Find the datastore by the given datastore name using property collector
self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name) self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name)
assert self.datastore_id is not None assert self.datastore_id is not None
logger.info('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id)) print('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))
# Build the storage backing for the library to be created # Build the storage backing for the library to be created
storage_backings = [] storage_backings = []
@ -90,22 +86,22 @@ class LibraryCrud(SampleBase):
# Create a local content library backed the VC datastore using vAPIs # Create a local content library backed the VC datastore using vAPIs
library_id = self.client.local_library_service.create(create_spec=create_spec, library_id = self.client.local_library_service.create(create_spec=create_spec,
client_token=generate_random_uuid()) client_token=generate_random_uuid())
logger.info('Local library created: ID: {0}'.format(library_id)) print('Local library created: ID: {0}'.format(library_id))
# Retrieve the local content library # Retrieve the local content library
self.local_library = self.client.local_library_service.get(library_id) self.local_library = self.client.local_library_service.get(library_id)
logger.info('Retrieved library: ID: {0}'.format(self.local_library.id)) print('Retrieved library: ID: {0}'.format(self.local_library.id))
# Update the local content library # Update the local content library
update_spec = LibraryModel() update_spec = LibraryModel()
update_spec.description = "new description" update_spec.description = "new description"
self.client.local_library_service.update(library_id, update_spec) self.client.local_library_service.update(library_id, update_spec)
logger.info('Updated library description') print('Updated library description')
def _cleanup(self): def _cleanup(self):
if self.local_library: if self.local_library:
self.client.local_library_service.delete(library_id=self.local_library.id) self.client.local_library_service.delete(library_id=self.local_library.id)
logger.info('Deleted Library Id: {0}'.format(self.local_library.id)) print('Deleted Library Id: {0}'.format(self.local_library.id))
def main(): def main():

View File

@ -12,7 +12,6 @@
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
""" """
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
@ -23,9 +22,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.iso_mount')
class IsoMount(SampleBase): class IsoMount(SampleBase):
""" """
Demonstrates the content library ISO item mount and Demonstrates the content library ISO item mount and
@ -81,11 +77,11 @@ class IsoMount(SampleBase):
# Mount the iso item as a CDROM device # Mount the iso item as a CDROM device
device_id = self.client.iso_service.mount(library_item_id, vm_id) device_id = self.client.iso_service.mount(library_item_id, vm_id)
assert device_id is not None assert device_id is not None
logger.info('Mounted library item {0}' print('Mounted library item {0}'
' on vm {1} at device {2}'.format(self.iso_item_name, self.vm_name, device_id)) ' on vm {1} at device {2}'.format(self.iso_item_name, self.vm_name, device_id))
# Unmount the CDROM # Unmount the CDROM
self.client.iso_service.unmount(vm_id, device_id) self.client.iso_service.unmount(vm_id, device_id)
logger.info('Unmounted library item {0}' print('Unmounted library item {0}'
'from vm {1} mounted at device {2}'.format(self.iso_item_name, 'from vm {1} mounted at device {2}'.format(self.iso_item_name,
self.vm_name, device_id)) self.vm_name, device_id))
@ -93,7 +89,7 @@ class IsoMount(SampleBase):
def _cleanup(self): def _cleanup(self):
if self.local_library: if self.local_library:
self.client.local_library_service.delete(library_id=self.local_library.id) self.client.local_library_service.delete(library_id=self.local_library.id)
logger.info('Deleted Library Id: {0}'.format(self.local_library.id)) print('Deleted Library Id: {0}'.format(self.local_library.id))
def main(): def main():

View File

@ -27,14 +27,11 @@ from com.vmware.content.library.item_client import (DownloadSessionModel,
from com.vmware.content.library.item.downloadsession_client import File as DownloadSessionFile from com.vmware.content.library.item.downloadsession_client import File as DownloadSessionFile
from com.vmware.content.library.item.updatesession_client import File as UpdateSessionFile from com.vmware.content.library.item.updatesession_client import File as UpdateSessionFile
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.lib')
class ClsApiHelper(object): class ClsApiHelper(object):
""" """
@ -81,7 +78,7 @@ class ClsApiHelper(object):
# Create a local content library backed the VC datastore # Create a local content library backed the VC datastore
library_id = self.client.local_library_service.create(create_spec=create_spec, library_id = self.client.local_library_service.create(create_spec=create_spec,
client_token=generate_random_uuid()) client_token=generate_random_uuid())
logger.info('Local library created, ID: {0}'.format(library_id)) print('Local library created, ID: {0}'.format(library_id))
return library_id return library_id
@ -117,12 +114,12 @@ class ClsApiHelper(object):
item_description='Sample iso file', item_description='Sample iso file',
item_type='iso') item_type='iso')
assert library_item_id is not None assert library_item_id is not None
logger.info('Library item created id: {0}'.format(library_item_id)) print('Library item created id: {0}'.format(library_item_id))
# Upload an iso file to above library item, use the filename as the item_filename # Upload an iso file to above library item, use the filename as the item_filename
iso_files_map = self.get_iso_file_map(item_filename=iso_filename, disk_filename=iso_filename) iso_files_map = self.get_iso_file_map(item_filename=iso_filename, disk_filename=iso_filename)
self.upload_files(library_item_id=library_item_id, files_map=iso_files_map) self.upload_files(library_item_id=library_item_id, files_map=iso_files_map)
logger.info('Uploaded iso file to library item {0}'.format(library_item_id)) print('Uploaded iso file to library item {0}'.format(library_item_id))
return library_item_id return library_item_id
def get_iso_file_map(self, item_filename, disk_filename): def get_iso_file_map(self, item_filename, disk_filename):

View File

@ -24,7 +24,6 @@ from pyVmomi import vim
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vim.helpers.vim_utils import ( from samples.vsphere.vim.helpers.vim_utils import (
@ -34,9 +33,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.deploy_ovf_template')
class DeployOvfTemplate(SampleBase): class DeployOvfTemplate(SampleBase):
""" """
Demonstrates the workflow to deploy an OVF library item to a resource pool. Demonstrates the workflow to deploy an OVF library item to a resource pool.
@ -82,7 +78,7 @@ class DeployOvfTemplate(SampleBase):
cluster_obj = get_obj(self.servicemanager.content, cluster_obj = get_obj(self.servicemanager.content,
[vim.ClusterComputeResource], self.cluster_name) [vim.ClusterComputeResource], self.cluster_name)
assert cluster_obj is not None assert cluster_obj is not None
logger.info("Cluster Moref: {0}".format(cluster_obj)) print("Cluster Moref: {0}".format(cluster_obj))
deployment_target = LibraryItem.DeploymentTarget( deployment_target = LibraryItem.DeploymentTarget(
resource_pool_id=cluster_obj.resourcePool._GetMoId()) resource_pool_id=cluster_obj.resourcePool._GetMoId())
@ -97,7 +93,7 @@ class DeployOvfTemplate(SampleBase):
ovf_summary = self.client.ovf_lib_item_service.filter(ovf_library_item_id=lib_item_id, ovf_summary = self.client.ovf_lib_item_service.filter(ovf_library_item_id=lib_item_id,
target=deployment_target) target=deployment_target)
logger.info('Found an OVF template :{0} to deploy.'.format(ovf_summary.name)) print('Found an OVF template :{0} to deploy.'.format(ovf_summary.name))
# Deploy the ovf template # Deploy the ovf template
self.deploy_ovf_template(lib_item_id, ovf_summary, deployment_target) self.deploy_ovf_template(lib_item_id, ovf_summary, deployment_target)
@ -125,13 +121,13 @@ class DeployOvfTemplate(SampleBase):
# The type and ID of the target deployment is available in the deployment result. # The type and ID of the target deployment is available in the deployment result.
if result.succeeded: if result.succeeded:
logger.info('Deployment successful. Result resource: {0}, ID: {1}' print('Deployment successful. Result resource: {0}, ID: {1}'
.format(result.resource_id.type, result.resource_id.id)) .format(result.resource_id.type, result.resource_id.id))
self.vm_id = result.resource_id.id self.vm_id = result.resource_id.id
error = result.error error = result.error
if error is not None: if error is not None:
for warning in error.warnings: for warning in error.warnings:
logger.warn('OVF warning: {}'.format(warning.message)) print('OVF warning: {}'.format(warning.message))
# Power on the VM and wait for the power on operation to be completed # Power on the VM and wait for the power on operation to be completed
self.vm_obj = get_obj_by_moId(self.servicemanager.content, self.vm_obj = get_obj_by_moId(self.servicemanager.content,
@ -140,9 +136,9 @@ class DeployOvfTemplate(SampleBase):
poweron_vm(self.servicemanager.content, self.vm_obj) poweron_vm(self.servicemanager.content, self.vm_obj)
else: else:
logger.error('Deployment failed.') print('Deployment failed.')
for error in result.error.errors: for error in result.error.errors:
logger.error('OVF error: {}'.format(error.message)) print('OVF error: {}'.format(error.message))
def _cleanup(self): def _cleanup(self):
if self.vm_obj is not None: if self.vm_obj is not None:

View File

@ -23,7 +23,6 @@ from com.vmware.content_client import LibraryModel
from com.vmware.content.library_client import ItemModel, StorageBacking from com.vmware.content.library_client import ItemModel, StorageBacking
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id from samples.vsphere.vim.helpers.get_datastore_by_name import get_datastore_id
@ -33,9 +32,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.ovef_import_export')
class OvfImportExport(SampleBase): class OvfImportExport(SampleBase):
""" """
Demonstrates the workflow to import an OVF package into the content library, Demonstrates the workflow to import an OVF package into the content library,
@ -74,7 +70,7 @@ class OvfImportExport(SampleBase):
# Find the datastore by the given datastore name using property collector # Find the datastore by the given datastore name using property collector
self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name) self.datastore_id = get_datastore_id(service_manager=self.servicemanager, datastore_name=self.datastore_name)
assert self.datastore_id is not None assert self.datastore_id is not None
logger.info('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id)) print('DataStore: {0} ID: {1}'.format(self.datastore_name, self.datastore_id))
# Build the storage backing for the library to be created # Build the storage backing for the library to be created
storage_backings = [] storage_backings = []
@ -91,7 +87,7 @@ class OvfImportExport(SampleBase):
# Create a local content library backed the VC datastore using vAPIs # Create a local content library backed the VC datastore using vAPIs
library_id = self.client.local_library_service.create(create_spec=create_spec, library_id = self.client.local_library_service.create(create_spec=create_spec,
client_token=generate_random_uuid()) client_token=generate_random_uuid())
logger.info('Local library created: ID: {0}'.format(library_id)) print('Local library created: ID: {0}'.format(library_id))
self.local_library = self.client.local_library_service.get(library_id) self.local_library = self.client.local_library_service.get(library_id)
# Create a new library item in the content library for uploading the files # Create a new library item in the content library for uploading the files
@ -101,23 +97,23 @@ class OvfImportExport(SampleBase):
item_type='ovf') item_type='ovf')
assert self.library_item_id is not None assert self.library_item_id is not None
assert self.client.library_item_service.get(self.library_item_id) is not None assert self.client.library_item_service.get(self.library_item_id) is not None
logger.info('Library item created id: {0}'.format(self.library_item_id)) print('Library item created id: {0}'.format(self.library_item_id))
# Upload a VM template to the CL # Upload a VM template to the CL
ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR) ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
self.helper.upload_files(library_item_id=self.library_item_id, files_map=ovf_files_map) self.helper.upload_files(library_item_id=self.library_item_id, files_map=ovf_files_map)
logger.info('Uploaded ovf and vmdk files to library item {0}'.format(self.library_item_id)) print('Uploaded ovf and vmdk files to library item {0}'.format(self.library_item_id))
# Download the library item from the CL # Download the library item from the CL
temp_dir = tempfile.mkdtemp(prefix='simpleVmTemplate-') temp_dir = tempfile.mkdtemp(prefix='simpleVmTemplate-')
logger.info('Downloading library item {0} to directory {1}'.format(self.library_item_id, temp_dir)) print('Downloading library item {0} to directory {1}'.format(self.library_item_id, temp_dir))
downloaded_files_map = self.helper.download_files(library_item_id=self.library_item_id, directory=temp_dir) downloaded_files_map = self.helper.download_files(library_item_id=self.library_item_id, directory=temp_dir)
assert len(downloaded_files_map) == len(ovf_files_map) assert len(downloaded_files_map) == len(ovf_files_map)
def _cleanup(self): def _cleanup(self):
if self.local_library: if self.local_library:
self.client.local_library_service.delete(library_id=self.local_library.id) self.client.local_library_service.delete(library_id=self.local_library.id)
logger.info('Deleted Library Id: {0}'.format(self.local_library.id)) print('Deleted Library Id: {0}'.format(self.local_library.id))
def main(): def main():

View File

@ -22,7 +22,6 @@ from com.vmware.content.library_client import (ItemModel, PublishInfo,
StorageBacking, SubscriptionInfo) StorageBacking, SubscriptionInfo)
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.contentlibrary.lib.cls_sync_helper import ClsSyncHelper from samples.vsphere.contentlibrary.lib.cls_sync_helper import ClsSyncHelper
@ -31,9 +30,6 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.library_publish_subscribe')
class LibraryPublishSubscribe(SampleBase): class LibraryPublishSubscribe(SampleBase):
""" """
Demonstrates the basic sync workflow to publish and subscribe content libraries. Demonstrates the basic sync workflow to publish and subscribe content libraries.
@ -74,11 +70,11 @@ class LibraryPublishSubscribe(SampleBase):
# Create a published library backed the VC datastore using vAPIs # Create a published library backed the VC datastore using vAPIs
self.pub_lib_id = self.create_published_library(storage_backings) self.pub_lib_id = self.create_published_library(storage_backings)
assert self.pub_lib_id is not None assert self.pub_lib_id is not None
logger.info('Published library created: ID: {0}'.format(self.pub_lib_id)) print('Published library created: ID: {0}'.format(self.pub_lib_id))
pub_lib = self.client.local_library_service.get(self.pub_lib_id) pub_lib = self.client.local_library_service.get(self.pub_lib_id)
pub_lib_url = pub_lib.publish_info.publish_url pub_lib_url = pub_lib.publish_info.publish_url
assert pub_lib_url is not None assert pub_lib_url is not None
logger.info('Publish URL : {0}'.format(pub_lib_url)) print('Publish URL : {0}'.format(pub_lib_url))
# Create a library item in the published library # Create a library item in the published library
pub_lib_item_id = self.helper.create_iso_library_item(self.pub_lib_id, 'item_1', self.DEMO_FILENAME) pub_lib_item_id = self.helper.create_iso_library_item(self.pub_lib_id, 'item_1', self.DEMO_FILENAME)
@ -88,13 +84,13 @@ class LibraryPublishSubscribe(SampleBase):
sub_lib, sub_spec = self.create_subcribed_library(storage_backings, sub_lib, sub_spec = self.create_subcribed_library(storage_backings,
pub_lib_url) pub_lib_url)
assert self.sub_lib_id is not None assert self.sub_lib_id is not None
logger.info('Subscribed library created: ID: {0}'.format(self.sub_lib_id)) print('Subscribed library created: ID: {0}'.format(self.sub_lib_id))
# It is not mandatory to verify sync, it is just for demonstrating the sample workflow. # It is not mandatory to verify sync, it is just for demonstrating the sample workflow.
assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC). assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC).
verify_library_sync(self.pub_lib_id, sub_lib)) verify_library_sync(self.pub_lib_id, sub_lib))
sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id) sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
logger.info('Subscribed library synced : {0}'.format(sub_lib.last_sync_time)) print('Subscribed library synced : {0}'.format(sub_lib.last_sync_time))
sub_item_ids = self.client.library_item_service.list(self.sub_lib_id) sub_item_ids = self.client.library_item_service.list(self.sub_lib_id)
assert len(sub_item_ids) == 1, 'Subscribed library must have one item' assert len(sub_item_ids) == 1, 'Subscribed library must have one item'
@ -108,14 +104,14 @@ class LibraryPublishSubscribe(SampleBase):
assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC). assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC).
verify_library_sync(self.pub_lib_id, sub_lib)) verify_library_sync(self.pub_lib_id, sub_lib))
sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id) sub_lib = self.client.subscribed_library_service.get(self.sub_lib_id)
logger.info('Subscribed library synced : {0}'.format(sub_lib.last_sync_time)) print('Subscribed library synced : {0}'.format(sub_lib.last_sync_time))
# List the subscribed items. # List the subscribed items.
sub_item_ids = self.client.library_item_service.list(self.sub_lib_id) sub_item_ids = self.client.library_item_service.list(self.sub_lib_id)
assert len(sub_item_ids) == 2, 'Subscribed library must have two items' assert len(sub_item_ids) == 2, 'Subscribed library must have two items'
for sub_item_id in sub_item_ids : for sub_item_id in sub_item_ids :
sub_item = self.client.library_item_service.get(sub_item_id) sub_item = self.client.library_item_service.get(sub_item_id)
logger.info('Subscribed item : {0}'.format(sub_item.name)) print('Subscribed item : {0}'.format(sub_item.name))
# Change the subscribed library to be on-demand # Change the subscribed library to be on-demand
sub_spec.subscription_info.on_demand = True sub_spec.subscription_info.on_demand = True
@ -124,7 +120,7 @@ class LibraryPublishSubscribe(SampleBase):
# Evict the cached content of the first subscribed library item # Evict the cached content of the first subscribed library item
self.client.subscribed_item_service.evict(sub_item_id) self.client.subscribed_item_service.evict(sub_item_id)
sub_item = self.client.library_item_service.get(sub_item_id) sub_item = self.client.library_item_service.get(sub_item_id)
logger.info('Subscribed item evicted : {0}'.format(sub_item.name)) print('Subscribed item evicted : {0}'.format(sub_item.name))
assert not sub_item.cached, 'Subscribed item must not be cached' assert not sub_item.cached, 'Subscribed item must not be cached'
# Force synchronize the subscribed library item to fetch and cache the content # Force synchronize the subscribed library item to fetch and cache the content
@ -133,7 +129,7 @@ class LibraryPublishSubscribe(SampleBase):
assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC). assert (ClsSyncHelper(self.client, self.SYNC_TIMEOUT_SEC).
verify_item_sync(sub_item_id)) verify_item_sync(sub_item_id))
sub_item = self.client.library_item_service.get(sub_item_id) sub_item = self.client.library_item_service.get(sub_item_id)
logger.info('Subscribed item force sync : {0}'.format(sub_item.name)) print('Subscribed item force sync : {0}'.format(sub_item.name))
assert sub_item.cached, 'Subscribed item must be cached' assert sub_item.cached, 'Subscribed item must be cached'
def create_published_library(self, storage_backings): def create_published_library(self, storage_backings):
@ -183,11 +179,11 @@ class LibraryPublishSubscribe(SampleBase):
def _cleanup(self): def _cleanup(self):
if self.sub_lib_id: if self.sub_lib_id:
self.client.subscribed_library_service.delete(self.sub_lib_id) self.client.subscribed_library_service.delete(self.sub_lib_id)
logger.info('Deleted subscribed library Id: {0}'.format(self.sub_lib_id)) print('Deleted subscribed library Id: {0}'.format(self.sub_lib_id))
if self.pub_lib_id: if self.pub_lib_id:
self.client.local_library_service.delete(self.pub_lib_id) self.client.local_library_service.delete(self.pub_lib_id)
logger.info('Deleted published library Id : {0}'.format(self.pub_lib_id)) print('Deleted published library Id : {0}'.format(self.pub_lib_id))
def main(): def main():

View File

@ -18,7 +18,6 @@ except ImportError:
import urllib.request as urllib2 import urllib.request as urllib2
from com.vmware.vcenter.ovf_client import LibraryItem from com.vmware.vcenter.ovf_client import LibraryItem
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.logging_context import LoggingContext
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
@ -28,8 +27,6 @@ from samples.vsphere.vcenter.helper.vm_helper import get_vm
__author__ = 'VMware, Inc.' __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
logger = LoggingContext.get_logger('samples.vsphere.contentlibrary.vm_template_capture')
class CaptureVMTemplateToContentLibrary(SampleBase): class CaptureVMTemplateToContentLibrary(SampleBase):
""" """
@ -76,7 +73,7 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
storage_backings = self.helper.create_storage_backings(self.servicemanager, storage_backings = self.helper.create_storage_backings(self.servicemanager,
self.datastore_name) self.datastore_name)
logger.info('Creating Content Library') print('Creating Content Library')
# Create a content library # Create a content library
library_id = self.helper.create_local_library(storage_backings, library_id = self.helper.create_local_library(storage_backings,
self.cl_name) self.cl_name)
@ -91,7 +88,7 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
self.library_item_id = self.capture_source_vm(vm_id, param) self.library_item_id = self.capture_source_vm(vm_id, param)
assert self.library_item_id is not None assert self.library_item_id is not None
assert self.client.library_item_service.get(self.library_item_id) is not None assert self.client.library_item_service.get(self.library_item_id) is not None
logger.info('The VM id : {0} is captured as vm template library item id : {1}'.format print('The VM id : {0} is captured as vm template library item id : {1}'.format
(vm_id, self.library_item_id)) (vm_id, self.library_item_id))
def capture_source_vm(self, vm_id, param): def capture_source_vm(self, vm_id, param):
@ -113,7 +110,7 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
# delete the local library. # delete the local library.
if self.content_library is not None: if self.content_library is not None:
self.client.local_library_service.delete(library_id=self.content_library.id) self.client.local_library_service.delete(library_id=self.content_library.id)
logger.info('Deleted Library Id: {0}'.format print('Deleted Library Id: {0}'.format
(self.content_library.id)) (self.content_library.id))

View File

@ -19,9 +19,6 @@ from com.vmware.content_client import Library
from com.vmware.vcenter.inventory_client import Datastore from com.vmware.vcenter.inventory_client import Datastore
from samples.vsphere.vim.helpers.vim_utils import get_obj_by_moId from samples.vsphere.vim.helpers.vim_utils import get_obj_by_moId
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
logger = LoggingContext.get_logger('samples.vsphere.inventory.find_cl_datastore')
class FindClDatastore(SampleBase): class FindClDatastore(SampleBase):
@ -57,11 +54,11 @@ class FindClDatastore(SampleBase):
def _execute(self): def _execute(self):
library_model = self.find_cl_by_name() library_model = self.find_cl_by_name()
assert library_model is not None assert library_model is not None
logger.info('Found CL: {0} Id: {1}'.format(library_model.name, library_model.id)) print('Found CL: {0} Id: {1}'.format(library_model.name, library_model.id))
datastore_ids = [] datastore_ids = []
for storage_backing in library_model.storage_backings: for storage_backing in library_model.storage_backings:
logger.info('Storage backing datastore id: {0} storage uri:{1}' print('Storage backing datastore id: {0} storage uri:{1}'
.format(storage_backing.datastore_id, storage_backing.storage_uri)) .format(storage_backing.datastore_id, storage_backing.storage_uri))
if storage_backing.datastore_id is not None: if storage_backing.datastore_id is not None:
datastore_ids.append(storage_backing.datastore_id) datastore_ids.append(storage_backing.datastore_id)
@ -69,11 +66,11 @@ class FindClDatastore(SampleBase):
self.datastore_vim_objs = [] # for testing only self.datastore_vim_objs = [] # for testing only
datastores = self.inv_datastore_service.find(datastore_ids) datastores = self.inv_datastore_service.find(datastore_ids)
for moid, info in datastores.items(): for moid, info in datastores.items():
logger.info('Datastore moid: {0} type: {1}'.format(moid, info.type)) print('Datastore moid: {0} type: {1}'.format(moid, info.type))
vim_type = self.get_vim_type(info.type) vim_type = self.get_vim_type(info.type)
datastore = get_obj_by_moId(self.servicemanager.content, [vim_type], moid) datastore = get_obj_by_moId(self.servicemanager.content, [vim_type], moid)
assert datastore is not None assert datastore is not None
logger.info('Vim object retrieved for datastore: {0}'.format(datastore.name)) print('Vim object retrieved for datastore: {0}'.format(datastore.name))
self.datastore_vim_objs.append(datastore) # for testing only self.datastore_vim_objs.append(datastore) # for testing only
def _cleanup(self): def _cleanup(self):

View File

@ -16,9 +16,6 @@ __copyright__ = 'Copyright 2014 VMware, Inc. All rights reserved.'
import argparse import argparse
from samples.vsphere.common.sample_config import SampleConfig from samples.vsphere.common.sample_config import SampleConfig
from samples.vsphere.common.lookup_service_helper import LookupServiceHelper from samples.vsphere.common.lookup_service_helper import LookupServiceHelper
from samples.vsphere.common.logging_context import LoggingContext
logger = LoggingContext.get_logger('samples.vsphere.lookupservice.print_services')
class PrintServices(object): class PrintServices(object):
@ -46,35 +43,35 @@ class PrintServices(object):
else: else:
self.lswsdlurl = self.args.lswsdlurl self.lswsdlurl = self.args.lswsdlurl
assert self.lswsdlurl is not None assert self.lswsdlurl is not None
logger.info('lswsdlurl: {0}'.format(self.lswsdlurl)) print('lswsdlurl: {0}'.format(self.lswsdlurl))
if self.args.lssoapurl is None: if self.args.lssoapurl is None:
self.lssoapurl = SampleConfig.get_ls_soap_url() # look for lookup service SOAP URL in the sample config self.lssoapurl = SampleConfig.get_ls_soap_url() # look for lookup service SOAP URL in the sample config
else: else:
self.lssoapurl = self.args.lssoapurl self.lssoapurl = self.args.lssoapurl
assert self.lssoapurl is not None assert self.lssoapurl is not None
logger.info('lssoapurl: {0}'.format(self.lssoapurl)) print('lssoapurl: {0}'.format(self.lssoapurl))
def execute(self): def execute(self):
logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl)) print('Connecting to lookup service url: {0}'.format(self.lssoapurl))
lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, soap_url=self.lssoapurl) lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, soap_url=self.lssoapurl)
lookupservicehelper.connect() lookupservicehelper.connect()
# print the PSC nodes and SSO service endpoint URLs # print the PSC nodes and SSO service endpoint URLs
for index, sso_url in enumerate(lookupservicehelper.find_sso_urls(), start=1): for index, sso_url in enumerate(lookupservicehelper.find_sso_urls(), start=1):
logger.info('=============================') print('=============================')
logger.info('PSC node: {0}'.format(index)) print('PSC node: {0}'.format(index))
logger.info(' SSO URL: {0}'.format(sso_url)) print(' SSO URL: {0}'.format(sso_url))
logger.info('=============================') print('=============================')
# print the mgmt (vCenter Server) nodes and some of the critical service endpoint URLs # print the mgmt (vCenter Server) nodes and some of the critical service endpoint URLs
for instance_name, node_id in lookupservicehelper.find_mgmt_nodes().items(): for instance_name, node_id in lookupservicehelper.find_mgmt_nodes().items():
logger.info('=============================') print('=============================')
logger.info('Mgmt node instance name: {0} node_id: {1}'.format(instance_name, node_id)) print('Mgmt node instance name: {0} node_id: {1}'.format(instance_name, node_id))
logger.info(' VAPI URL: {0}'.format(lookupservicehelper.find_vapi_url(node_id))) print(' VAPI URL: {0}'.format(lookupservicehelper.find_vapi_url(node_id)))
logger.info(' VIM URL: {0}'.format(lookupservicehelper.find_vim_url(node_id))) print(' VIM URL: {0}'.format(lookupservicehelper.find_vim_url(node_id)))
logger.info(' SPBM URL: {0}'.format(lookupservicehelper.find_vim_pbm_url(node_id))) print(' SPBM URL: {0}'.format(lookupservicehelper.find_vim_pbm_url(node_id)))
logger.info('=============================') print('=============================')
def cleanup(self): def cleanup(self):
pass pass

View File

@ -21,9 +21,6 @@ from com.vmware.cis.tagging_client import (
Category, CategoryModel, Tag, TagAssociation) Category, CategoryModel, Tag, TagAssociation)
from samples.vsphere.vim.helpers.get_cluster_by_name import get_cluster_id from samples.vsphere.vim.helpers.get_cluster_by_name import get_cluster_id
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.common.logging_context import LoggingContext
logger = LoggingContext.get_logger('samples.vsphere.workflow.tagging_workflow')
class TaggingWorkflow(SampleBase): class TaggingWorkflow(SampleBase):
@ -71,27 +68,27 @@ class TaggingWorkflow(SampleBase):
if self.cluster_name is None: # for testing if self.cluster_name is None: # for testing
self.cluster_name = self.args.clustername self.cluster_name = self.args.clustername
assert self.cluster_name is not None assert self.cluster_name is not None
logger.info('Cluster Name: {0}'.format(self.cluster_name)) print('Cluster Name: {0}'.format(self.cluster_name))
if self.category_name is None: if self.category_name is None:
self.category_name = self.args.categoryname self.category_name = self.args.categoryname
assert self.category_name is not None assert self.category_name is not None
logger.info('Category Name: {0}'.format(self.category_name)) print('Category Name: {0}'.format(self.category_name))
if self.category_desc is None: if self.category_desc is None:
self.category_desc = self.args.categorydesc self.category_desc = self.args.categorydesc
assert self.category_desc is not None assert self.category_desc is not None
logger.info('Category Description: {0}'.format(self.category_desc)) print('Category Description: {0}'.format(self.category_desc))
if self.tag_name is None: if self.tag_name is None:
self.tag_name = self.args.tagname self.tag_name = self.args.tagname
assert self.tag_name is not None assert self.tag_name is not None
logger.info('Tag Name: {0}'.format(self.tag_name)) print('Tag Name: {0}'.format(self.tag_name))
if self.tag_desc is None: if self.tag_desc is None:
self.tag_desc = self.args.tagdesc self.tag_desc = self.args.tagdesc
assert self.tag_desc is not None assert self.tag_desc is not None
logger.info('Tag Description: {0}'.format(self.tag_desc)) print('Tag Description: {0}'.format(self.tag_desc))
if self.servicemanager is None: if self.servicemanager is None:
self.servicemanager = self.get_service_manager() self.servicemanager = self.get_service_manager()
@ -101,43 +98,43 @@ class TaggingWorkflow(SampleBase):
self.tag_association = TagAssociation(self.servicemanager.stub_config) self.tag_association = TagAssociation(self.servicemanager.stub_config)
def _execute(self): def _execute(self):
logger.info('List all the existing categories user has access to...') print('List all the existing categories user has access to...')
categories = self.category_svc.list() categories = self.category_svc.list()
if len(categories) > 0: if len(categories) > 0:
for category in categories: for category in categories:
logger.info('Found Category: {0}'.format(category)) print('Found Category: {0}'.format(category))
else: else:
logger.info('No Tag Category Found...') print('No Tag Category Found...')
logger.info('List all the existing tags user has access to...') print('List all the existing tags user has access to...')
tags = self.tag_svc.list() tags = self.tag_svc.list()
if len(tags) > 0: if len(tags) > 0:
for tag in tags: for tag in tags:
logger.info('Found Tag: {0}'.format(tag)) print('Found Tag: {0}'.format(tag))
else: else:
logger.info('No Tag Found...') print('No Tag Found...')
logger.info('creating a new tag category...') print('creating a new tag category...')
self.category_id = self.create_tag_category(self.category_name, self.category_desc, CategoryModel.Cardinality.MULTIPLE) self.category_id = self.create_tag_category(self.category_name, self.category_desc, CategoryModel.Cardinality.MULTIPLE)
assert self.category_id is not None assert self.category_id is not None
logger.info('Tag category created; Id: {0}'.format(self.category_id)) print('Tag category created; Id: {0}'.format(self.category_id))
logger.info("creating a new Tag...") print("creating a new Tag...")
self.tag_id = self.create_tag(self.tag_name, self.tag_desc, self.category_id) self.tag_id = self.create_tag(self.tag_name, self.tag_desc, self.category_id)
assert self.tag_id is not None assert self.tag_id is not None
logger.info('Tag created; Id: {0}'.format(self.tag_id)) print('Tag created; Id: {0}'.format(self.tag_id))
logger.info('updating the tag...') print('updating the tag...')
date_time = time.strftime('%d/%m/%Y %H:%M:%S') date_time = time.strftime('%d/%m/%Y %H:%M:%S')
self.update_tag(self.tag_id, 'Server Tag updated at ' + date_time) self.update_tag(self.tag_id, 'Server Tag updated at ' + date_time)
logger.info('Tag updated; Id: {0}'.format(self.tag_id)) print('Tag updated; Id: {0}'.format(self.tag_id))
logger.info('finding the cluster {0}'.format(self.cluster_name)) print('finding the cluster {0}'.format(self.cluster_name))
self.cluster_moid = get_cluster_id(service_manager=self.servicemanager, cluster_name=self.cluster_name) self.cluster_moid = get_cluster_id(service_manager=self.servicemanager, cluster_name=self.cluster_name)
assert self.cluster_moid is not None assert self.cluster_moid is not None
logger.info('Found cluster:{0} mo_id:{1}'.format('vAPISDKCluster', self.cluster_moid)) print('Found cluster:{0} mo_id:{1}'.format('vAPISDKCluster', self.cluster_moid))
logger.info('Tagging the cluster {0}...'.format(self.cluster_name)) print('Tagging the cluster {0}...'.format(self.cluster_name))
self.dynamic_id = DynamicID(type='ClusterComputeResource', id=self.cluster_moid) self.dynamic_id = DynamicID(type='ClusterComputeResource', id=self.cluster_moid)
self.tag_association.attach(tag_id=self.tag_id, object_id=self.dynamic_id) self.tag_association.attach(tag_id=self.tag_id, object_id=self.dynamic_id)
for tag_id in self.tag_association.list_attached_tags(self.dynamic_id): for tag_id in self.tag_association.list_attached_tags(self.dynamic_id):
@ -145,21 +142,21 @@ class TaggingWorkflow(SampleBase):
self.tag_attached = True self.tag_attached = True
break break
assert self.tag_attached assert self.tag_attached
logger.info('Tagged cluster: {0}'.format(self.cluster_moid)) print('Tagged cluster: {0}'.format(self.cluster_moid))
def _cleanup(self): def _cleanup(self):
try: try:
if self.tag_attached: if self.tag_attached:
self.tag_association.detach(self.tag_id, self.dynamic_id) self.tag_association.detach(self.tag_id, self.dynamic_id)
logger.info('Removed tag from cluster: {0}'.format(self.cluster_moid)) print('Removed tag from cluster: {0}'.format(self.cluster_moid))
if self.tag_id is not None: if self.tag_id is not None:
self.delete_tag(self.tag_id) self.delete_tag(self.tag_id)
logger.info('Tag deleted; Id: {0}'.format(self.tag_id)) print('Tag deleted; Id: {0}'.format(self.tag_id))
if self.category_id is not None: if self.category_id is not None:
self.delete_tag_category(self.category_id) self.delete_tag_category(self.category_id)
logger.info('Tag category deleted; Id: {0}'.format(self.category_id)) print('Tag category deleted; Id: {0}'.format(self.category_id))
except Exception as e: except Exception as e:
raise Exception(e) raise Exception(e)

View File

@ -16,10 +16,6 @@ __copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
from pyVmomi import vim from pyVmomi import vim
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.vim.helpers.vim_utils import get_obj from samples.vsphere.vim.helpers.vim_utils import get_obj
from samples.vsphere.common.logging_context import LoggingContext
# Get the logger #
logger = LoggingContext().get_logger('samples.vsphere.vim.helpers.get_cluster_by_name')
class GetClusterByName(SampleBase): class GetClusterByName(SampleBase):
@ -47,9 +43,9 @@ class GetClusterByName(SampleBase):
cluster_obj = get_obj(content, [vim.ClusterComputeResource], self.cluster_name) cluster_obj = get_obj(content, [vim.ClusterComputeResource], self.cluster_name)
if cluster_obj is not None: if cluster_obj is not None:
self.mo_id = cluster_obj._GetMoId() self.mo_id = cluster_obj._GetMoId()
logger.info('Cluster MoId: {0}'.format(self.mo_id)) print('Cluster MoId: {0}'.format(self.mo_id))
else: else:
logger.info('Cluster: {0} not found'.format(self.cluster_name)) print('Cluster: {0} not found'.format(self.cluster_name))
def _cleanup(self): def _cleanup(self):
pass pass

View File

@ -16,10 +16,6 @@ __copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
from pyVmomi import vim from pyVmomi import vim
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.vim.helpers.vim_utils import get_obj from samples.vsphere.vim.helpers.vim_utils import get_obj
from samples.vsphere.common.logging_context import LoggingContext
# Get the logger #
logger = LoggingContext().get_logger('samples.vsphere.vim.helpers.get_datastore_by_name')
class GetDatastoreByName(SampleBase): class GetDatastoreByName(SampleBase):
@ -47,9 +43,9 @@ class GetDatastoreByName(SampleBase):
datastore_obj = get_obj(content, [vim.Datastore], self.datastore_name) datastore_obj = get_obj(content, [vim.Datastore], self.datastore_name)
if datastore_obj is not None: if datastore_obj is not None:
self.mo_id = datastore_obj._GetMoId() self.mo_id = datastore_obj._GetMoId()
logger.info('Datastore MoId: {0}'.format(self.mo_id)) print('Datastore MoId: {0}'.format(self.mo_id))
else: else:
logger.info('Datastore: {0} not found'.format(self.datastore_name)) print('Datastore: {0} not found'.format(self.datastore_name))
def _cleanup(self): def _cleanup(self):
pass pass

View File

@ -14,10 +14,7 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.'
from pyVmomi import vim, vmodl from pyVmomi import vim, vmodl
from samples.vsphere.common.logging_context import LoggingContext
# Get the logger #
logger = LoggingContext().get_logger('samples.vsphere.vim.helpers.vim_utils')
_views = [] # list of container views _views = [] # list of container views
@ -54,12 +51,12 @@ def delete_object(content, mo):
""" """
Deletes a vsphere managed object and waits for the deletion to complete Deletes a vsphere managed object and waits for the deletion to complete
""" """
logger.info('Deleting {0}'.format(mo._GetMoId())) print('Deleting {0}'.format(mo._GetMoId()))
try: try:
wait_for_tasks(content, [mo.Destroy()]) wait_for_tasks(content, [mo.Destroy()])
logger.info('Deleted {0}'.format(mo._GetMoId())) print('Deleted {0}'.format(mo._GetMoId()))
except: except:
logger.error('Unexpected error while deleting managed object {0}'.format(mo._GetMoId())) print('Unexpected error while deleting managed object {0}'.format(mo._GetMoId()))
return False return False
return True return True
@ -71,12 +68,12 @@ def poweron_vm(content, mo):
if not isinstance(mo, vim.VirtualMachine): if not isinstance(mo, vim.VirtualMachine):
return False return False
logger.info('Powering on vm {0}'.format(mo._GetMoId())) print('Powering on vm {0}'.format(mo._GetMoId()))
try: try:
wait_for_tasks(content, [mo.PowerOn()]) wait_for_tasks(content, [mo.PowerOn()])
logger.info('{0} powered on successfully'.format(mo._GetMoId())) print('{0} powered on successfully'.format(mo._GetMoId()))
except: except:
logger.error('Unexpected error while powering on vm {0}'.format(mo._GetMoId())) print('Unexpected error while powering on vm {0}'.format(mo._GetMoId()))
return False return False
return True return True
@ -88,12 +85,12 @@ def poweroff_vm(content, mo):
if not isinstance(mo, vim.VirtualMachine): if not isinstance(mo, vim.VirtualMachine):
return False return False
logger.info('Powering off vm {0}'.format(mo._GetMoId())) print('Powering off vm {0}'.format(mo._GetMoId()))
try: try:
wait_for_tasks(content, [mo.PowerOff()]) wait_for_tasks(content, [mo.PowerOff()])
logger.info('{0} powered off successfully'.format(mo._GetMoId())) print('{0} powered off successfully'.format(mo._GetMoId()))
except: except:
logger.error('Unexpected error while powering off vm {0}'.format(mo._GetMoId())) print('Unexpected error while powering off vm {0}'.format(mo._GetMoId()))
return False return False
return True return True

View File

@ -28,12 +28,9 @@ from com.vmware.cis_client import Session
from vmware.vapi.security.sso import create_saml_bearer_security_context from vmware.vapi.security.sso import create_saml_bearer_security_context
from vmware.vapi.security.session import create_session_security_context from vmware.vapi.security.session import create_session_security_context
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from samples.vsphere.common.logging_context import LoggingContext
from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.lib.connect import get_requests_connector
from samples.common.ssl_helper import get_unverified_context from samples.common.ssl_helper import get_unverified_context
logger = LoggingContext.get_logger('samples.vsphere.workflow.connection_workflow')
class ConnectionWorkflow(object): class ConnectionWorkflow(object):
""" """
@ -77,16 +74,16 @@ class ConnectionWorkflow(object):
self.skip_verification = self.args.skipverification self.skip_verification = self.args.skipverification
def execute(self): def execute(self):
logger.info('vapi_url: {0}'.format(self.vapi_url)) print('vapi_url: {0}'.format(self.vapi_url))
# parse the URL and determine the scheme # parse the URL and determine the scheme
o = urlparse(self.vapi_url) o = urlparse(self.vapi_url)
assert o.scheme is not None assert o.scheme is not None
if o.scheme.lower() != 'https': if o.scheme.lower() != 'https':
logger.error('VAPI URL must be a https URL') print('VAPI URL must be a https URL')
raise Exception('VAPI URL must be a https URL') raise Exception('VAPI URL must be a https URL')
logger.info('sts_url: {0}'.format(self.sts_url)) print('sts_url: {0}'.format(self.sts_url))
logger.info('Initialize SsoAuthenticator and fetching SAML bearer token...') print('Initialize SsoAuthenticator and fetching SAML bearer token...')
authenticator = sso.SsoAuthenticator(self.sts_url) authenticator = sso.SsoAuthenticator(self.sts_url)
context = None context = None
if self.skip_verification: if self.skip_verification:
@ -96,10 +93,10 @@ class ConnectionWorkflow(object):
delegatable=True, delegatable=True,
ssl_context=context) ssl_context=context)
logger.info('Creating SAML Bearer Security Context...') print('Creating SAML Bearer Security Context...')
sec_ctx = create_saml_bearer_security_context(bearer_token) sec_ctx = create_saml_bearer_security_context(bearer_token)
logger.info('Connecting to VAPI provider and preparing stub configuration...') print('Connecting to VAPI provider and preparing stub configuration...')
session = requests.Session() session = requests.Session()
if self.skip_verification: if self.skip_verification:
session.verify = False session.verify = False
@ -110,17 +107,17 @@ class ConnectionWorkflow(object):
self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
self.session = Session(self.stub_config) self.session = Session(self.stub_config)
logger.info('Login to VAPI endpoint and get the session_id...') print('Login to VAPI endpoint and get the session_id...')
self.session_id = self.session.create() self.session_id = self.session.create()
logger.info('Update the VAPI connection with session_id...') print('Update the VAPI connection with session_id...')
session_sec_ctx = create_session_security_context(self.session_id) session_sec_ctx = create_session_security_context(self.session_id)
connector.set_security_context(session_sec_ctx) connector.set_security_context(session_sec_ctx)
def cleanup(self): def cleanup(self):
if self.session_id is not None: if self.session_id is not None:
self.disconnect() self.disconnect()
logger.info('VAPI session disconnected successfully...') print('VAPI session disconnected successfully...')
def disconnect(self): def disconnect(self):
self.session.delete() self.session.delete()

View File

@ -25,9 +25,6 @@ from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from com.vmware.cis.tagging_client import Tag from com.vmware.cis.tagging_client import Tag
from samples.vsphere.common.lookup_service_helper import LookupServiceHelper from samples.vsphere.common.lookup_service_helper import LookupServiceHelper
from samples.vsphere.common.sample_config import SampleConfig from samples.vsphere.common.sample_config import SampleConfig
from samples.vsphere.common.logging_context import LoggingContext
logger = LoggingContext.get_logger('samples.vsphere.workflow.vapi_connection_workflow')
class VapiConnectionWorkflow(object): class VapiConnectionWorkflow(object):
@ -76,14 +73,14 @@ class VapiConnectionWorkflow(object):
else: else:
self.lswsdlurl = self.args.lswsdlurl self.lswsdlurl = self.args.lswsdlurl
assert self.lswsdlurl is not None assert self.lswsdlurl is not None
logger.info('lswsdlurl: {0}'.format(self.lswsdlurl)) print('lswsdlurl: {0}'.format(self.lswsdlurl))
if self.args.lssoapurl is None: if self.args.lssoapurl is None:
self.lssoapurl = SampleConfig.get_ls_soap_url() # look for lookup service SOAP URL in the sample config self.lssoapurl = SampleConfig.get_ls_soap_url() # look for lookup service SOAP URL in the sample config
else: else:
self.lssoapurl = self.args.lssoapurl self.lssoapurl = self.args.lssoapurl
assert self.lssoapurl is not None assert self.lssoapurl is not None
logger.info('lssoapurl: {0}'.format(self.lssoapurl)) print('lssoapurl: {0}'.format(self.lssoapurl))
if self.args.username is None: if self.args.username is None:
self.username = SampleConfig.get_username() # look for sso user name in the sample config self.username = SampleConfig.get_username() # look for sso user name in the sample config
@ -103,7 +100,7 @@ class VapiConnectionWorkflow(object):
self.skip_verification = self.args.skipverification self.skip_verification = self.args.skipverification
def execute(self): def execute(self):
logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl)) print('Connecting to lookup service url: {0}'.format(self.lssoapurl))
lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl,
soap_url=self.lssoapurl, soap_url=self.lssoapurl,
skip_verification=self.skip_verification) skip_verification=self.skip_verification)
@ -116,9 +113,9 @@ class VapiConnectionWorkflow(object):
assert self.mgmtnodeid is not None assert self.mgmtnodeid is not None
self.vapiurl = lookupservicehelper.find_vapi_url(self.mgmtnodeid) self.vapiurl = lookupservicehelper.find_vapi_url(self.mgmtnodeid)
logger.info('vapi_url: {0}'.format(self.vapiurl)) print('vapi_url: {0}'.format(self.vapiurl))
logger.info('Connecting to VAPI endpoint and preparing stub configuration...') print('Connecting to VAPI endpoint and preparing stub configuration...')
session = requests.Session() session = requests.Session()
if self.skip_verification: if self.skip_verification:
session.verify = False session.verify = False
@ -130,27 +127,27 @@ class VapiConnectionWorkflow(object):
self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.stub_config = StubConfigurationFactory.new_std_configuration(connector)
self.session = Session(self.stub_config) self.session = Session(self.stub_config)
logger.info('Login to VAPI endpoint and get the session_id...') print('Login to VAPI endpoint and get the session_id...')
self.session_id = self.session.create() self.session_id = self.session.create()
logger.info('Update the VAPI connection with session_id...') print('Update the VAPI connection with session_id...')
session_sec_ctx = create_session_security_context(self.session_id) session_sec_ctx = create_session_security_context(self.session_id)
connector.set_security_context(session_sec_ctx) connector.set_security_context(session_sec_ctx)
# make sure you can access some of the VAPI services # make sure you can access some of the VAPI services
tag_svc = Tag(self.stub_config) tag_svc = Tag(self.stub_config)
logger.info('List all the existing tags user has access to...') print('List all the existing tags user has access to...')
tags = tag_svc.list() tags = tag_svc.list()
if len(tags) > 0: if len(tags) > 0:
for tag in tags: for tag in tags:
logger.info('Found Tag: {0}'.format(tag)) print('Found Tag: {0}'.format(tag))
else: else:
logger.info('No Tag Found...') print('No Tag Found...')
def cleanup(self): def cleanup(self):
if self.session_id is not None: if self.session_id is not None:
self.disconnect() self.disconnect()
logger.info('VAPI session disconnected successfully...') print('VAPI session disconnected successfully...')
def disconnect(self): def disconnect(self):
self.session.delete() self.session.delete()