1
0
mirror of https://github.com/vmware/vsphere-automation-sdk-python.git synced 2024-11-22 09:39:58 -05:00

Improve sample code

1. Make sample code more consistent
2. Improve input parameter parser

Signed-off-by: Tianhao He <tianhao64@users.noreply.github.com>
This commit is contained in:
Tianhao He 2017-08-17 23:09:38 -07:00
parent 47e6c610c4
commit abe05ece27
13 changed files with 731 additions and 695 deletions

View File

@ -19,11 +19,12 @@ __vcenter_version__ = 'TODO: <compatible vcenter versions>'
import atexit import atexit
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
from samples.vsphere.common.sample_util import parse_cli_args from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.service_manager import ServiceManager from samples.vsphere.common.service_manager import ServiceManager
class Sample: class Sample(object):
""" """
TODO: Sample description and prerequisites. TODO: Sample description and prerequisites.
e.g. Demonstrates getting list of VMs present in vCenter e.g. Demonstrates getting list of VMs present in vCenter
@ -33,40 +34,44 @@ class Sample:
""" """
def __init__(self): def __init__(self):
self.vm_service = None # Service used by the sample code. self.service_manager = None
self.stub_config = None self.vm_name = None
self.si = None
self.cleardata = None self.cleardata = None
def setup(self): def setup(self):
server, username, password, cleardata, skip_verification = \ # Create argument parser for standard inputs:
parse_cli_args() # server, username, password, cleanup and skipverification
self.cleardata = cleardata parser = sample_cli.build_arg_parser()
# Add your custom input arguments
parser.add_argument('-n', '--vm_name',
action='store',
default='Sample_Default_VM_for_Simple_Testbed',
help='Name of the testing vm')
args = sample_util.process_cli_args(parser.parse_args())
self.vm_name = args.vm_name
self.cleardata = args.cleardata
# Connect to both Vim and vAPI services # Connect to both Vim and vAPI services
service_manager = ServiceManager(server, self.service_manager = ServiceManager(args.server,
username, args.username,
password, args.password,
skip_verification) args.skipverification)
service_manager.connect() self.service_manager.connect()
atexit.register(service_manager.disconnect) atexit.register(self.service_manager.disconnect)
# Get the vAPI stub
self.stub_config = service_manager.stub_config
self.vm_service = VM(self.stub_config)
# Get VIM service instance (pyVmomi)
self.si = service_manager.si
def run(self): def run(self):
# TODO add steps to demo your API # TODO add your sample code here
# Using vAPI services # Using REST API service
vms = self.vm_service.list() vm_service = VM(self.service_manager.stub_config)
filter_spec = VM.FilterSpec(names=set([self.vm_name]))
vms = vm_service.list(filter_spec)
print(vms) print(vms)
# Using vim services # Using Vim API service (pyVmomi)
current_time = self.si.CurrentTime() current_time = self.service_manager.si.CurrentTime()
print(current_time) print(current_time)
def cleanup(self): def cleanup(self):

View File

@ -25,7 +25,7 @@ def build_arg_parser():
-u username -u username
-p password -p password
-c cleanup -c cleanup
-v skip_verification -v skipverification
""" """
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
@ -43,7 +43,7 @@ def build_arg_parser():
action='store', action='store',
help='Password to use when connecting to vc') help='Password to use when connecting to vc')
parser.add_argument('-c', '--cleanup', parser.add_argument('-c', '--cleardata',
action='store_true', action='store_true',
help='Clean up after sample run. ') help='Clean up after sample run. ')

View File

@ -28,18 +28,6 @@ def pp(value):
return output.getvalue() return output.getvalue()
def parse_cli_args():
"""
Parse the server IP and credential used by samples.
Use values from command line arguments if present, otherwise use values
from testbed.py
"""
# parse command line
parser = sample_cli.build_arg_parser()
args = parser.parse_args()
return process_cli_args(args)
def parse_cli_args_vm(vm_name): def parse_cli_args_vm(vm_name):
""" """
Parse the server IP, credential and vm name used by vcenter vm samples. Parse the server IP, credential and vm name used by vcenter vm samples.
@ -51,10 +39,7 @@ def parse_cli_args_vm(vm_name):
parser.add_argument('-n', '--vm_name', parser.add_argument('-n', '--vm_name',
action='store', action='store',
help='Name of the testing vm') help='Name of the testing vm')
args = parser.parse_args() args = process_cli_args(parser.parse_args())
server, username, password, cleardata, skip_verification = \
process_cli_args(args)
if args.vm_name: if args.vm_name:
vm_name = args.vm_name vm_name = args.vm_name
@ -64,45 +49,37 @@ def parse_cli_args_vm(vm_name):
raise Exception("vm name is required") raise Exception("vm name is required")
print("vm name = {}".format(vm_name)) print("vm name = {}".format(vm_name))
return server, username, password, cleardata, skip_verification, vm_name return args.server, args.username, args.password, args.cleardata, \
args.skipverification, vm_name
def process_cli_args(args): def process_cli_args(args):
""" """
Process server IP and credential args. Verify if required inputs (server, username and password) are provided.
If they are not passed through cmd arguments, we will try to get them from
testbed.py. If they are not configured in testbed.py either, we will raise
an exception to remind the user to provide them.
""" """
if args.server: if not args.server:
server = args.server
else:
print("Using vcenter server specified in testbed.py") print("Using vcenter server specified in testbed.py")
server = testbed.config['SERVER'] args.server = testbed.config['SERVER']
if not server: if not args.server:
raise Exception("vcenter server is required") raise Exception("vcenter server is required")
print("vcenter server = {}".format(server)) print("vcenter server = {}".format(args.server))
if args.username: if not args.username:
username = args.username
else:
print("Using vc user specified in testbed.py") print("Using vc user specified in testbed.py")
username = testbed.config['USERNAME'] args.username = testbed.config['USERNAME']
if not username: if not args.username:
raise Exception("vc username is required") raise Exception("vc username is required")
print("vc username = {}".format(username)) print("vc username = {}".format(args.username))
if args.password: if not args.password:
password = args.password
else:
print("Using vc password specified in testbed.py") print("Using vc password specified in testbed.py")
password = testbed.config['PASSWORD'] args.password = testbed.config['PASSWORD']
cleardata = args.cleanup return args
print("sample cleanup = {}".format(cleardata))
skip_verification = args.skipverification
print("skip server cert verification = {}".format(skip_verification))
return server, username, password, cleardata, skip_verification
class Context(object): class Context(object):

View File

@ -22,19 +22,23 @@ try:
except ImportError: except ImportError:
import urllib.request as urllib2 import urllib.request as urllib2
import atexit
from com.vmware.content.library_client import Item from com.vmware.content.library_client import Item
from com.vmware.vcenter.ovf_client import LibraryItem from com.vmware.vcenter.ovf_client import LibraryItem
from pyVmomi import vim from pyVmomi import vim
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.id_generator import generate_random_uuid from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.common.vim.helpers.vim_utils import ( from samples.vsphere.common.vim.helpers.vim_utils import (
get_obj, get_obj_by_moId, poweron_vm, poweroff_vm, delete_object) get_obj, get_obj_by_moId, poweron_vm, poweroff_vm, delete_object)
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
class DeployOvfTemplate(SampleBase): class DeployOvfTemplate:
""" """
Demonstrates the workflow to deploy an OVF library item to a resource pool. Demonstrates the workflow to deploy an OVF library item to a resource pool.
Note: the sample needs an existing library item with an OVF template Note: the sample needs an existing library item with an OVF template
@ -42,7 +46,6 @@ class DeployOvfTemplate(SampleBase):
""" """
def __init__(self): def __init__(self):
SampleBase.__init__(self, self.__doc__)
self.servicemanager = None self.servicemanager = None
self.client = None self.client = None
self.helper = None self.helper = None
@ -51,29 +54,37 @@ class DeployOvfTemplate(SampleBase):
self.vm_obj = None self.vm_obj = None
self.vm_name = None self.vm_name = None
def _options(self): def setup(self):
self.argparser.add_argument('-clustername', parser = sample_cli.build_arg_parser()
'--clustername', parser.add_argument('-n', '--vm_name',
help='The name of the cluster to be used.') action='store',
self.argparser.add_argument('-libitemname', help='Name of the testing vm')
'--libitemname', parser.add_argument('-clustername',
help='The name of the library item to deploy.' '--clustername',
'The library item should contain an OVF package.') help='The name of the cluster to be used.')
parser.add_argument('-libitemname',
'--libitemname',
help='The name of the library item to deploy.'
'The library item should contain an OVF package.')
args = sample_util.process_cli_args(parser.parse_args())
self.lib_item_name = args.libitemname
self.cluster_name = args.clustername
self.vm_name = args.vm_name
def _setup(self): self.servicemanager = ServiceManager(args.server,
self.cluster_name = self.args.clustername args.username,
assert self.cluster_name is not None args.password,
args.skipverification)
self.servicemanager.connect()
atexit.register(self.servicemanager.disconnect)
self.lib_item_name = self.args.libitemname
assert self.lib_item_name is not None
self.servicemanager = self.get_service_manager()
self.client = ClsApiClient(self.servicemanager) self.client = ClsApiClient(self.servicemanager)
self.helper = ClsApiHelper(self.client, self.skip_verification) self.helper = ClsApiHelper(self.client, args.skipverification)
# Default VM name # Default VM name
self.vm_name = 'vm-' + str(generate_random_uuid()) self.vm_name = 'vm-' + str(generate_random_uuid())
def _execute(self): def execute(self):
# Find the cluster's resource pool moid # Find the cluster's resource pool moid
cluster_obj = get_obj(self.servicemanager.content, cluster_obj = get_obj(self.servicemanager.content,
@ -141,7 +152,7 @@ class DeployOvfTemplate(SampleBase):
for error in result.error.errors: for error in result.error.errors:
print('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:
# Power off the VM and wait for the power off operation to complete # Power off the VM and wait for the power off operation to complete
poweroff_vm(self.servicemanager.content, self.vm_obj) poweroff_vm(self.servicemanager.content, self.vm_obj)
@ -151,7 +162,9 @@ class DeployOvfTemplate(SampleBase):
def main(): def main():
deploy_ovf_sample = DeployOvfTemplate() deploy_ovf_sample = DeployOvfTemplate()
deploy_ovf_sample.main() deploy_ovf_sample.setup()
deploy_ovf_sample.execute()
deploy_ovf_sample.cleanup()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -17,20 +17,19 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+' __vcenter_version__ = '6.0+'
from pprint import pprint
import requests import requests
from com.vmware.cis.tagging_client import (Category, CategoryModel)
from com.vmware.cis_client import Session from com.vmware.cis_client import Session
from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.lib.connect import get_requests_connector
from vmware.vapi.security.session import create_session_security_context from vmware.vapi.security.session import create_session_security_context
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.stdlib.client.factories import StubConfigurationFactory from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
from com.vmware.cis.tagging_client import (Category, CategoryModel)
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common import sso
from samples.vsphere.common.ssl_helper import get_unverified_context from samples.vsphere.common.ssl_helper import get_unverified_context
from samples.vsphere.common.vapiconnect import create_unverified_session from samples.vsphere.common.vapiconnect import create_unverified_session
from samples.vsphere.common.sample_util import parse_cli_args
from samples.vsphere.common import sso
class EmbeddedPscSsoWorkflow(object): class EmbeddedPscSsoWorkflow(object):
@ -40,18 +39,15 @@ class EmbeddedPscSsoWorkflow(object):
""" """
def __init__(self): def __init__(self):
self.server = None self.args = None
self.username = None
self.password = None
self.session = None self.session = None
self.session_id = None self.session_id = None
self.skip_verification = False
self.category_svc = None self.category_svc = None
self.category_id = None self.category_id = None
def setup(self): def setup(self):
self.server, self.username, self.password, _, self.skip_verification = \ parser = sample_cli.build_arg_parser()
parse_cli_args() self.args = sample_util.process_cli_args(parser.parse_args())
def run(self): def run(self):
print('\n\n#### Example: Login to vCenter server with ' print('\n\n#### Example: Login to vCenter server with '
@ -59,18 +55,18 @@ class EmbeddedPscSsoWorkflow(object):
# Since the platform services controller is embedded, the sso server # Since the platform services controller is embedded, the sso server
# is the same as the vCenter server. # is the same as the vCenter server.
ssoUrl = 'https://{}/sts/STSService'.format(self.server) ssoUrl = 'https://{}/sts/STSService'.format(self.args.server)
print('\nStep 1: Connect to the Single Sign-On URL and ' print('\nStep 1: Connect to the Single Sign-On URL and '
'retrieve the SAML bearer token.') 'retrieve the SAML bearer token.')
authenticator = sso.SsoAuthenticator(ssoUrl) authenticator = sso.SsoAuthenticator(ssoUrl)
context = None context = None
if self.skip_verification: if self.args.skipverification:
context = get_unverified_context() context = get_unverified_context()
bearer_token = authenticator.get_bearer_saml_assertion( bearer_token = authenticator.get_bearer_saml_assertion(
self.username, self.args.username,
self.password, self.args.password,
delegatable=True, delegatable=True,
ssl_context=context) ssl_context=context)
@ -81,12 +77,12 @@ class EmbeddedPscSsoWorkflow(object):
# The URL for the stub requests are made against the /api HTTP endpoint # The URL for the stub requests are made against the /api HTTP endpoint
# of the vCenter system. # of the vCenter system.
vapi_url = 'https://{}/api'.format(self.server) vapi_url = 'https://{}/api'.format(self.args.server)
# Create an authenticated stub configuration object that can be used to # Create an authenticated stub configuration object that can be used to
# issue requests against vCenter. # issue requests against vCenter.
session = requests.Session() session = requests.Session()
if self.skip_verification: if self.args.skipverification:
session = create_unverified_session(session) session = create_unverified_session(session)
connector = get_requests_connector(session=session, url=vapi_url) connector = get_requests_connector(session=session, url=vapi_url)
connector.set_security_context(sec_ctx) connector.set_security_context(sec_ctx)

View File

@ -30,8 +30,7 @@ from samples.vsphere.vcenter.setup.setup_cli import build_arg_parser
from samples.vsphere.vcenter.setup.testbed_setup import cleanup as testbed_cleanup from samples.vsphere.vcenter.setup.testbed_setup import cleanup as testbed_cleanup
from samples.vsphere.vcenter.setup.testbed_setup import setup as testbed_setup from samples.vsphere.vcenter.setup.testbed_setup import setup as testbed_setup
from samples.vsphere.vcenter.setup.testbed_setup import validate as testbed_validate from samples.vsphere.vcenter.setup.testbed_setup import validate as testbed_validate
from samples.vsphere.vcenter.vm.main import cleanup as sample_cleanup from samples.vsphere.vcenter.vm.main import VMSetup
from samples.vsphere.vcenter.vm.main import run as sample_run
from samples.vsphere.common.ssl_helper import get_unverified_context from samples.vsphere.common.ssl_helper import get_unverified_context
@ -91,10 +90,12 @@ print(context.to_option_string())
# Testbed Setup # Testbed Setup
############################################################################### ###############################################################################
vm_setup = VMSetup(context)
# Setup testbed # Setup testbed
if context.option['DO_TESTBED_SETUP']: if context.option['DO_TESTBED_SETUP']:
# Clean up in case of past failures # Clean up in case of past failures
sample_cleanup(context) vm_setup.cleanup()
testbed_cleanup(context) testbed_cleanup(context)
testbed_setup(context) testbed_setup(context)
@ -113,11 +114,12 @@ if (context.option['DO_TESTBED_SETUP'] or
# Run Sample # Run Sample
if context.option['DO_SAMPLES']: if context.option['DO_SAMPLES']:
sample_run(context) vm_setup.setup(context)
vm_setup.run()
# Cleanup after sample run # Cleanup after sample run
if context.option['DO_SAMPLES_CLEANUP']: if context.option['DO_SAMPLES_CLEANUP']:
sample_cleanup(context) vm_setup.cleanup()
############################################################################### ###############################################################################
# Testbed Cleanup # Testbed Cleanup
@ -125,5 +127,5 @@ if context.option['DO_SAMPLES_CLEANUP']:
# Teardown testbed. # Teardown testbed.
if context.option['DO_TESTBED_CLEANUP']: if context.option['DO_TESTBED_CLEANUP']:
sample_cleanup(context) vm_setup.cleanup()
testbed_cleanup(context) testbed_cleanup(context)

View File

@ -15,9 +15,9 @@ __author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.' __copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
config = {} config = {}
config["SERVER"] = "" config["SERVER"] = "10.192.248.66"
config["USERNAME"] = "administrator@vsphere.local" config["USERNAME"] = "administrator@vsphere.local"
config["PASSWORD"] = "VMware1!" config["PASSWORD"] = "Admin!23"
config["ESX_HOST1"] = "" config["ESX_HOST1"] = ""
config["ESX_HOST2"] = "" config["ESX_HOST2"] = ""

View File

@ -25,143 +25,148 @@ from com.vmware.vcenter.vm.hardware_client import (
from com.vmware.vcenter.vm.hardware_client import ScsiAddressSpec from com.vmware.vcenter.vm.hardware_client import ScsiAddressSpec
from com.vmware.vcenter.vm_client import (Power) from com.vmware.vcenter.vm_client import (Power)
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.vcenter.helper import network_helper from samples.vsphere.vcenter.helper import network_helper
from samples.vsphere.vcenter.helper import vm_placement_helper from samples.vsphere.vcenter.helper import vm_placement_helper
from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm
""" class CreateBasicVM(object):
Demonstrates how to create a basic VM with following configuration:
2 disks, 1 nic
Sample Prerequisites:
- datacenter
- vm folder
- datastore
- standard switch network
"""
stub_config = None
cleardata = False
vm_name = None
def setup(context=None):
global stub_config, cleardata, vm_name
if context:
# Run sample suite via setup script
vm_name = testbed.config['VM_NAME_BASIC']
stub_config = context.stub_config
else:
# Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_BASIC'])
stub_config = vapiconnect.connect(server,
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
# Get a placement spec
datacenter_name = testbed.config['VM_DATACENTER_NAME']
vm_folder_name = testbed.config['VM_FOLDER2_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME']
std_portgroup_name = testbed.config['STDPORTGROUP_NAME']
placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
stub_config,
datacenter_name,
vm_folder_name,
datastore_name)
# Get a standard network backing
standard_network = network_helper.get_standard_network_backing(
stub_config,
std_portgroup_name,
datacenter_name)
create_basic_vm(stub_config, placement_spec, standard_network)
def create_basic_vm(stub_config, placement_spec, standard_network):
""" """
Create a basic VM. Demonstrates how to create a basic VM with following configuration:
2 disks, 1 nic
Using the provided PlacementSpec, create a VM with a selected Guest OS Sample Prerequisites:
and provided name. - datacenter
- vm folder
Create a VM with the following configuration: - datastore
* Create 2 disks and specify one of them on scsi0:0 since it's the boot disk - standard switch network
* Specify 1 ethernet adapter using a Standard Portgroup backing
* Setup for PXE install by selecting network as first boot device
Use guest and system provided defaults for most configuration settings.
""" """
guest_os = testbed.config['VM_GUESTOS']
boot_disk = Disk.CreateSpec(type=Disk.HostBusAdapterType.SCSI, def __init__(self, stub_config=None, placement_spec=None):
scsi=ScsiAddressSpec(bus=0, unit=0), self.context = None
new_vmdk=Disk.VmdkCreateSpec()) self.service_manager = None
data_disk = Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec()) self.stub_config = stub_config
self.placement_spec = placement_spec
self.vm_name = testbed.config['VM_NAME_BASIC']
self.cleardata = None
nic = Ethernet.CreateSpec( def setup(self):
start_connected=True, parser = sample_cli.build_arg_parser()
backing=Ethernet.BackingSpec( parser.add_argument('-n', '--vm_name',
type=Ethernet.BackingType.STANDARD_PORTGROUP, action='store',
network=standard_network)) help='Name of the testing vm')
args = sample_util.process_cli_args(parser.parse_args())
if args.vm_name:
self.vm_name = args.vm_name
self.cleardata = args.cleardata
# TODO Should DISK be put before ETHERNET? Does the BIOS automatically try self.service_manager = ServiceManager(args.server,
# the next device if the DISK is empty? args.username,
boot_device_order = [BootDevice.EntryCreateSpec(BootDevice.Type.ETHERNET), args.password,
BootDevice.EntryCreateSpec(BootDevice.Type.DISK)] args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
vm_create_spec = VM.CreateSpec(name=vm_name, self.stub_config = self.service_manager.stub_config
guest_os=guest_os,
placement=placement_spec,
disks=[boot_disk, data_disk],
nics=[nic],
boot_devices=boot_device_order)
print('\n# Example: create_basic_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(stub_config) def run(self):
vm = vm_svc.create(vm_create_spec) # Get a placement spec
datacenter_name = testbed.config['VM_DATACENTER_NAME']
vm_folder_name = testbed.config['VM_FOLDER2_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME']
std_portgroup_name = testbed.config['STDPORTGROUP_NAME']
print("create_basic_vm: Created VM '{}' ({})".format(vm_name, vm)) if not self.placement_spec:
self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
self.stub_config,
datacenter_name,
vm_folder_name,
datastore_name)
vm_info = vm_svc.get(vm) # Get a standard network backing
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) standard_network = network_helper.get_standard_network_backing(
self.stub_config,
std_portgroup_name,
datacenter_name)
return vm """
Create a basic VM.
Using the provided PlacementSpec, create a VM with a selected Guest OS
and provided name.
def cleanup(): Create a VM with the following configuration:
vm = get_vm(stub_config, vm_name) * Create 2 disks and specify one of them on scsi0:0 since it's the boot disk
if vm: * Specify 1 ethernet adapter using a Standard Portgroup backing
power_svc = Power(stub_config) * Setup for PXE install by selecting network as first boot device
vm_svc = VM(stub_config)
state = power_svc.get(vm) Use guest and system provided defaults for most configuration settings.
if state == Power.Info(state=Power.State.POWERED_ON): """
power_svc.stop(vm) guest_os = testbed.config['VM_GUESTOS']
elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm) boot_disk = Disk.CreateSpec(type=Disk.HostBusAdapterType.SCSI,
power_svc.stop(vm) scsi=ScsiAddressSpec(bus=0, unit=0),
print("Deleting VM '{}' ({})".format(vm_name, vm)) new_vmdk=Disk.VmdkCreateSpec())
vm_svc.delete(vm) data_disk = Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec())
nic = Ethernet.CreateSpec(
start_connected=True,
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=standard_network))
boot_device_order = [
BootDevice.EntryCreateSpec(BootDevice.Type.ETHERNET),
BootDevice.EntryCreateSpec(BootDevice.Type.DISK)]
vm_create_spec = VM.CreateSpec(name=self.vm_name,
guest_os=guest_os,
placement=self.placement_spec,
disks=[boot_disk, data_disk],
nics=[nic],
boot_devices=boot_device_order)
print('\n# Example: create_basic_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(self.stub_config)
vm = vm_svc.create(vm_create_spec)
print("create_basic_vm: Created VM '{}' ({})".format(self.vm_name, vm))
vm_info = vm_svc.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm
def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name)
if vm:
power_svc = Power(self.stub_config)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm)
power_svc.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm)
def main(): def main():
setup() create_basic_vm = CreateBasicVM()
cleanup() create_basic_vm.setup()
run() create_basic_vm.cleanup()
if cleardata: create_basic_vm.run()
cleanup() if create_basic_vm.cleardata:
create_basic_vm.cleanup()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -19,107 +19,112 @@ __vcenter_version__ = '6.5+'
import atexit import atexit
from com.vmware.vcenter.vm_client import Power from com.vmware.vcenter.vm_client import (Power)
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.vcenter.helper import vm_placement_helper from samples.vsphere.vcenter.helper import vm_placement_helper
from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm
""" class CreateDefaultVM(object):
Demonstrates how to create a VM with system provided defaults
Sample Prerequisites:
- datacenter
- vm folder
- datastore
"""
stub_config = None
cleardata = False
vm_name = None
def setup(context=None):
global stub_config, cleardata, vm_name
if context:
# Run sample suite via setup script
vm_name = testbed.config['VM_NAME_DEFAULT']
stub_config = context.stub_config
else:
# Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_DEFAULT'])
stub_config = vapiconnect.connect(server,
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
# Get a placement spec
datacenter_name = testbed.config['VM_DATACENTER_NAME']
vm_folder_name = testbed.config['VM_FOLDER2_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME']
placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
stub_config,
datacenter_name,
vm_folder_name,
datastore_name)
# Create the VMs
create_default_vm(stub_config, placement_spec)
def create_default_vm(stub_config, placement_spec):
""" """
Create a default VM. Demonstrates how to create a VM with system provided defaults
Using the provided PlacementSpec, create a VM with a selected Guest OS Sample Prerequisites:
and provided name. Use all the guest and system provided defaults. - datacenter
- vm folder
- datastore
""" """
guest_os = testbed.config['VM_GUESTOS']
vm_create_spec = VM.CreateSpec(name=vm_name,
guest_os=guest_os,
placement=placement_spec)
print('\n# Example: create_default_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(stub_config) def __init__(self, stub_config=None, placement_spec=None):
vm = vm_svc.create(vm_create_spec) self.context = None
print("create_default_vm: Created VM '{}' ({})".format(vm_name, vm)) self.service_manager = None
self.stub_config = stub_config
self.placement_spec = placement_spec
self.vm_name = testbed.config['VM_NAME_DEFAULT']
self.cleardata = None
vm_info = vm_svc.get(vm) def setup(self):
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) parser = sample_cli.build_arg_parser()
return vm parser.add_argument('-n', '--vm_name',
action='store',
help='Name of the testing vm')
args = sample_util.process_cli_args(parser.parse_args())
if args.vm_name:
self.vm_name = args.vm_name
self.cleardata = args.cleardata
self.service_manager = ServiceManager(args.server,
args.username,
args.password,
args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
def cleanup(): self.stub_config = self.service_manager.stub_config
vm = get_vm(stub_config, vm_name)
if vm: def run(self):
power_svc = Power(stub_config) # Get a placement spec
vm_svc = VM(stub_config) datacenter_name = testbed.config['VM_DATACENTER_NAME']
state = power_svc.get(vm) vm_folder_name = testbed.config['VM_FOLDER2_NAME']
if state == Power.Info(state=Power.State.POWERED_ON): datastore_name = testbed.config['VM_DATASTORE_NAME']
power_svc.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED): if not self.placement_spec:
power_svc.start(vm) self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
power_svc.stop(vm) self.stub_config,
print("Deleting VM '{}' ({})".format(vm_name, vm)) datacenter_name,
vm_svc.delete(vm) vm_folder_name,
datastore_name)
"""
Create a default VM.
Using the provided PlacementSpec, create a VM with a selected Guest OS
and provided name. Use all the guest and system provided defaults.
"""
guest_os = testbed.config['VM_GUESTOS']
vm_create_spec = VM.CreateSpec(name=self.vm_name,
guest_os=guest_os,
placement=self.placement_spec)
print('\n# Example: create_default_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(self.stub_config)
vm = vm_svc.create(vm_create_spec)
print("create_default_vm: Created VM '{}' ({})".format(self.vm_name, vm))
vm_info = vm_svc.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm
def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name)
if vm:
power_svc = Power(self.stub_config)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm)
power_svc.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm)
def main(): def main():
setup() create_default_vm = CreateDefaultVM()
cleanup() create_default_vm.setup()
run() create_default_vm.cleanup()
if cleardata: create_default_vm.run()
cleanup() if create_default_vm.cleardata:
create_default_vm.cleanup()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -25,231 +25,242 @@ from com.vmware.vcenter.vm.hardware_client import (
from com.vmware.vcenter.vm.hardware_client import ScsiAddressSpec from com.vmware.vcenter.vm.hardware_client import ScsiAddressSpec
from com.vmware.vcenter.vm_client import (Hardware, Power) from com.vmware.vcenter.vm_client import (Hardware, Power)
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.vcenter.helper import network_helper from samples.vsphere.vcenter.helper import network_helper
from samples.vsphere.vcenter.helper import vm_placement_helper from samples.vsphere.vcenter.helper import vm_placement_helper
from samples.vsphere.vcenter.helper.vm_helper import get_vm
from samples.vsphere.vcenter.setup import testbed from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.helper.vm_helper import get_vm
""" class CreateExhaustiveVM(object):
Demonstrates how to create a exhaustive VM with the below configuration:
3 disks, 2 nics, 2 vcpu, 2 GB, memory, boot=BIOS, 1 cdrom, 1 serial port,
1 parallel port, 1 floppy, boot_device=[CDROM, DISK, ETHERNET])
Sample Prerequisites:
- datacenter
- vm folder
- resource pool
- datastore
- standard switch network
- distributed switch network
- An iso file on the datastore mentioned above
"""
stub_config = None
cleardata = False
vm_name = None
def setup(context=None):
global stub_config, cleardata, vm_name
if context:
# Run sample suite via setup script
vm_name = testbed.config['VM_NAME_EXHAUSTIVE']
stub_config = context.stub_config
else:
# Run sample in standalone mode
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(testbed.config['VM_NAME_EXHAUSTIVE'])
stub_config = vapiconnect.connect(server,
username,
password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
# Get a placement spec
datacenter_name = testbed.config['VM_DATACENTER_NAME']
vm_folder_name = testbed.config['VM_FOLDER2_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME']
std_portgroup_name = testbed.config['STDPORTGROUP_NAME']
dv_portgroup_name = testbed.config['VDPORTGROUP1_NAME']
placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
stub_config,
datacenter_name,
vm_folder_name,
datastore_name)
# Get a standard network backing
standard_network = network_helper.get_standard_network_backing(
stub_config,
std_portgroup_name,
datacenter_name)
# Get a distributed network backing
distributed_network = network_helper.get_distributed_network_backing(
stub_config,
dv_portgroup_name,
datacenter_name)
create_exhaustive_vm(stub_config, placement_spec, standard_network,
distributed_network)
def create_exhaustive_vm(stub_config, placement_spec, standard_network,
distributed_network):
""" """
Create an exhaustive VM. Demonstrates how to create a exhaustive VM with the below configuration:
3 disks, 2 nics, 2 vcpu, 2 GB, memory, boot=BIOS, 1 cdrom, 1 serial port,
1 parallel port, 1 floppy, boot_device=[CDROM, DISK, ETHERNET])
Using the provided PlacementSpec, create a VM with a selected Guest OS Sample Prerequisites:
and provided name. - datacenter
- vm folder
Create a VM with the following configuration: - resource pool
* Hardware Version = VMX_11 (for 6.0) - datastore
* CPU (count = 2, coresPerSocket = 2, hotAddEnabled = false, - standard switch network
hotRemoveEnabled = false) - distributed switch network
* Memory (size_mib = 2 GB, hotAddEnabled = false) - An iso file on the datastore mentioned above
* 3 Disks and specify each of the HBAs and the unit numbers
* (capacity=40 GB, name=<some value>, spaceEfficient=true)
* Specify 2 ethernet adapters, one using a Standard Portgroup backing and
the
other using a DISTRIBUTED_PORTGROUP networking backing.
* nic1: Specify Ethernet (macType=MANUAL, macAddress=<some value>)
* nic2: Specify Ethernet (macType=GENERATED)
* 1 CDROM (type=ISO_FILE, file="os.iso", startConnected=true)
* 1 Serial Port (type=NETWORK_SERVER, file="tcp://localhost/16000",
startConnected=true)
* 1 Parallel Port (type=HOST_DEVICE, startConnected=false)
* 1 Floppy Drive (type=CLIENT_DEVICE)
* Boot, type=BIOS
* BootDevice order: CDROM, DISK, ETHERNET
Use guest and system provided defaults for remaining configuration settings.
""" """
guest_os = testbed.config['VM_GUESTOS']
iso_datastore_path = testbed.config['ISO_DATASTORE_PATH']
serial_port_network_location = \
testbed.config['SERIAL_PORT_NETWORK_SERVER_LOCATION']
GiB = 1024 * 1024 * 1024 def __init__(self, stub_config=None, placement_spec=None,
GiBMemory = 1024 standard_network=None, distributed_network=None):
self.context = None
self.service_manager = None
self.stub_config = stub_config
self.placement_spec = placement_spec
self.standard_network = standard_network
self.distributed_network = distributed_network
self.vm_name = testbed.config['VM_NAME_EXHAUSTIVE']
self.cleardata = None
vm_create_spec = VM.CreateSpec( def setup(self):
guest_os=guest_os, parser = sample_cli.build_arg_parser()
name=vm_name, parser.add_argument('-n', '--vm_name',
placement=placement_spec, action='store',
hardware_version=Hardware.Version.VMX_11, help='Name of the testing vm')
cpu=Cpu.UpdateSpec(count=2, args = sample_util.process_cli_args(parser.parse_args())
cores_per_socket=1, if args.vm_name:
hot_add_enabled=False, self.vm_name = args.vm_name
hot_remove_enabled=False), self.cleardata = args.cleardata
memory=Memory.UpdateSpec(size_mib=2 * GiBMemory,
hot_add_enabled=False),
disks=[
Disk.CreateSpec(type=Disk.HostBusAdapterType.SCSI,
scsi=ScsiAddressSpec(bus=0, unit=0),
new_vmdk=Disk.VmdkCreateSpec(name='boot',
capacity=40 * GiB)),
Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec(name='data1',
capacity=10 * GiB)),
Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec(name='data2',
capacity=10 * GiB))
],
nics=[
Ethernet.CreateSpec(
start_connected=True,
mac_type=Ethernet.MacAddressType.MANUAL,
mac_address='11:23:58:13:21:34',
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=standard_network)),
Ethernet.CreateSpec(
start_connected=True,
mac_type=Ethernet.MacAddressType.GENERATED,
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP,
network=distributed_network)),
],
cdroms=[
Cdrom.CreateSpec(
start_connected=True,
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.ISO_FILE,
iso_file=iso_datastore_path)
)
],
serial_ports=[
Serial.CreateSpec(
start_connected=False,
backing=Serial.BackingSpec(
type=Serial.BackingType.NETWORK_SERVER,
network_location=serial_port_network_location)
)
],
parallel_ports=[
Parallel.CreateSpec(
start_connected=False,
backing=Parallel.BackingSpec(
type=Parallel.BackingType.HOST_DEVICE)
)
],
floppies=[
Floppy.CreateSpec(
backing=Floppy.BackingSpec(
type=Floppy.BackingType.CLIENT_DEVICE)
)
],
boot=Boot.CreateSpec(type=Boot.Type.BIOS,
delay=0,
enter_setup_mode=False
),
# TODO Should DISK be put before CDROM and ETHERNET? Does the BIOS
# automatically try the next device if the DISK is empty?
boot_devices=[
BootDevice.EntryCreateSpec(BootDevice.Type.CDROM),
BootDevice.EntryCreateSpec(BootDevice.Type.DISK),
BootDevice.EntryCreateSpec(BootDevice.Type.ETHERNET)
]
)
print('# Example: create_exhaustive_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(stub_config) self.service_manager = ServiceManager(args.server,
vm = vm_svc.create(vm_create_spec) args.username,
args.password,
args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
print("create_exhaustive_vm: Created VM '{}' ({})".format(vm_name, vm)) self.stub_config = self.service_manager.stub_config
vm_info = vm_svc.get(vm) def run(self):
print('vm.get({}) -> {}'.format(vm, pp(vm_info))) # Get a placement spec
datacenter_name = testbed.config['VM_DATACENTER_NAME']
vm_folder_name = testbed.config['VM_FOLDER2_NAME']
datastore_name = testbed.config['VM_DATASTORE_NAME']
std_portgroup_name = testbed.config['STDPORTGROUP_NAME']
dv_portgroup_name = testbed.config['VDPORTGROUP1_NAME']
return vm if not self.placement_spec:
self.placement_spec = vm_placement_helper.get_placement_spec_for_resource_pool(
self.stub_config,
datacenter_name,
vm_folder_name,
datastore_name)
# Get a standard network backing
if not self.standard_network:
self.standard_network = network_helper.get_standard_network_backing(
self.stub_config,
std_portgroup_name,
datacenter_name)
def cleanup(): # Get a distributed network backing
vm = get_vm(stub_config, vm_name) if not self.distributed_network:
if vm: self.distributed_network = network_helper.get_distributed_network_backing(
power_svc = Power(stub_config) self.stub_config,
vm_svc = VM(stub_config) dv_portgroup_name,
state = power_svc.get(vm) datacenter_name)
if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm) """
elif state == Power.Info(state=Power.State.SUSPENDED): Create an exhaustive VM.
power_svc.start(vm)
power_svc.stop(vm) Using the provided PlacementSpec, create a VM with a selected Guest OS
print("Deleting VM '{}' ({})".format(vm_name, vm)) and provided name.
vm_svc.delete(vm)
Create a VM with the following configuration:
* Hardware Version = VMX_11 (for 6.0)
* CPU (count = 2, coresPerSocket = 2, hotAddEnabled = false,
hotRemoveEnabled = false)
* Memory (size_mib = 2 GB, hotAddEnabled = false)
* 3 Disks and specify each of the HBAs and the unit numbers
* (capacity=40 GB, name=<some value>, spaceEfficient=true)
* Specify 2 ethernet adapters, one using a Standard Portgroup backing and
the
other using a DISTRIBUTED_PORTGROUP networking backing.
* nic1: Specify Ethernet (macType=MANUAL, macAddress=<some value>)
* nic2: Specify Ethernet (macType=GENERATED)
* 1 CDROM (type=ISO_FILE, file="os.iso", startConnected=true)
* 1 Serial Port (type=NETWORK_SERVER, file="tcp://localhost/16000",
startConnected=true)
* 1 Parallel Port (type=HOST_DEVICE, startConnected=false)
* 1 Floppy Drive (type=CLIENT_DEVICE)
* Boot, type=BIOS
* BootDevice order: CDROM, DISK, ETHERNET
Use guest and system provided defaults for remaining configuration settings.
"""
guest_os = testbed.config['VM_GUESTOS']
iso_datastore_path = testbed.config['ISO_DATASTORE_PATH']
serial_port_network_location = \
testbed.config['SERIAL_PORT_NETWORK_SERVER_LOCATION']
GiB = 1024 * 1024 * 1024
GiBMemory = 1024
vm_create_spec = VM.CreateSpec(
guest_os=guest_os,
name=self.vm_name,
placement=self.placement_spec,
hardware_version=Hardware.Version.VMX_11,
cpu=Cpu.UpdateSpec(count=2,
cores_per_socket=1,
hot_add_enabled=False,
hot_remove_enabled=False),
memory=Memory.UpdateSpec(size_mib=2 * GiBMemory,
hot_add_enabled=False),
disks=[
Disk.CreateSpec(type=Disk.HostBusAdapterType.SCSI,
scsi=ScsiAddressSpec(bus=0, unit=0),
new_vmdk=Disk.VmdkCreateSpec(name='boot',
capacity=40 * GiB)),
Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec(name='data1',
capacity=10 * GiB)),
Disk.CreateSpec(new_vmdk=Disk.VmdkCreateSpec(name='data2',
capacity=10 * GiB))
],
nics=[
Ethernet.CreateSpec(
start_connected=True,
mac_type=Ethernet.MacAddressType.MANUAL,
mac_address='11:23:58:13:21:34',
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.STANDARD_PORTGROUP,
network=self.standard_network)),
Ethernet.CreateSpec(
start_connected=True,
mac_type=Ethernet.MacAddressType.GENERATED,
backing=Ethernet.BackingSpec(
type=Ethernet.BackingType.DISTRIBUTED_PORTGROUP,
network=self.distributed_network)),
],
cdroms=[
Cdrom.CreateSpec(
start_connected=True,
backing=Cdrom.BackingSpec(type=Cdrom.BackingType.ISO_FILE,
iso_file=iso_datastore_path)
)
],
serial_ports=[
Serial.CreateSpec(
start_connected=False,
backing=Serial.BackingSpec(
type=Serial.BackingType.NETWORK_SERVER,
network_location=serial_port_network_location)
)
],
parallel_ports=[
Parallel.CreateSpec(
start_connected=False,
backing=Parallel.BackingSpec(
type=Parallel.BackingType.HOST_DEVICE)
)
],
floppies=[
Floppy.CreateSpec(
backing=Floppy.BackingSpec(
type=Floppy.BackingType.CLIENT_DEVICE)
)
],
boot=Boot.CreateSpec(type=Boot.Type.BIOS,
delay=0,
enter_setup_mode=False
),
# TODO Should DISK be put before CDROM and ETHERNET? Does the BIOS
# automatically try the next device if the DISK is empty?
boot_devices=[
BootDevice.EntryCreateSpec(BootDevice.Type.CDROM),
BootDevice.EntryCreateSpec(BootDevice.Type.DISK),
BootDevice.EntryCreateSpec(BootDevice.Type.ETHERNET)
]
)
print(
'# Example: create_exhaustive_vm: Creating a VM using spec\n-----')
print(pp(vm_create_spec))
print('-----')
vm_svc = VM(self.stub_config)
vm = vm_svc.create(vm_create_spec)
print("create_exhaustive_vm: Created VM '{}' ({})".format(self.vm_name,
vm))
vm_info = vm_svc.get(vm)
print('vm.get({}) -> {}'.format(vm, pp(vm_info)))
return vm
def cleanup(self):
vm = get_vm(self.stub_config, self.vm_name)
if vm:
power_svc = Power(self.stub_config)
vm_svc = VM(self.stub_config)
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm)
power_svc.stop(vm)
print("Deleting VM '{}' ({})".format(self.vm_name, vm))
vm_svc.delete(vm)
def main(): def main():
setup() create_exhaustive_vm = CreateExhaustiveVM()
cleanup() create_exhaustive_vm.setup()
run() create_exhaustive_vm.cleanup()
if cleardata: create_exhaustive_vm.run()
cleanup() if create_exhaustive_vm.cleardata:
create_exhaustive_vm.cleanup()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -13,58 +13,73 @@
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
""" """
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+'
import atexit import atexit
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args_vm
from com.vmware.vcenter_client import VM
from com.vmware.vcenter.vm_client import Power from com.vmware.vcenter.vm_client import Power
from com.vmware.vcenter_client import VM
from samples.vsphere.common import sample_cli
from samples.vsphere.common import sample_util
from samples.vsphere.common.service_manager import ServiceManager
from samples.vsphere.vcenter.helper.vm_helper import get_vm from samples.vsphere.vcenter.helper.vm_helper import get_vm
"""
Demonstrates Deleting User specified Virtual Machine (VM)
Sample Prerequisites:
vCenter/ESX
"""
stub_config = None class DeleteVM(object):
vm_name = None
vm = None
def setup(context=None):
global stub_config, vm_name
server, username, password, cleardata, skip_verification, vm_name = \
parse_cli_args_vm(vm_name)
stub_config = vapiconnect.connect(server, username, password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
""" """
Delete User specified VM from Server Demonstrates Deleting User specified Virtual Machine (VM)
Sample Prerequisites:
vCenter/ESX
""" """
global vm
vm_svc = VM(stub_config) def __init__(self):
power_svc = Power(stub_config) self.service_manager = None
vm = get_vm(stub_config, vm_name) self.vm_name = None
if not vm:
raise Exception('Sample requires an existing vm with name ({}).' def setup(self):
'Please create the vm first.'.format(vm_name)) parser = sample_cli.build_arg_parser()
print("Deleting VM -- '{}-({})')".format(vm_name, vm)) parser.add_argument('-n', '--vm_name',
state = power_svc.get(vm) action='store',
if state == Power.Info(state=Power.State.POWERED_ON): default='Sample_Default_VM_for_Simple_Testbed',
power_svc.stop(vm) help='Name of the testing vm')
elif state == Power.Info(state=Power.State.SUSPENDED): args = sample_util.process_cli_args(parser.parse_args())
power_svc.start(vm) self.vm_name = args.vm_name
power_svc.stop(vm)
vm_svc.delete(vm) self.service_manager = ServiceManager(args.server,
print("Deleted VM -- '{}-({})".format(vm_name, vm)) args.username,
args.password,
args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
def run(self):
"""
Delete User specified VM from Server
"""
vm_svc = VM(self.service_manager.stub_config)
power_svc = Power(self.service_manager.stub_config)
vm = get_vm(self.service_manager.stub_config, self.vm_name)
if not vm:
raise Exception('Sample requires an existing vm with name ({}).'
'Please create the vm first.'.format(vm_name))
print("Deleting VM -- '{}-({})')".format(self.vm_name, vm))
state = power_svc.get(vm)
if state == Power.Info(state=Power.State.POWERED_ON):
power_svc.stop(vm)
elif state == Power.Info(state=Power.State.SUSPENDED):
power_svc.start(vm)
power_svc.stop(vm)
vm_svc.delete(vm)
print("Deleted VM -- '{}-({})".format(self.vm_name, vm))
def main(): def main():
setup() delete_vm = DeleteVM()
run() delete_vm.setup()
delete_vm.run()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -13,47 +13,58 @@
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
""" """
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.5+'
import atexit import atexit
from samples.vsphere.common import vapiconnect
from samples.vsphere.common.sample_util import parse_cli_args
from samples.vsphere.common.sample_util import pp
from com.vmware.vcenter_client import VM from com.vmware.vcenter_client import VM
""" from samples.vsphere.common import sample_cli
Demonstrates getting list of VMs present in vCenter from samples.vsphere.common import sample_util
Sample Prerequisites: from samples.vsphere.common.service_manager import ServiceManager
vCenter/ESX from pprint import pprint
"""
stub_config = None
cleardata = False
def setup(context=None): class ListVM(object):
global stub_config, cleardata
server, username, password, cleardata, skip_verification = parse_cli_args()
stub_config = vapiconnect.connect(server, username, password,
skip_verification)
atexit.register(vapiconnect.logout, stub_config)
def run():
""" """
List VMs present in server Demonstrates getting list of VMs present in vCenter
Sample Prerequisites:
vCenter/ESX
""" """
vm_svc = VM(stub_config)
list_of_vms = vm_svc.list() def __init__(self):
print("----------------------------") self.service_manager = None
print("List Of VMs")
print("----------------------------") def setup(self):
for vm in list_of_vms: parser = sample_cli.build_arg_parser()
print('{}'.format(vm)) args = sample_util.process_cli_args(parser.parse_args())
print("----------------------------")
self.service_manager = ServiceManager(args.server,
args.username,
args.password,
args.skipverification)
self.service_manager.connect()
atexit.register(self.service_manager.disconnect)
def run(self):
"""
List VMs present in server
"""
vm_svc = VM(self.service_manager.stub_config)
list_of_vms = vm_svc.list()
print("----------------------------")
print("List Of VMs")
print("----------------------------")
pprint(list_of_vms)
print("----------------------------")
def main(): def main():
setup() list_vm = ListVM()
run() list_vm.setup()
list_vm.run()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -21,122 +21,118 @@ import samples.vsphere.vcenter.vm.placement
import samples.vsphere.vcenter.vm.power import samples.vsphere.vcenter.vm.power
from samples.vsphere.common.sample_util import pp from samples.vsphere.common.sample_util import pp
from samples.vsphere.vcenter.setup import testbed_setup from samples.vsphere.vcenter.setup import testbed_setup
from samples.vsphere.vcenter.vm.create import create_basic_vm from samples.vsphere.vcenter.setup import testbed
from samples.vsphere.vcenter.vm.create import create_default_vm from samples.vsphere.vcenter.vm.create.create_default_vm import CreateDefaultVM
from samples.vsphere.vcenter.vm.create import create_exhaustive_vm from samples.vsphere.vcenter.vm.create.create_basic_vm import CreateBasicVM
from samples.vsphere.vcenter.vm.create.create_exhaustive_vm import \
CreateExhaustiveVM
def setup(context): class VMSetup(object):
print('Setup Samples Started') def __init__(self, context=None):
create_default_vm.setup(context) self.context = context
create_basic_vm.setup(context) self.basic_vm = None
create_exhaustive_vm.setup(context) self.default_vm = None
print('Setup Samples Complete') self.exhaustive_vm = None
def setup(self, context):
print('Setup Samples Started')
def cleanup(context): self.context = context
setup(context)
print('Cleanup Samples Started') ###########################################################################
create_default_vm.cleanup() # Getting a PlacementSpec
create_basic_vm.cleanup() ###########################################################################
create_exhaustive_vm.cleanup() placement_spec = samples.vsphere.vcenter.vm.placement.get_placement_spec_for_resource_pool(context)
print('Cleanup Samples Complete\n') print('=' * 79)
print('= Resource selection')
print('=' * 79)
print('placement_spec={}'.format(pp(placement_spec)))
###########################################################################
# Getting a Network
# Choose one of the following ways to get the PlacementSpec
# 1. STANDARD_PORTGROUP on DATACENTER2
# 2. DISTRIBUTED_PORTGROUP on DATACENTER2
###########################################################################
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))
def validate(context): distributed_network = samples.vsphere.vcenter.helper \
print('Validating and Detecting Resources in vcenter.vm Samples') .network_helper.get_distributed_network_backing(
r = testbed_setup.validate(context) context.stub_config,
if r: context.testbed.config['VDPORTGROUP1_NAME'],
print('==> Samples Setup validated') context.testbed.config['VM_DATACENTER_NAME'])
return True print('distributed_network={}'.format(distributed_network))
else:
print('==> Samples Setup has errors')
return False
print('=' * 79)
def run(context): self.default_vm = CreateDefaultVM(context.stub_config,
# Clean up in case of past failures placement_spec)
cleanup(context) self.basic_vm = CreateBasicVM(context.stub_config, placement_spec)
self.exhaustive_vm = CreateExhaustiveVM(context.stub_config,
placement_spec,
standard_network,
distributed_network)
# Check that sample is ready to run print('Setup Samples Complete')
if context.option['DO_SAMPLES']:
if not validate(context):
exit(0)
########################################################################### def cleanup(self):
# Getting a PlacementSpec
###########################################################################
placement_spec = samples.vsphere.vcenter.vm.placement \
.get_placement_spec_for_resource_pool(context)
print('=' * 79)
print('= Resource selection')
print('=' * 79)
print('placement_spec={}'.format(pp(placement_spec)))
########################################################################### print('Cleanup Samples Started')
# Getting a Network CreateDefaultVM(self.context.stub_config).cleanup()
# Choose one of the following ways to get the PlacementSpec CreateBasicVM(self.context.stub_config).cleanup()
# 1. STANDARD_PORTGROUP on DATACENTER2 CreateExhaustiveVM(self.context.stub_config).cleanup()
# 2. DISTRIBUTED_PORTGROUP on DATACENTER2 print('Cleanup Samples Complete\n')
###########################################################################
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 \ def validate(self):
.network_helper.get_distributed_network_backing( print('Validating and Detecting Resources in vcenter.vm Samples')
context.stub_config, r = testbed_setup.validate(self.context)
context.testbed.config['VDPORTGROUP1_NAME'], if r:
context.testbed.config['VM_DATACENTER_NAME']) print('==> Samples Setup validated')
print('distributed_network={}'.format(distributed_network)) return True
else:
print('==> Samples Setup has errors')
return False
print('=' * 79) def run(self):
# Clean up in case of past failures
self.cleanup()
########################################################################### # Check that sample is ready to run
# Create VM samples if self.context.option['DO_SAMPLES']:
# if not self.validate():
# Choose one of the following ways to create the VM exit(0)
# 1. Default
# 2. Basic (2 disks, 1 nic)
# 3. Exhaustive (3 disks, 2 nics, 2 vcpu, 2 GB memory, boot=BIOS, 1 cdrom,
# 1 serial port, 1 parallel port, 1 floppy,
# boot_devices= [CDROM, DISK, ETHERNET])
###########################################################################
create_default_vm.create_default_vm(context.stub_config, placement_spec)
create_basic_vm.create_basic_vm(context.stub_config,
placement_spec,
standard_network)
create_exhaustive_vm.create_exhaustive_vm(context.stub_config,
placement_spec,
standard_network,
distributed_network)
########################################################################### ###########################################################################
# Power operation samples # Create VM samples
# #
# Runs through the power lifecycle for the VM: start, suspend, # Choose one of the following ways to create the VM
# resume (start), stop # 1. Default
# # 2. Basic (2 disks, 1 nic)
########################################################################### # 3. Exhaustive (3 disks, 2 nics, 2 vcpu, 2 GB memory, boot=BIOS, 1 cdrom,
samples.vsphere.vcenter.vm.power.setup(context) # 1 serial port, 1 parallel port, 1 floppy,
samples.vsphere.vcenter.vm.power.run() # boot_devices= [CDROM, DISK, ETHERNET])
samples.vsphere.vcenter.vm.power.cleanup() ###########################################################################
self.default_vm.run()
self.basic_vm.run()
self.exhaustive_vm.run()
########################################################################### ###########################################################################
# Incremental device CRUDE + connect/disconnect samples # Incremental device CRUDE + connect/disconnect samples
# #
########################################################################### ###########################################################################
if context.option['DO_SAMPLES_INCREMENTAL']: if self.context.option['DO_SAMPLES_INCREMENTAL']:
samples.vsphere.vcenter.vm.hardware.main.setup(context) samples.vsphere.vcenter.vm.hardware.main.setup(self.context)
samples.vsphere.vcenter.vm.hardware.main.validate(context) samples.vsphere.vcenter.vm.hardware.main.validate(self.context)
samples.vsphere.vcenter.vm.hardware.main.run() samples.vsphere.vcenter.vm.hardware.main.run()
if context.option['DO_SAMPLES_CLEANUP']: if self.context.option['DO_SAMPLES_CLEANUP']:
samples.vsphere.vcenter.vm.hardware.main.cleanup() samples.vsphere.vcenter.vm.hardware.main.cleanup()
# Sample cleanup # Sample cleanup
if context.option['DO_SAMPLES_CLEANUP']: if self.context.option['DO_SAMPLES_CLEANUP']:
cleanup(context) self.cleanup()