Skip to content

Commit 8503fcd

Browse files
authored
Merge pull request #30 from tianhao64/master
Improve sample code
2 parents 47e6c61 + abe05ec commit 8503fcd

File tree

13 files changed

+769
-733
lines changed

13 files changed

+769
-733
lines changed

sample_template/sample_template.py

Lines changed: 30 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,12 @@
1919
import atexit
2020

2121
from com.vmware.vcenter_client import VM
22-
from samples.vsphere.common.sample_util import parse_cli_args
22+
from samples.vsphere.common import sample_cli
23+
from samples.vsphere.common import sample_util
2324
from samples.vsphere.common.service_manager import ServiceManager
2425

2526

26-
class Sample:
27+
class Sample(object):
2728
"""
2829
TODO: Sample description and prerequisites.
2930
e.g. Demonstrates getting list of VMs present in vCenter
@@ -33,40 +34,44 @@ class Sample:
3334
"""
3435

3536
def __init__(self):
36-
self.vm_service = None # Service used by the sample code.
37-
self.stub_config = None
38-
self.si = None
37+
self.service_manager = None
38+
self.vm_name = None
3939
self.cleardata = None
4040

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

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

54-
# Get the vAPI stub
55-
self.stub_config = service_manager.stub_config
56-
self.vm_service = VM(self.stub_config)
52+
args = sample_util.process_cli_args(parser.parse_args())
53+
self.vm_name = args.vm_name
54+
self.cleardata = args.cleardata
5755

58-
# Get VIM service instance (pyVmomi)
59-
self.si = service_manager.si
56+
# Connect to both Vim and vAPI services
57+
self.service_manager = ServiceManager(args.server,
58+
args.username,
59+
args.password,
60+
args.skipverification)
61+
self.service_manager.connect()
62+
atexit.register(self.service_manager.disconnect)
6063

6164
def run(self):
62-
# TODO add steps to demo your API
65+
# TODO add your sample code here
6366

64-
# Using vAPI services
65-
vms = self.vm_service.list()
67+
# Using REST API service
68+
vm_service = VM(self.service_manager.stub_config)
69+
filter_spec = VM.FilterSpec(names=set([self.vm_name]))
70+
vms = vm_service.list(filter_spec)
6671
print(vms)
6772

68-
# Using vim services
69-
current_time = self.si.CurrentTime()
73+
# Using Vim API service (pyVmomi)
74+
current_time = self.service_manager.si.CurrentTime()
7075
print(current_time)
7176

7277
def cleanup(self):

samples/vsphere/common/sample_cli.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def build_arg_parser():
2525
-u username
2626
-p password
2727
-c cleanup
28-
-v skip_verification
28+
-v skipverification
2929
3030
"""
3131
parser = argparse.ArgumentParser(
@@ -43,7 +43,7 @@ def build_arg_parser():
4343
action='store',
4444
help='Password to use when connecting to vc')
4545

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

samples/vsphere/common/sample_util.py

Lines changed: 18 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,6 @@ def pp(value):
2828
return output.getvalue()
2929

3030

31-
def parse_cli_args():
32-
"""
33-
Parse the server IP and credential used by samples.
34-
Use values from command line arguments if present, otherwise use values
35-
from testbed.py
36-
"""
37-
# parse command line
38-
parser = sample_cli.build_arg_parser()
39-
args = parser.parse_args()
40-
return process_cli_args(args)
41-
42-
4331
def parse_cli_args_vm(vm_name):
4432
"""
4533
Parse the server IP, credential and vm name used by vcenter vm samples.
@@ -51,10 +39,7 @@ def parse_cli_args_vm(vm_name):
5139
parser.add_argument('-n', '--vm_name',
5240
action='store',
5341
help='Name of the testing vm')
54-
args = parser.parse_args()
55-
56-
server, username, password, cleardata, skip_verification = \
57-
process_cli_args(args)
42+
args = process_cli_args(parser.parse_args())
5843

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

67-
return server, username, password, cleardata, skip_verification, vm_name
52+
return args.server, args.username, args.password, args.cleardata, \
53+
args.skipverification, vm_name
6854

6955

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

75-
if args.server:
76-
server = args.server
77-
else:
64+
if not args.server:
7865
print("Using vcenter server specified in testbed.py")
79-
server = testbed.config['SERVER']
80-
if not server:
66+
args.server = testbed.config['SERVER']
67+
if not args.server:
8168
raise Exception("vcenter server is required")
82-
print("vcenter server = {}".format(server))
69+
print("vcenter server = {}".format(args.server))
8370

84-
if args.username:
85-
username = args.username
86-
else:
71+
if not args.username:
8772
print("Using vc user specified in testbed.py")
88-
username = testbed.config['USERNAME']
89-
if not username:
73+
args.username = testbed.config['USERNAME']
74+
if not args.username:
9075
raise Exception("vc username is required")
91-
print("vc username = {}".format(username))
76+
print("vc username = {}".format(args.username))
9277

93-
if args.password:
94-
password = args.password
95-
else:
78+
if not args.password:
9679
print("Using vc password specified in testbed.py")
97-
password = testbed.config['PASSWORD']
98-
99-
cleardata = args.cleanup
100-
print("sample cleanup = {}".format(cleardata))
101-
102-
skip_verification = args.skipverification
103-
print("skip server cert verification = {}".format(skip_verification))
80+
args.password = testbed.config['PASSWORD']
10481

105-
return server, username, password, cleardata, skip_verification
82+
return args
10683

10784

10885
class Context(object):

samples/vsphere/contentlibrary/ovfdeploy/deploy_ovf_template.py

Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,30 @@
2222
except ImportError:
2323
import urllib.request as urllib2
2424

25+
import atexit
26+
2527
from com.vmware.content.library_client import Item
2628
from com.vmware.vcenter.ovf_client import LibraryItem
2729
from pyVmomi import vim
2830

31+
from samples.vsphere.common import sample_cli
32+
from samples.vsphere.common import sample_util
2933
from samples.vsphere.common.id_generator import generate_random_uuid
30-
from samples.vsphere.common.sample_base import SampleBase
34+
from samples.vsphere.common.service_manager import ServiceManager
3135
from samples.vsphere.common.vim.helpers.vim_utils import (
3236
get_obj, get_obj_by_moId, poweron_vm, poweroff_vm, delete_object)
3337
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
3438
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper
3539

3640

37-
class DeployOvfTemplate(SampleBase):
41+
class DeployOvfTemplate:
3842
"""
3943
Demonstrates the workflow to deploy an OVF library item to a resource pool.
4044
Note: the sample needs an existing library item with an OVF template
4145
and an existing cluster with resources for deploying the VM.
4246
"""
4347

4448
def __init__(self):
45-
SampleBase.__init__(self, self.__doc__)
4649
self.servicemanager = None
4750
self.client = None
4851
self.helper = None
@@ -51,29 +54,37 @@ def __init__(self):
5154
self.vm_obj = None
5255
self.vm_name = None
5356

54-
def _options(self):
55-
self.argparser.add_argument('-clustername',
56-
'--clustername',
57-
help='The name of the cluster to be used.')
58-
self.argparser.add_argument('-libitemname',
59-
'--libitemname',
60-
help='The name of the library item to deploy.'
61-
'The library item should contain an OVF package.')
62-
63-
def _setup(self):
64-
self.cluster_name = self.args.clustername
65-
assert self.cluster_name is not None
57+
def setup(self):
58+
parser = sample_cli.build_arg_parser()
59+
parser.add_argument('-n', '--vm_name',
60+
action='store',
61+
help='Name of the testing vm')
62+
parser.add_argument('-clustername',
63+
'--clustername',
64+
help='The name of the cluster to be used.')
65+
parser.add_argument('-libitemname',
66+
'--libitemname',
67+
help='The name of the library item to deploy.'
68+
'The library item should contain an OVF package.')
69+
args = sample_util.process_cli_args(parser.parse_args())
70+
self.lib_item_name = args.libitemname
71+
self.cluster_name = args.clustername
72+
self.vm_name = args.vm_name
73+
74+
self.servicemanager = ServiceManager(args.server,
75+
args.username,
76+
args.password,
77+
args.skipverification)
78+
self.servicemanager.connect()
79+
atexit.register(self.servicemanager.disconnect)
6680

67-
self.lib_item_name = self.args.libitemname
68-
assert self.lib_item_name is not None
69-
70-
self.servicemanager = self.get_service_manager()
7181
self.client = ClsApiClient(self.servicemanager)
72-
self.helper = ClsApiHelper(self.client, self.skip_verification)
82+
self.helper = ClsApiHelper(self.client, args.skipverification)
83+
7384
# Default VM name
7485
self.vm_name = 'vm-' + str(generate_random_uuid())
7586

76-
def _execute(self):
87+
def execute(self):
7788

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

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

152163
def main():
153164
deploy_ovf_sample = DeployOvfTemplate()
154-
deploy_ovf_sample.main()
165+
deploy_ovf_sample.setup()
166+
deploy_ovf_sample.execute()
167+
deploy_ovf_sample.cleanup()
155168

156169

157170
if __name__ == '__main__':

samples/vsphere/sso/embedded_psc_sso_workflow.py

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,19 @@
1717
__copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.'
1818
__vcenter_version__ = '6.0+'
1919

20-
from pprint import pprint
2120
import requests
22-
21+
from com.vmware.cis.tagging_client import (Category, CategoryModel)
2322
from com.vmware.cis_client import Session
2423
from vmware.vapi.lib.connect import get_requests_connector
2524
from vmware.vapi.security.session import create_session_security_context
2625
from vmware.vapi.security.sso import create_saml_bearer_security_context
2726
from vmware.vapi.stdlib.client.factories import StubConfigurationFactory
28-
from com.vmware.cis.tagging_client import (Category, CategoryModel)
2927

28+
from samples.vsphere.common import sample_cli
29+
from samples.vsphere.common import sample_util
30+
from samples.vsphere.common import sso
3031
from samples.vsphere.common.ssl_helper import get_unverified_context
3132
from samples.vsphere.common.vapiconnect import create_unverified_session
32-
from samples.vsphere.common.sample_util import parse_cli_args
33-
from samples.vsphere.common import sso
3433

3534

3635
class EmbeddedPscSsoWorkflow(object):
@@ -40,37 +39,34 @@ class EmbeddedPscSsoWorkflow(object):
4039
"""
4140

4241
def __init__(self):
43-
self.server = None
44-
self.username = None
45-
self.password = None
42+
self.args = None
4643
self.session = None
4744
self.session_id = None
48-
self.skip_verification = False
4945
self.category_svc = None
5046
self.category_id = None
5147

5248
def setup(self):
53-
self.server, self.username, self.password, _, self.skip_verification = \
54-
parse_cli_args()
49+
parser = sample_cli.build_arg_parser()
50+
self.args = sample_util.process_cli_args(parser.parse_args())
5551

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

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

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

6763
authenticator = sso.SsoAuthenticator(ssoUrl)
6864
context = None
69-
if self.skip_verification:
65+
if self.args.skipverification:
7066
context = get_unverified_context()
7167
bearer_token = authenticator.get_bearer_saml_assertion(
72-
self.username,
73-
self.password,
68+
self.args.username,
69+
self.args.password,
7470
delegatable=True,
7571
ssl_context=context)
7672

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

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

8682
# Create an authenticated stub configuration object that can be used to
8783
# issue requests against vCenter.
8884
session = requests.Session()
89-
if self.skip_verification:
85+
if self.args.skipverification:
9086
session = create_unverified_session(session)
9187
connector = get_requests_connector(session=session, url=vapi_url)
9288
connector.set_security_context(sec_ctx)

0 commit comments

Comments
 (0)