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

Merge pull request #9 from tianhao64/tianhao64-patch-1

Tianhao64 patch 1
This commit is contained in:
Tianhao He 2017-02-24 16:04:23 -08:00 committed by GitHub
commit 9a5d455c62
43 changed files with 246 additions and 155 deletions

10
.travis.yml Normal file
View File

@ -0,0 +1,10 @@
language: python
python:
- "2.7.13"
- "3.6"
# command to install dependencies
install:
- "pip install -r requirements.txt"
- "pip install pycodestyle"
# command to run tests
script: pycodestyle samples/*

View File

@ -2,7 +2,9 @@
# package as multiple distribution
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -36,6 +36,7 @@ def main():
print(generate_random_string(5))
print(rand('Simple VM-'))
# Start program
if __name__ == "__main__":
main()

View File

@ -16,6 +16,7 @@ __copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.'
import os
from suds.client import Client
class LookupServiceHelper(object):
def __init__(self, wsdl_url, soap_url, skip_verification):
self.wsdl_url = wsdl_url
@ -50,11 +51,13 @@ class LookupServiceHelper(object):
assert self.client is not None
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.value = 'ServiceInstance'
lookupServiceContent = self.client.service.RetrieveServiceContent(self.managedObjectReference)
lookupServiceContent = self.client.service.RetrieveServiceContent(
self.managedObjectReference)
self.serviceRegistration = lookupServiceContent.serviceRegistration
@ -184,20 +187,27 @@ class LookupServiceHelper(object):
assert self.client 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)
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration,
lookupServiceRegistrationFilter)
assert len(result) > 0
# Support for MxN
# return the results in a dictionary where key is NodeId and Value is Service URL
results_dict = {}
for lookupServiceRegistrationInfo in result:
lookupServiceRegistrationEndpoint = lookupServiceRegistrationInfo.serviceEndpoints[0]
lookupServiceRegistrationEndpoint = \
lookupServiceRegistrationInfo.serviceEndpoints[0]
assert lookupServiceRegistrationEndpoint is not None
results_dict[lookupServiceRegistrationInfo.nodeId] = lookupServiceRegistrationEndpoint.url
results_dict[
lookupServiceRegistrationInfo.nodeId] = lookupServiceRegistrationEndpoint.url
return results_dict
def __find_platform_service_urls(self, product, service, endpoint, protocol):
def __find_platform_service_urls(self, product, service, endpoint,
protocol):
"""
Finds the endpoint URLs of a service running on PSCs (Platform Service Controller).
Returns a list of service URLs since there is no node id associated with the PSC.
@ -205,14 +215,19 @@ class LookupServiceHelper(object):
assert self.client 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)
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration,
lookupServiceRegistrationFilter)
assert len(result) > 0
urls = []
for lookupServiceRegistrationInfo in result:
lookupServiceRegistrationEndpoint = lookupServiceRegistrationInfo.serviceEndpoints[0]
lookupServiceRegistrationEndpoint = \
lookupServiceRegistrationInfo.serviceEndpoints[0]
assert lookupServiceRegistrationEndpoint is not None
urls.append(lookupServiceRegistrationEndpoint.url)
return urls
@ -220,15 +235,18 @@ class LookupServiceHelper(object):
def __create_filter_spec(self, product, service, endpoint, protocol):
assert self.client is not None
lookupServiceRegistrationServiceType = self.client.factory.create('ns0:LookupServiceRegistrationServiceType')
lookupServiceRegistrationServiceType = self.client.factory.create(
'ns0:LookupServiceRegistrationServiceType')
lookupServiceRegistrationServiceType.product = product
lookupServiceRegistrationServiceType.type = service
lookupServiceRegistrationEndpointType = self.client.factory.create('ns0:LookupServiceRegistrationEndpointType')
lookupServiceRegistrationEndpointType = self.client.factory.create(
'ns0:LookupServiceRegistrationEndpointType')
lookupServiceRegistrationEndpointType.type = endpoint
lookupServiceRegistrationEndpointType.protocol = protocol
lookupServiceRegistrationFilter = self.client.factory.create('ns0:LookupServiceRegistrationFilter')
lookupServiceRegistrationFilter = self.client.factory.create(
'ns0:LookupServiceRegistrationFilter')
lookupServiceRegistrationFilter.serviceType = lookupServiceRegistrationServiceType
lookupServiceRegistrationFilter.endpointType = lookupServiceRegistrationEndpointType
return lookupServiceRegistrationFilter
@ -243,26 +261,31 @@ class LookupServiceHelper(object):
assert self.client is not None
assert self.serviceRegistration is not None
lookupServiceRegistrationServiceType = self.client.factory.create('ns0:LookupServiceRegistrationServiceType')
lookupServiceRegistrationServiceType = self.client.factory.create(
'ns0:LookupServiceRegistrationServiceType')
lookupServiceRegistrationServiceType.product = 'com.vmware.cis'
lookupServiceRegistrationServiceType.type = 'vcenterserver'
lookupServiceRegistrationEndpointType = self.client.factory.create('ns0:LookupServiceRegistrationEndpointType')
lookupServiceRegistrationEndpointType = self.client.factory.create(
'ns0:LookupServiceRegistrationEndpointType')
lookupServiceRegistrationEndpointType.type = 'com.vmware.vim'
lookupServiceRegistrationEndpointType.protocol = 'vmomi'
lookupServiceRegistrationFilter = self.client.factory.create('ns0:LookupServiceRegistrationFilter')
lookupServiceRegistrationFilter = self.client.factory.create(
'ns0:LookupServiceRegistrationFilter')
lookupServiceRegistrationFilter.serviceType = lookupServiceRegistrationServiceType
lookupServiceRegistrationFilter.endpointType = lookupServiceRegistrationEndpointType
result = self.client.service.List(self.serviceRegistration, lookupServiceRegistrationFilter)
result = self.client.service.List(self.serviceRegistration,
lookupServiceRegistrationFilter)
assert len(result) > 0
results_dict = {}
for lookupServiceRegistrationInfo in result:
for lookupServiceRegistrationAttribute in lookupServiceRegistrationInfo.serviceAttributes:
if lookupServiceRegistrationAttribute.key == 'com.vmware.vim.vcenter.instanceName':
results_dict[lookupServiceRegistrationAttribute.value] = lookupServiceRegistrationInfo.nodeId
results_dict[
lookupServiceRegistrationAttribute.value] = lookupServiceRegistrationInfo.nodeId
return results_dict
def get_mgmt_node_id(self, instance_name):
@ -295,8 +318,10 @@ class LookupServiceHelper(object):
if len(result) < 1:
raise Exception('No management node found')
if len(result) > 1:
raise MultipleManagementNodeException(MultipleManagementNodeException.format(result))
return list(result.keys())[0], list(result.values())[0] # python 3.x dict.keys() returns a view rather than a list
raise MultipleManagementNodeException(
MultipleManagementNodeException.format(result))
return list(result.keys())[0], list(result.values())[
0] # python 3.x dict.keys() returns a view rather than a list
class MultipleManagementNodeException(Exception):
@ -315,12 +340,14 @@ class MultipleManagementNodeException(Exception):
"""
message = 'Multiple Management Node Found on server'
for k, v in nodes.items():
message = message + os.linesep + 'Node name: {0} uuid: {1}'.format(k, v)
message = message + os.linesep + 'Node name: {0} uuid: {1}'.format(
k, v)
return message
def main():
lookup_service_helper = LookupServiceHelper(wsdl_url='file:///path/to/lookupservice.wsdl',
lookup_service_helper = LookupServiceHelper(
wsdl_url='file:///path/to/lookupservice.wsdl',
soap_url='https://server_ip/lookupservice/sdk')
lookup_service_helper.connect()
print(lookup_service_helper.find_sso_url())
@ -329,6 +356,7 @@ def main():
print(lookup_service_helper.find_vim_pbm_urls())
print(lookup_service_helper.find_mgmt_nodes())
# Start program
if __name__ == "__main__":
main()

View File

@ -24,7 +24,9 @@ class PlatformServiceController(object):
"""
Manages services on the infrastructure node (e.g. lookup service, SSO etc.)
"""
def __init__(self, lswsdlurl, lssoapurl, ssousername, ssopassword, skip_verification):
def __init__(self, lswsdlurl, lssoapurl, ssousername, ssopassword,
skip_verification):
self.lswsdlurl = lswsdlurl
self.lssoapurl = lssoapurl
self.ssousername = ssousername
@ -48,11 +50,13 @@ class PlatformServiceController(object):
self.stsurl = self.lookupservicehelper.find_sso_url()
assert self.stsurl is not None
print('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)
context = None
if self.skip_verification:
context = get_unverified_context()
self.bearer_token = au.get_bearer_saml_assertion(
self.ssousername, self.ssopassword, delegatable=True, ssl_context=context)
self.ssousername, self.ssopassword, delegatable=True,
ssl_context=context)
self.sec_ctx = create_saml_bearer_security_context(self.bearer_token)

View File

@ -13,7 +13,6 @@
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2013, 2016 VMware, Inc. All rights reserved.'
import argparse
import traceback
from samples.vsphere.common.service_manager_factory import ServiceManagerFactory
@ -26,12 +25,16 @@ class SampleBase(object):
self.description = description
# setup the argument parser
self.argparser = argparse.ArgumentParser(description=description)
self.argparser.add_argument('-s', '--server', help='Hostname of vCenter Server')
self.argparser.add_argument('-u', '--username', help='Username to login to the vCenter Server')
self.argparser.add_argument('-p', '--password', help='Password to login to the vCenter Server')
self.argparser.add_argument('-s', '--server',
help='Hostname of vCenter Server')
self.argparser.add_argument('-u', '--username',
help='Username to login to the vCenter Server')
self.argparser.add_argument('-p', '--password',
help='Password to login to the vCenter Server')
self.argparser.add_argument('-c', '--cleardata', action='store_true',
help='Clears the sample data on server after running')
self.argparser.add_argument('-v', '--skipverification', action='store_true',
self.argparser.add_argument('-v', '--skipverification',
action='store_true',
help='Do not verify server certificate')
self.args = None
self.server = None

View File

@ -64,4 +64,3 @@ class ServiceManager(object):
print('disconnecting the session')
vapiconnect.logout(self.stub_config)
Disconnect(self.si)

View File

@ -36,5 +36,6 @@ class ServiceManagerFactory(object):
if cls.service_manager:
cls.service_manager.disconnect()
import atexit
atexit.register(ServiceManagerFactory.disconnect)

View File

@ -15,6 +15,7 @@ __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import ssl
def get_unverified_context():
"""
Get an unverified ssl context. Used to disable the server certificate

View File

@ -2,7 +2,9 @@
# package as multiple distribution
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -182,7 +182,7 @@ class File(object):
match_pattern = None
dirname = None
if path != None:
if path is not None:
# Determine the dirname and the basename making sure only the
# basename is passed in the match_pattern
paths = path.split('/')
@ -239,13 +239,13 @@ class File(object):
stub = self._datastore_mo._stub
cookie = self._make_cookie(stub)
f = None
if src_file != None:
if src_file is not None:
f = src_file
elif src_url != None:
elif src_url is not None:
f = requests.get(src_url, stream=True)
elif src_path != None:
elif src_path is not None:
f = open(src_file, 'wb')
elif content == None:
elif content is None:
raise Exception('No input provided for put')
if f:

View File

@ -2,7 +2,9 @@
# package as multiple distribution
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -23,6 +23,7 @@ class GetClusterByName(SampleBase):
"""
Retrieves the given cluster MOID from VC using container view
"""
def __init__(self):
SampleBase.__init__(self, self.__doc__)
self.cluster_name = None
@ -30,7 +31,8 @@ class GetClusterByName(SampleBase):
self.servicemanager = None
def _options(self):
self.argparser.add_argument('-clustername', '--clustername', help='Name of the cluster to be queried')
self.argparser.add_argument('-clustername', '--clustername',
help='Name of the cluster to be queried')
def _setup(self):
if self.cluster_name is None:
@ -41,7 +43,8 @@ class GetClusterByName(SampleBase):
def _execute(self):
content = self.servicemanager.content
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:
self.mo_id = cluster_obj._GetMoId()
print('Cluster MoId: {0}'.format(self.mo_id))

View File

@ -23,6 +23,7 @@ class GetDatastoreByName(SampleBase):
"""
Retrieves the given datastore MOID from VC using container view
"""
def __init__(self):
SampleBase.__init__(self, self.__doc__)
self.datastore_name = None
@ -30,7 +31,8 @@ class GetDatastoreByName(SampleBase):
self.servicemanager = None
def _options(self):
self.argparser.add_argument('-datastorename', '--datastorename', help='Name of the datastore to be queried')
self.argparser.add_argument('-datastorename', '--datastorename',
help='Name of the datastore to be queried')
def _setup(self):
if self.datastore_name is None:

View File

@ -15,7 +15,6 @@ __copyright__ = 'Copyright 2013 VMware, Inc. All rights reserved.'
from pyVmomi import vim, vmodl
_views = [] # list of container views
@ -24,7 +23,8 @@ def get_obj(content, vimtype, name):
Get the vsphere managed object associated with a given text name
"""
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
container = content.viewManager.CreateContainerView(content.rootFolder,
vimtype, True)
_views.append(container)
for c in container.view:
if c.name == name:
@ -38,7 +38,8 @@ def get_obj_by_moId(content, vimtype, moid):
Get the vsphere managed object by moid value
"""
obj = None
container = content.viewManager.CreateContainerView(content.rootFolder, vimtype, True)
container = content.viewManager.CreateContainerView(content.rootFolder,
vimtype, True)
_views.append(container)
for c in container.view:
if c._GetMoId() == moid:
@ -55,8 +56,9 @@ def delete_object(content, mo):
try:
wait_for_tasks(content, [mo.Destroy()])
print('Deleted {0}'.format(mo._GetMoId()))
except:
print('Unexpected error while deleting managed object {0}'.format(mo._GetMoId()))
except Exception:
print('Unexpected error while deleting managed object {0}'.format(
mo._GetMoId()))
return False
return True
@ -72,7 +74,7 @@ def poweron_vm(content, mo):
try:
wait_for_tasks(content, [mo.PowerOn()])
print('{0} powered on successfully'.format(mo._GetMoId()))
except:
except Exception:
print('Unexpected error while powering on vm {0}'.format(mo._GetMoId()))
return False
return True
@ -89,8 +91,9 @@ def poweroff_vm(content, mo):
try:
wait_for_tasks(content, [mo.PowerOff()])
print('{0} powered off successfully'.format(mo._GetMoId()))
except:
print('Unexpected error while powering off vm {0}'.format(mo._GetMoId()))
except Exception:
print(
'Unexpected error while powering off vm {0}'.format(mo._GetMoId()))
return False
return True
@ -102,7 +105,8 @@ def wait_for_tasks(content, tasks):
taskList = [str(task) for task in tasks]
# Create filter
objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in tasks]
objSpecs = [vmodl.query.PropertyCollector.ObjectSpec(obj=task) for task in
tasks]
propSpec = vmodl.query.PropertyCollector.PropertySpec(type=vim.Task,
pathSet=[], all=True)
filterSpec = vmodl.query.PropertyCollector.FilterSpec()
@ -149,5 +153,7 @@ def __destroy_container_views():
except vmodl.fault.ManagedObjectNotFound:
pass # silently bypass the exception if the objects are already deleted/not found on the server
import atexit
atexit.register(__destroy_container_views)

View File

@ -35,7 +35,7 @@ def get_datastore_mo(stub_config, soap_stub,
# property collector query but it's a little more complicated
def get_datacenter_for_datastore(datastore_mo):
datacenter_mo = datastore_mo.parent
while datacenter_mo != None:
while datacenter_mo is not None:
if isinstance(datacenter_mo, vim.Datacenter):
return datacenter_mo
datacenter_mo = datacenter_mo.parent

View File

@ -33,12 +33,14 @@ def create_vmdk(service_instance, datacenter_mo, datastore_path):
format(datastore_path, datacenter_mo.name))
return task.info.result
def delete_vmdk(service_instance, datacenter_mo, datastore_path):
"""Delete vmdk from specific datastore"""
vdm = service_instance.content.virtualDiskManager
task = vdm.DeleteVirtualDisk(datastore_path, datacenter_mo)
pyVim.task.WaitForTask(task)
def detect_vmdk(stub_config, soap_stub, datacenter_name, datastore_name,
datastore_path):
"""Find vmdk in specific datastore"""

View File

@ -110,4 +110,3 @@ def main():
if __name__ == '__main__':
main()

View File

@ -22,6 +22,7 @@ from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.vm_helper import get_vm
class IsoMount(SampleBase):
"""
Demonstrates the content library ISO item mount and
@ -64,12 +65,16 @@ class IsoMount(SampleBase):
self.helper = ClsApiHelper(self.client, self.skip_verification)
def _execute(self):
storage_backings = self.helper.create_storage_backings(self.servicemanager, self.datastore_name)
storage_backings = self.helper.create_storage_backings(
self.servicemanager, self.datastore_name)
library_id = self.helper.create_local_library(storage_backings, self.lib_name)
library_id = self.helper.create_local_library(storage_backings,
self.lib_name)
self.local_library = self.client.local_library_service.get(library_id)
library_item_id = self.helper.create_iso_library_item(library_id,self.iso_item_name, self.ISO_FILENAME)
library_item_id = self.helper.create_iso_library_item(library_id,
self.iso_item_name,
self.ISO_FILENAME)
vm_id = get_vm(self.servicemanager.stub_config, self.vm_name)
assert vm_id is not None
@ -77,18 +82,17 @@ class IsoMount(SampleBase):
# Mount the iso item as a CDROM device
device_id = self.client.iso_service.mount(library_item_id, vm_id)
assert device_id is not None
print('Mounted library item {0}'
' on vm {1} at device {2}'.format(self.iso_item_name, self.vm_name, device_id))
print('Mounted library item {0} on vm {1} at device {2}'.
format(self.iso_item_name, self.vm_name, device_id))
# Unmount the CDROM
self.client.iso_service.unmount(vm_id, device_id)
print('Unmounted library item {0}'
'from vm {1} mounted at device {2}'.format(self.iso_item_name,
self.vm_name, device_id))
print('Unmounted library item {0} from vm {1} mounted at device {2}'.
format(self.iso_item_name, self.vm_name, device_id))
def _cleanup(self):
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)
print('Deleted Library Id: {0}'.format(self.local_library.id))

View File

@ -10,16 +10,16 @@
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
# Required to distribute different parts of this
# package as multiple distribution
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -126,8 +126,7 @@ class ClsApiHelper(object):
def get_iso_file_map(self, item_filename, disk_filename):
iso_files_map = {}
iso_file_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),
self.ISO_FILE_RELATIVE_DIR
+ disk_filename))
self.ISO_FILE_RELATIVE_DIR + disk_filename))
iso_files_map[item_filename] = iso_file_path
return iso_files_map

View File

@ -16,6 +16,7 @@ __vcenter_version__ = '6.0+'
import time
class ClsSyncHelper:
"""
Helper class to wait for the subscribed libraries and items to be
@ -54,7 +55,8 @@ class ClsSyncHelper:
"""
self.start_time = time.time()
is_synced = False
pub_item_id = self.client.library_item_service.get(sub_item_id).source_id
pub_item_id = self.client.library_item_service.get(
sub_item_id).source_id
pub_item = self.client.library_item_service.get(pub_item_id)
while self.not_timed_out():
@ -94,9 +96,10 @@ class ClsSyncHelper:
while self.not_timed_out():
# Get the subscribed library's updated information from server.
refreshed_sub_lib = self.client.subscribed_library_service.get(sub_lib.id)
if refreshed_sub_lib.last_sync_time != None:
if (sub_lib.last_sync_time == None or
refreshed_sub_lib = self.client.subscribed_library_service.get(
sub_lib.id)
if refreshed_sub_lib.last_sync_time is not None:
if (sub_lib.last_sync_time is None or
refreshed_sub_lib.last_sync_time > sub_lib.last_sync_time):
is_synced = True
break
@ -113,7 +116,8 @@ class ClsSyncHelper:
return False
synced_item_ids = []
for sub_item_id in sub_item_ids:
source_id = self.client.library_item_service.get(sub_item_id).source_id
source_id = self.client.library_item_service.get(
sub_item_id).source_id
if source_id not in synced_item_ids and source_id in pub_item_ids:
synced_item_ids.append(sub_item_id)

View File

@ -33,7 +33,6 @@ from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
class DeployOvfTemplate(SampleBase):
"""
Demonstrates the workflow to deploy an OVF library item to a resource pool.
@ -71,7 +70,7 @@ class DeployOvfTemplate(SampleBase):
self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification)
# Default VM name
self.vm_name = 'vm-'+str(generate_random_uuid())
self.vm_name = 'vm-' + str(generate_random_uuid())
def _execute(self):

View File

@ -56,6 +56,7 @@ class LibraryPublishSubscribe(SampleBase):
self.argparser.add_argument('-datastorename',
'--datastorename',
help='The name of the datastore.')
def _setup(self):
self.datastore_name = self.args.datastorename
assert self.datastore_name is not None
@ -65,7 +66,8 @@ class LibraryPublishSubscribe(SampleBase):
self.helper = ClsApiHelper(self.client, self.skip_verification)
def _execute(self):
storage_backings = self.helper.create_storage_backings(self.servicemanager,
storage_backings = self.helper.create_storage_backings(
self.servicemanager,
self.datastore_name)
# Create a published library backed the VC datastore using vAPIs
@ -78,7 +80,9 @@ class LibraryPublishSubscribe(SampleBase):
print('Publish URL : {0}'.format(pub_lib_url))
# 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)
assert self.client.library_item_service.get(pub_lib_item_id) is not None
# Create the subscribed library
@ -97,7 +101,8 @@ class LibraryPublishSubscribe(SampleBase):
assert len(sub_item_ids) == 1, 'Subscribed library must have one item'
# Add another item to the published library
self.helper.create_iso_library_item(self.pub_lib_id, 'item_2', self.DEMO_FILENAME)
self.helper.create_iso_library_item(self.pub_lib_id, 'item_2',
self.DEMO_FILENAME)
# Manually synchronize the subscribed library to get the latest changes immediately.
self.client.subscribed_library_service.sync(self.sub_lib_id)
@ -110,7 +115,7 @@ class LibraryPublishSubscribe(SampleBase):
# List the subscribed items.
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'
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)
print('Subscribed item : {0}'.format(sub_item.name))

View File

@ -29,7 +29,6 @@ from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
from samples.vsphere.vcenter.helper.vm_helper import get_vm
class CaptureVMTemplateToContentLibrary(SampleBase):
"""
Demonstrates the workflow to capture a virtual machine into a content library.
@ -72,7 +71,8 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
self.helper = ClsApiHelper(self.client, self.skip_verification)
def _execute(self):
storage_backings = self.helper.create_storage_backings(self.servicemanager,
storage_backings = self.helper.create_storage_backings(
self.servicemanager,
self.datastore_name)
print('Creating Content Library')
@ -94,7 +94,8 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
(vm_id, self.library_item_id))
def capture_source_vm(self, vm_id, param):
source = LibraryItem.DeployableIdentity(self.deployable_resource_type, vm_id)
source = LibraryItem.DeployableIdentity(self.deployable_resource_type,
vm_id)
result = self.client.ovf_lib_item_service.create(source,
param["target"],
param["spec"],
@ -111,7 +112,8 @@ class CaptureVMTemplateToContentLibrary(SampleBase):
def _cleanup(self):
# delete the local library.
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)
print('Deleted Library Id: {0}'.format
(self.content_library.id))
@ -120,6 +122,7 @@ def main():
vm_template_capture = CaptureVMTemplateToContentLibrary()
vm_template_capture.main()
# Start program
if __name__ == '__main__':
main()

View File

@ -17,7 +17,9 @@ __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
# package as multiple distribution
try:
import pkg_resources
pkg_resources.declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) # @ReservedAssignment

View File

@ -205,6 +205,7 @@ def main():
tagging_workflow = TaggingWorkflow()
tagging_workflow.main()
# Start program
if __name__ == '__main__':
main()

View File

@ -13,7 +13,6 @@
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
from com.vmware.vcenter_client import (Datacenter, Folder)
@ -64,7 +63,7 @@ def cleanup_datacenters(context):
datacenter_summaries = datacenter_svc.list(
Datacenter.FilterSpec(names=names))
print("Found {} Datacenters matching names {}".
format(len(datacenter_summaries),", ".
format(len(datacenter_summaries), ", ".
join(["'{}'".format(n) for n in names])))
for datacenter_summary in datacenter_summaries:

View File

@ -13,7 +13,6 @@
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task
from com.vmware.vcenter_client import Host
from pyVmomi import vim
@ -39,12 +38,12 @@ def detect_nfs_datastore_on_host(context, host_name):
datastore = datastore_mo._moId
print("Detected NFS Volume '{}' as {} on Host '{}' ({})".
format(datastore_name, datastore, host_name, host))
context.testbed.entities['HOST_NFS_DATASTORE_IDS'][host_name]\
context.testbed.entities['HOST_NFS_DATASTORE_IDS'][host_name] \
= datastore
return True
print("NFS Volume '{}' missing on Host '{}'".
format(datastore_name,host_name))
format(datastore_name, host_name))
return False
@ -81,7 +80,7 @@ def cleanup_nfs_datastore(context):
datastore_system.RemoveDatastore(datastore_mo)
print("Removed NFS Volume '{}' ({}) from Host '{}' ({})".
format(datastore_name, datastore_mo._moId,
host_mo.name,host_mo._moId))
host_mo.name, host_mo._moId))
# Remote NFS Datastore at the vCenter level
# TODO Do we need to do this?
@ -133,7 +132,7 @@ def setup_nfs_datastore_on_host(context, host_name):
if info.name == local_path:
print("Found NFS Volume '{}' ({}) on Host '{}' ({})".
format(local_path, datastore_mo._moId,
host_name,host_mo._moId))
host_name, host_mo._moId))
return datastore_mo._moId
else:
print("Found NFS remote host '{}' and path '{}' on Host '{}' ({}) as '{}'".
@ -168,7 +167,7 @@ def detect_vmfs_datastore(context, host_name, datastore_name):
datastore = datastore_mo._moId
print("Detected VMFS Volume '{}' as {} on Host '{}' ({})".
format(datastore_name, datastore, host_name, host))
context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name]\
context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name] \
= datastore
return True
@ -216,7 +215,7 @@ def setup_vmfs_datastore(context, host_name, datastore_name):
datastore = vmfs_datastores[datastore_name]._moId
print("Detected VMFS Volume '{}' as {} on Host '{}' ({})".
format(datastore_name, datastore, host_name, host))
context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name]\
context.testbed.entities['HOST_VMFS_DATASTORE_IDS'][host_name] \
= datastore
return True

View File

@ -109,4 +109,3 @@ if context.option['DO_SAMPLES_CLEANUP']:
if context.option['DO_TESTBED_CLEANUP']:
sample_cleanup(context)
testbed_cleanup(context)

View File

@ -13,7 +13,6 @@
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
import pyVim.task
from com.vmware.vcenter_client import Host
from pyVmomi import vim
@ -80,7 +79,7 @@ def cleanup_vdswitch(context):
def find_vdswitch(context, datacenter_name, vdswitch_name):
""" Retrieve an existing Distributed Switch"""
# TODO Ugly deep nesting.
for datacenter_mo in context.service_instance.content.rootFolder\
for datacenter_mo in context.service_instance.content.rootFolder \
.childEntity:
if (isinstance(datacenter_mo, vim.Datacenter) and
datacenter_mo.name == datacenter_name):
@ -102,9 +101,10 @@ def find_vdportgroup(context, datacenter_name, vdswitch_name, vdportgroup_name):
vdswitch_mo = find_vdswitch(context, datacenter_name, vdswitch_name)
for vdportgroup_mo in vdswitch_mo.portgroup:
if vdportgroup_mo.name == vdportgroup_name:
print("Found Distributed Portgroup '{}' ({}) on Distributed Switch '{}' ({})".
print(
"Found Distributed Portgroup '{}' ({}) on Distributed Switch '{}' ({})".
format(vdportgroup_name, vdportgroup_mo._moId,
vdswitch_name,vdswitch_mo._moId))
vdswitch_name, vdswitch_mo._moId))
return vdportgroup_mo
return None
@ -146,7 +146,8 @@ def create_vdportgroup(context, vdswitch_name, vdportgroup_name):
for vdportgroup_mo in vdswitch_mo.portgroup:
if vdportgroup_mo.name == vdportgroup_name:
vdportgroup = vdportgroup_mo._moId
print("Created Distributed Portgroup '{}' ({}) on Distributed Switch '{}' ({})".
print(
"Created Distributed Portgroup '{}' ({}) on Distributed Switch '{}' ({})".
format(vdportgroup_name, vdportgroup, vdswitch_name, vdswitch))
return vdportgroup
@ -245,7 +246,8 @@ def detect_stdportgroup(context, host_name, network_name):
if (type(network_mo) == vim.Network and
network_mo.name == network_name):
network = network_mo._moId
print("Detected Standard Portgroup '{}' as {} on Host '{}' ({})".
print(
"Detected Standard Portgroup '{}' as {} on Host '{}' ({})".
format(network_name, network, host_name, host))
context.testbed.entities['HOST_STANDARD_SWITCH_IDS'][
host_name] = network

View File

@ -85,6 +85,7 @@ config["FLOPPY_DATACENTER_NAME"] = config["VM_DATACENTER_NAME"]
config["FLOPPY_DATASTORE_ROOT_PATH"] = config["BACKENDS_DATASTORE_ROOT_PATH"] + "/floppy"
config["FLOPPY_DATASTORE_PATH"] = config["FLOPPY_DATASTORE_ROOT_PATH"] + "/fdboot.img"
class Testbed(object):
def __init__(self):
self.config = {}
@ -134,5 +135,6 @@ class Testbed(object):
_testbed = Testbed()
_testbed.config.update(config)
def get():
return _testbed

View File

@ -41,6 +41,7 @@ cleardata = False
satas_to_delete = []
orig_sata_summaries = None
def setup(context=None):
global vm, vm_name, stub_config, cleardata
if context:
@ -57,6 +58,7 @@ def setup(context=None):
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
global vm
vm = get_vm(stub_config, vm_name)

View File

@ -41,6 +41,7 @@ cleardata = False
scsis_to_delete = []
orig_scsi_summaries = None
def setup(context=None):
global vm, vm_name, stub_config, cleardata
if context:
@ -58,6 +59,7 @@ def setup(context=None):
atexit.register(vapiconnect.logout, stub_config)
def run():
global vm
vm = get_vm(stub_config, vm_name)
@ -136,6 +138,7 @@ def cleanup():
print('vm.hardware.adapter.Scsi WARNING: '
'Final SCSI adapters info does not match original')
def main():
setup()
run()

View File

@ -41,6 +41,7 @@ stub_config = None
cleardata = False
orig_floppy_summaries = None
def setup(context=None):
global vm, vm_name, stub_config, cleardata
if context:
@ -57,6 +58,7 @@ def setup(context=None):
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
# * Floppy images must be pre-existing. This API does not expose
# a way to create new floppy images.
@ -117,7 +119,7 @@ def run():
print('\n# Example: Create Floppy with IMAGE_FILE backing, '
'start_connected=True,')
print( ' allow_guest_control=True')
print(' allow_guest_control=True')
floppy_create_spec = Floppy.CreateSpec(
allow_guest_control=True,
start_connected=True,

View File

@ -58,6 +58,7 @@ def setup(context=None):
atexit.register(vapiconnect.logout, stub_config)
def run():
global vm
vm = get_vm(stub_config, vm_name)
@ -120,5 +121,6 @@ def main():
if cleardata:
cleanup()
if __name__ == '__main__':
main()

View File

@ -55,7 +55,6 @@ def validate(context):
def run(context):
# Clean up in case of past failures
cleanup(context)
@ -80,14 +79,14 @@ def run(context):
# 1. STANDARD_PORTGROUP on DATACENTER2
# 2. DISTRIBUTED_PORTGROUP on DATACENTER2
###########################################################################
standard_network = samples.vsphere.vcenter.helper\
standard_network = samples.vsphere.vcenter.helper \
.network_helper.get_standard_network_backing(
context.stub_config,
context.testbed.config['STDPORTGROUP_NAME'],
context.testbed.config['VM_DATACENTER_NAME'])
print('standard_network={}'.format(standard_network))
distributed_network = samples.vsphere.vcenter.helper\
distributed_network = samples.vsphere.vcenter.helper \
.network_helper.get_distributed_network_backing(
context.stub_config,
context.testbed.config['VDPORTGROUP1_NAME'],
@ -137,7 +136,6 @@ def run(context):
if context.option['DO_SAMPLES_CLEANUP']:
samples.vsphere.vcenter.vm.hardware.main.cleanup()
# Sample cleanup
if context.option['DO_SAMPLES_CLEANUP']:
cleanup(context)

View File

@ -17,10 +17,9 @@ __vcenter_version__ = '6.5+'
from com.vmware.vcenter_client import (Cluster, Datastore, Folder, ResourcePool,
VM)
from samples.vsphere.vcenter.helper import vm_placement_helper
#####################################################################
# Placement samples: How to get a valid PlacementSpec to create a VM
#####################################################################

2
setup.cfg Normal file
View File

@ -0,0 +1,2 @@
[pycodestyle]
ignore = E402, E501, E122, E126, E127, E128, E129, E131